### vintage_Petr_Mitrichev's blog

By vintage_Petr_Mitrichev, history, 22 months ago,

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 ?

• +28

 » 22 months ago, # | ← Rev. 2 →   +5 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.
 » 22 months ago, # | ← Rev. 3 →   +18 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.
•  » » 22 months ago, # ^ |   +10 Yes , i checked in c++14 , its 3.6 times faster than % .. thanks nikolapesic2802 , CodingKnight
•  » » » 22 months ago, # ^ |   0 With pleasure. Thanks for sharing the result of the experiment.
 » 22 months ago, # |   +21 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