本文介绍了C中的有效除法/余数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在这个NG中我找不到任何关于这个问题的讨论。 我想在C中实现一些可变精度整数运算, 并高效地完成。划分/余数 操作出现问题。我在x86上使用gcc,但我说的很多内容适用于 其他架构。 首先,我假设div和ldiv函数使用/和%(显然它取决于编译器和 优化的级别,显然它取决于一个操作而不是两个)。 但是,div和ldiv需要商,除数, 股息和余数的长度都是相同的。现在我已经在机器语言级别工作的所有机器(相当一部分) 实现整数除法,股息是两倍长作为 除数,商和余数。而且,这就是多重精度算术中出现的自然价值,你获得两倍的红利,就像其他一切一样。所以假设我使用16位除数, 商和余数,但32位红利。如果我用 汇编语言编写,我会使用将16位 除以32的指令。 但是当我用C语言编写,我被迫使用ldiv函数,因为一个操作数的是32位。 (让我们说我的机器上的int = 16位和long = 32位,因为 。)然后编译器必须实现这个ldiv函数 by使用将32位除以64位的指令,因为 除数现在是32位。换句话说,编译后的代码被强制使用一个除法指令,其操作数是所需数量的两倍,因为div和ldiv函数的设计是 。 br /> 任何人都知道解决这个问题(除了在我的C程序中插入汇编代码)? 谢谢提前...... 解决方案 我假设的跳跃我被迫似乎是一个有风险的人。你的测量结果是什么? 效率为/,%,/和%,和ldiv? 你*有*测量,避风港'不是吗? HAVEN''TYYY ???? - 呃********* @ sun.com 只需使用/和%。 I can''t find any discussion of this question in this NG.I''d like to implement some variable precision integer arithmetic in C,and do it efficiently. A problem arises with the divide/remainderoperations. I''m using gcc on x86, but a lot of what I say applies toother architectures.First, I assume the div and ldiv functions are more efficient thanusing / and % (obviously it depends on the compiler and level ofoptimization, but it''s one operation instead of two).However, div and ldiv require the length of the quotient, divisor,dividend and remainder to all be the same. Now all the machines I''veever worked with at the machine language level (quite a few of them)implement integer division with a dividend that is twice as long as thedivisor, quotient and remainder. Moreover, this is what naturallyarises in multiple precision arithmetic, you get dividends twice aslong as everything else. So suppose I''m using 16-bit divisors,quotients and remainders, but 32-bit dividends. If I were writing inassembly language, I would use the instructions that divide 16 bitsinto 32.But when I write in C, I''m forced to use the ldiv function, since oneof the operands is 32-bits. (Let''s say int=16-bit and long=32-bit, ason my machine.) Then the compiler has to implement this ldiv functionby using the instruction that divides 32-bits into 64-bits, since thedivisor is now 32-bits. In other words, the compiled code is forced touse a divide instruction with operands twice as large as needed, due tothe design of the div and ldiv functions.Anybody know a way around this (apart from inserting assembly code inmy C program)?Thanks in advance... 解决方案The leap from "I assume" to "I''m forced" seems arisky one. What have your measurements shown aboutthe efficiencies of /, %, both / and %, and ldiv?You *have* made measurements, haven''t you?HAVEN''T YOU????-- Er*********@sun.comjust use / and %. 这篇关于C中的有效除法/余数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-13 16:06