标签:leetcode
用二分,使复杂度由 O(n) 变为 O(logn)
#include<iostream> #include<cstdio> using namespace std; /// (b^n)mod m; (a*b mod m) = (a mod m)*(b mod m)mod m O(log n) /// (b^n)mod m; (a - b ) mod m =( (a mod m)-(b mod m) + n ) mod m ) O(log n) /// (b^n)mod m; (a + b ) mod m =( (a mod m)+(b mod m) mod m ) O(log n) int mod(int b,int n,int m) // 位运算 { int ans=1; while(n){ if(n&1) ans=(ans*b)%m; b=(b*b)%m; n=n>>1; } return ans; } int mod_1(int b,int n,int m) // O(log n) 递归 { if(n==0) return 1; int x=mod_1(b,n/2,m); long long ans=(long long)x*x%m; if(n%2) ans=ans*b%m; /// n&1 return (int)ans; } int main() { int b,n,m; while(scanf("%d%d%d",&b,&n,&m)) { printf("%d ",mod(b,n,m)); printf("%d\n",mod_1(b,n,m)); } return 0; } /** 12996 227 37909 == 7775 */
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:leetcode
原文地址:http://blog.csdn.net/u014705854/article/details/46817083