In accordance with that answer in Soen, it is possible to calculate the quotient and the rest of a division with a single operation IDIV
. That is, each of these 3 code snippets:
// Trecho 1
var quociente = x / y;
// Trecho 2
var resto = x % y;
// Trecho 3
var quociente = x / y;
var resto = x % y;
could at first be executed with only 1 instruction (that’s right: the two high-level code instructions in Section 3 would be translated into a single low-level instruction).
I say could, because I don’t know how it is done in the practice of language to language: it is expected that compilers will be able to make this conversion correctly (maybe except for section 3, where the difficulty in optimization is greater). But interpreted languages, languages with dynamic data types, etc., can implement this in another way. The only way to know for sure would be to analyze the generated low-level code (as the linked response did, for C++).
P.S. I know that "module" (mod
) is different from "rest" (rem
) - there are circumstances where they are different, in particular involving negative numbers - but for the purposes of this answer I considered them equivalent.
Do you ask for any specific language? (your example suggests Javascript) In general, I would say the answer is nay: This calculation can be done on the hardware, using an own optimized algorithm. But I don’t have enough knowledge to support this statement. And anyway, different languages can implement this in different ways, so it’s hard to answer like this in the blank.
– mgibsonbr
Any language, I used javascript, because I find it simpler.
– Rogers Corrêa
P.S. Related question. There is talk only about division and multiplication (not about module, as here), but how the evidence suggests that the same algorithm (implemented in ALU by
IDIV
) produces as a result both the quotient and the rest, I believe that the considerations there can apply also here.– mgibsonbr