You could write something like:
int i = 3;
int k = 2;
int division = i / k;
int remainder = i % k;
It seems as thought this would, on a low level, ask an ALU to perform two vision operations: one returning the quotient, and one returning the remainder. However, I believe an ALU would most likely calculate both in a single operation. If that is the case, this is not optimally efficient.
Is there a more efficient way of doing it, without asking the CPU to calculate twice? In other words, can it be done in a single operation from C++?
Actually, the code you wrote won’t generate any division instructions since the compiler can figure out the results at compile time. I wrote a little test program and set the compiler (VC++ 10SP1) to generate an assembly code listing.
I had to write it this way and explicitly tell the compiler to not inline any functions.
Otherwise the compiler would have happily optimized away most of the code. Here is the resulting assembly code for the divide function.
It’s smart enough to generate a single IDIV instruction and use the quotient and remainder generated by it. Modern C and C++ compilers have gotten really good at this sort of optimization. Unless you have a performance problem and have profiled your code to determine where the bottleneck is, don’t try to second guess the compiler.