题目大意:求N^N和10取余的结果。
解题思路:该题有很多种做法,可以直接暴力(但会TLE)、找规律、分治、快速幂取模都可以求解。后三种求法都很快,其中找规律可以直接打表,速度很快,但规律一般不好找;分治类似于二分查找每次规模近似减少一半,时间复杂度为O(logn),快速幂取模的原理类似。详见code。
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1061
找规律 code:
#include <iostream>
#include <cstdio>
using namespace std;
int t,m,n;
const int ans[20] = { 0, 1, 4, 7, 6, 5, 6, 3, 6, 9, 0, 1, 6, 3, 6, 5, 6, 7, 4, 9 };
int main(){
scanf("%d",&t);
while (t--){
scanf("%d",&n);
printf("%d\n",ans[n%20]);
}
return 0;
}
分治 code:
#include <iostream>
#include <cstdio>
using namespace std;
int t,m,n;
//直接暴力会TLE
//int main(){
// scanf("%d",&t);
// while(t--){
// scanf("%d",&n);
// ans=1;
// for(int i=0;i<n;i++)
// ans=(int)((long long)ans*n%10);
// printf("%d\n",ans);
// }
// return 0;
//}
int pow_mod(int a,int n,int m){
int x=1;
if(n>0) x=pow_mod(a,n/2,m);
long long ans = (long long)x*x%m;
if(n%2==1) ans=ans*a%m;
return (int)ans;
}
int main(){
scanf("%d",&t);
while(t--){
scanf("%d",&n);
int mod=pow_mod(n,n,10);
printf("%d\n",mod);
}
return 0;
}
快速幂取模 code(跟分治的原理一样):
#include <iostream>
#include <cstdio>
using namespace std;
int t,m,n;
int mod_exp(int a, int b, int m){
int ans, tmp;
ans=1%m;
tmp=a%m;
while (b){
if (b&1) ans=ans*tmp%m;
tmp=tmp*tmp%m;
b >>= 1;
}
return ans;
}
int main(){
scanf("%d",&t);
while (t--){
scanf("%d",&n);
printf("%d\n",mod_exp(n, n, 10));
}
return 0;
}