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)?
In integer division and modulus, the dividend is divided by the divisor into an integer quotient and a remainder. The integer quotient operation is referred to as integer division, and the integer remainder operation is the modulus.
Modulo − Represents as % operator. And gives the value of the remainder of an integer division. Division − represents as / operator. And gives the value of the quotient of a division.
In computing, the modulo operation returns the remainder or signed remainder of a division, after one number is divided by another (called the modulus of the operation).
Similarly, the remainder is evaluated using % (the modulo operator) and stored in remainder . remainder = dividend % divisor; Finally, the quotient and remainder are displayed using printf( ) . printf("Quotient = %d\n", quotient); printf("Remainder = %d", remainder);
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
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).
Yes. That's what the functions std::remquo
and std::div
do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With