Runtime calculation module(%)

Asked

Viewed 71 times

1

Statement of variables:

var x= 200;

var y= 50;

Module:

var resposta = x % y;

What the module should do, I believe (I calculate):

s1 = x / y;
s2 = s1 * y;
resposta = s2 - x;

The question in itself is: The calculation that the module does, takes the same execution time as if I did in hand?

  • 3

    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.

  • Any language, I used javascript, because I find it simpler.

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

1 answer

5


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.

  • Yes.So that answers my question. A calculation is definitely faster than several.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.