论直接取模与手写取模函数的时间差异

最近在多校题解中经常看到巨巨们手写函数进行取模操作,似乎是比%操作更快。

%操作在计算机中的实现依靠除法,显然不如手写函数的加减法更优秀。

在进行多次加法更新取模的时候,可以写一发。不过当算法复杂度在O(n)以上的时候,这个优化意义不大。

 1 #include <cstdio>
 2 
 3 const int maxn = 5e8+11;
 4 const int MOD = 1e9+7;
 5 typedef long long LL;
 6 
 7 inline void update(LL &x,LL d)
 8 {
 9     x += d;
10     if(x >= MOD) x -= MOD;
11     if(x < 0) x += MOD;
12 }
13 
14 int main()
15 {
16     LL ans = 0;
17     printf("update()
");
18     for(int i=0;i<maxn;i++)
19     {
20         //ans += i;
21         //ans %= MOD;
22         update(ans,i);
23     }
24     printf("%I64d
",ans);
25 }

看起来优化了很多的样子

cpu是i5-4300u

原文地址:https://www.cnblogs.com/helica/p/5742633.html