vintage_Petr_Mitrichev's blog

By vintage_Petr_Mitrichev, history, 6 years ago, In English

suppose u have to find a % b , i see many red coders solution instead of using directly a%b they do like ..

if (a >=mod) a-=mod ??

why so ?

»
6 years ago, # |
Rev. 2   Vote: I like it +5 Vote: I do not like it

Its faster(if you do addition like 1e6(1,000,000) or more times in a program, writing an addition function using this if instead of % will save a lot of time),but this can be used only for addition and a similar if for subtraction. It can not be used for multiplication.

»
6 years ago, # |
Rev. 3   Vote: I like it +18 Vote: I do not like it

The plausible reason should be that the execution time of the statement if(a >= b) a -= b; is more likely to be less than the execution time of the statement a %= b; when it is guaranteed that the expression a < 2*b is true. You may write a short C++ program to compare the average execution time of both statements so as to confirm or refute this hypothesis.

»
6 years ago, # |
  Vote: I like it +21 Vote: I do not like it

because

  const uint64_t maxn = 1000000009;
  uint64_t ans = 0;
  for (int i = 0; i < maxn; ++i) {
    ans += i;
    if (ans >= maxn) ans -= maxn;
  }

1000 ms

  const uint64_t maxn = 1000000009;
  uint64_t ans = 0;
  for (int i = 0; i < maxn; ++i) {
    ans = (ans + i) % maxn;
  }

8700 ms