Is there a C ++ function (built-in or not) that gives the results of integer division and modular separation without repeating the operation?

You can write something like:

int i = 3;
int k = 2;
int division = i / k;
int remainder = i % k;

It seems like it would be at a low level to ask ALU to perform two vision operations: one returns a quotient, and one returns a remainder. However, I believe that ALU will most likely calculate as in a single operation. If so, it is not optimally effective.

Is there a more efficient way to do this without asking the CPU to calculate twice? In other words, can this be done in a single operation from C ++?

+5
source share
5 answers

, , , , . (V++ 10SP1) .

#include <iostream>

using namespace std;

struct result {
    long quotient, remainder;
};

result divide(long num, long den) {
    result d = { num / den, num % den };
    return d;
}

int main() {
    result d = divide(3, 2);
    d = divide(10, 3);
    cout << d.quotient << " : " << d.remainder << endl;
    return 0;
}

, . . .

; 8    : result divide(long num, long den) {

  00000 55       push    ebp
  00001 8b ec        mov     ebp, esp

; 9    :     result d = { num / den, num % den };

  00003 99       cdq
  00004 f7 7d 08     idiv    DWORD PTR _den$[ebp]

; 10   :     return d;
; 11   : }

  00007 5d       pop     ebp
  00008 c3       ret     0

, IDIV . C ++ . , , , .

+9

:

int i = 3;
int k = 2;
int division = i / k;
int remainder = i - division * k;

, , div, , , , .

+5

ISO C99 ldiv:

#include <stdlib.h>

ldiv_t ldiv(long numer, long denom);

The ldiv() function computes the value numer/denom (numerator/denominator).
It returns the quotient and remainder in a structure named ldiv_t that contains
two long members named quot and rem.

, FPU, .

+5

, :

int division = i / k;
int remainder = i - (division * k);
+1

, , ( ). gcc ( g++, ) -O0 ( -O1 , ).

2^28 ( i k 1 2^14) :

division = 0;
remainder = 0;
// this test is only there to measure the constant overhead!

1.676s

division = i/k;
remainder = i%k;

24.614s

division = i/k;
remainder = i - division*k;

15.009s

ldiv_t d = ldiv(i,k);
division = d.quot;
remainder = d.rem;

18.845s

, , - . ldiv , .

0

All Articles