反复平方法(很经典的算法)

//2011-05-21 22:15:51 Accepted 1061 0MS 184K 466 B C++ //比较简单的题 ,求 n^n 估计暴力取模方法也能过,不试了 #include using namespace std; int solve(int a, int m, int n) { if(a > n) a = a%n; int i, d = 1, b[35]; for(i=0; i<35; i++) { b[i] = m%2; m = m/2; if(m==0) break; } for( ; i>=0; i--) { d = (d*d)%n; if(b[i]==1) d = (d*a)%n; } return d; } int main() { int testcases, n; scanf("%d", &testcases); while(testcases--) { scanf("%d", &n); int ans = solve(n, n, 10); printf("%d/n", ans); } return 0; }

你可能感兴趣的:(反复平方法(很经典的算法))