Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get both the modulus and quotient of division in a single operation in C++?

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)?

like image 821
mczarnek Avatar asked Sep 05 '20 03:09

mczarnek


People also ask

Is modulus and quotient same?

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.

What is the difference between the division (/) operator and the modulus (%) operator?

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.

Can modulus be divided?

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).

How do you find the quotient in C?

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);


Video Answer


3 Answers

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
like image 93
prl Avatar answered Oct 22 '22 02:10

prl


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).

like image 25
eerorika Avatar answered Oct 22 '22 04:10

eerorika


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

like image 40
Pete Becker Avatar answered Oct 22 '22 03:10

Pete Becker