http://blog.csdn.net/lsldd/article/details/5506933
讲的很清楚!
模板
// m^n % k int quickpow(int m,int n,int k) { int b = 1; while (n > 0) { if (n & 1) b = (b*m)%k; n = n >> 1 ; m = (m*m)%k; } return b; }
注意中间 会超出int,当然多设几个变量可以避免。。太懒了 没分析。。
#include <iostream> #include <stdio.h> using namespace std; //m^n%k long long quickPow(long long m,long long n,long long k) { if(!n)return 0; long long b=1; while(n) { if(n&1)b=(b*m)%k; m=(m*m)%k; n=n>>1; } return b; } int main() { //freopen("in.txt","r",stdin); int t; scanf("%d",&t); while(t--) { long long n; scanf("%lld",&n); printf("%d\n",quickPow(n,n,10)); } return 0; }