模平方根算法
求a的b次方有库函数 pow(a, b),可是它返回值是double类型,而且在不同开发环境下,数据有精度误差(比如某DEV,详见),如果自己写for循环,当b特别大时,超范围、超时都妥妥的。所以,就有了模平方根算法,也就是通常说的快速幂。
原理:
//递归写法 int pow_power(int a, int b,int MOD){ //a的b次方 if(b == 0) return 1; int res = pow_power(a, b/2); res = res * res % MOD; if(b&1) res = res * a % MOD; return res; } //迭代写法 int quickPower(int x, int n, int mod) { int t = x, res = 1; while (n) { if (n & 1) res = ((res % mod) * (t % mod)) % mod; t = ((t % mod) * (t % mod)) % mod; n >>= 1; } return res % mod; }
根据原理,还可以写出来快速乘(龟速乘),在乘法会爆long long范围时,只能这样做了。
int mul(int a, int b, int p){ //快速乘,计算a*b%p int res = 0; while(b){ if(b & 1) res = (ret + a) % p; a = (a + a) % p; b >>= 1; } return res; }