C++ Best way to get integer division and remainder

后端 未结 8 1890
挽巷
挽巷 2020-12-01 00:29

I am just wondering, if I want to divide a by b, and am interested both in the result c and the remainder (e.g. say I have number of seconds and want to split that into minu

相关标签:
8条回答
  • 2020-12-01 00:53

    All else being equal, the best solution is one that clearly expresses your intent. So:

    int totalSeconds = 453;
    int minutes = totalSeconds / 60;
    int remainingSeconds = totalSeconds % 60;
    

    is probably the best of the three options you presented. As noted in other answers however, the div method will calculate both values for you at once.

    0 讨论(0)
  • 2020-12-01 00:56

    On x86 the remainder is a by-product of the division itself so any half-decent compiler should be able to just use it (and not perform a div again). This is probably done on other architectures too.

    Instruction: DIV src

    Note: Unsigned division. Divides accumulator (AX) by "src". If divisor is a byte value, result is put to AL and remainder to AH. If divisor is a word value, then DX:AX is divided by "src" and result is stored in AX and remainder is stored in DX.

    int c = (int)a / b;
    int d = a % b; /* Likely uses the result of the division. */
    
    0 讨论(0)
  • 2020-12-01 00:59

    You cannot trust g++ 4.6.3 here with 64 bit integers on a 32 bit intel platform. a/b is computed by a call to divdi3 and a%b is computed by a call to moddi3. I can even come up with an example that computes a/b and a-b*(a/b) with these calls. So I use c=a/b and a-b*c.

    The div method gives a call to a function which computes the div structure, but a function call seems inefficient on platforms which have hardware support for the integral type (i.e. 64 bit integers on 64 bit intel/amd platforms).

    0 讨论(0)
  • 2020-12-01 01:03

    On x86 at least, g++ 4.6.1 just uses IDIVL and gets both from that single instruction.

    C++ code:

    void foo(int a, int b, int* c, int* d)
    {
      *c = a / b;
      *d = a % b;
    }
    

    x86 code:

    __Z3fooiiPiS_:
    LFB4:
        movq    %rdx, %r8
        movl    %edi, %edx
        movl    %edi, %eax
        sarl    $31, %edx
        idivl   %esi
        movl    %eax, (%r8)
        movl    %edx, (%rcx)
        ret
    
    0 讨论(0)
  • 2020-12-01 01:05

    You can use a modulus to get the remainder. Though @cnicutar's answer seems cleaner/more direct.

    0 讨论(0)
  • 2020-12-01 01:08

    In addition to the aforementioned std::div family of functions, there is also the std::remquo family of functions, return the rem-ainder and getting the quo-tient via a passed-in pointer.

    [Edit:] It looks like std::remquo doesn't really return the quotient after all.

    0 讨论(0)
提交回复
热议问题