7

I hear that when the processor does / or %, it will perform the same operation but one way it returns the quotient, the other way the remainder.

Is it possible to get both in a single operation? Maybe if I throw in a snippet of assembly code (which I've never done)?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
mczarnek
  • 1,305
  • 2
  • 11
  • 24

3 Answers3

12

Yes, the compiler will do it for you. Just use a divide followed by a remainder with the same operands.
https://godbolt.org/z/oK4f4s

void div(int n, int d, int *q, int *r)
{
    *q = n / d;
    *r = n % d;
}

div(int, int, int*, int*):
        mov     eax, edi
        mov     r8, rdx
        cdq
        idiv    esi
        mov     DWORD PTR [r8], eax
        mov     DWORD PTR [rcx], edx
        ret
prl
  • 11,716
  • 2
  • 13
  • 31
10

Is it possible to get both in a single operation?

No, there is no such operator in C++. There is function in the standard library which does both operations: std::div

But this doesn't matter. Whether you have one or two operations in C++ doesn't mean that the cpu would have to perform that many operations. A half decent optimiser will be able to translate both operations into a single instruction (assuming that is possible with the target CPU).

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 2
    (Or if not a single instruction, then compute the remainder from the quotient, dividend, and divisor, not redoing any unnecessary work. e.g. ARM has a multiply-and-subtract instruction designed for computing remainder after doing division.) – Peter Cordes Sep 05 '20 at 03:50
2

Yes. That's what the functions std::remquo and std::div do.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • 1
    `std::remquo` --> "sign and at least the three of the last bits" are saved at the quotient pointer, not the entire quotient. Useful with range reduction for [trig](https://stackoverflow.com/a/31525208/2410359) functions. – chux - Reinstate Monica Sep 05 '20 at 13:18
  • @chux-ReinstateMonica -- interesting; I'd never noticed that. Thanks. – Pete Becker Sep 05 '20 at 13:19