Divide and Get Remainder at the same time?

2019-01-23 00:30发布

Apparently, x86 (and probably a lot of other instruction sets) put both the quotient and the remainder of a divide operation in separate registers.

Now, we can probably trust compilers to optimize a code such as this to use only one call to divide:

( x / 6 )
( x % 6 )

And they probably do. Still, do any languages (or libraries, but mainly looking for languages) support giving both the divide and modulo results at the same time? If so, what are they, and What does the syntax look like?

10条回答
ら.Afraid
3楼-- · 2019-01-23 01:08
    int result,rest;
    _asm
    {
        xor edx, edx // pone edx a cero; edx = 0
        mov eax, result// eax = 2AF0
        mov ecx, radix // ecx = 4
        div ecx
        mov val, eax
        mov rest, edx
    }
查看更多
趁早两清
4楼-- · 2019-01-23 01:11

This return the result an de remainder

        int result,rest;
    _asm
    {
        xor edx, edx // pone edx a cero; edx = 0
        mov eax, result// eax = 2AF0
        mov ecx, radix // ecx = 4
        div ecx
        mov val, eax
        mov rest, edx
    }
查看更多
Fickle 薄情
5楼-- · 2019-01-23 01:16

The .NET framework has Math.DivRem:

int mod, div = Math.DivRem(11, 3, out mod);
// mod = 2, div = 3

Although, DivRem is just a wrapper around something like this:

int div = x / y;
int mod = x % y;

(I have no idea whether or not the jitter can/does optimise that sort of thing into a single instruction.)

查看更多
再贱就再见
6楼-- · 2019-01-23 01:16

In Java the class BigDecimal has the operation divideAndRemainder returning an array of 2 elements with the result and de remainder of the division.

BigDecimal bDecimal = ...
BigDecimal[] result = bDecimal.divideAndRemainder(new BigDecimal(60));

Javadoc: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#divideAndRemainder(java.math.BigDecimal)

查看更多
老娘就宠你
7楼-- · 2019-01-23 01:17

In C#/.NET you've got Math.DivRem: http://msdn.microsoft.com/en-us/library/system.math.divrem.aspx

But according to this thread this isn't that much an optimization.

查看更多
登录 后发表回答