HDU 1061.Rightmost Digit题解
题目
Rightmost Digit
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 55522 Accepted Submission(s): 20987
Problem Description
Given a positive integer N, you should output the most right digit of N^N.
Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single positive integer N(1<=N<=1,000,000,000).
Output
For each test case, you should output the rightmost digit of N^N.
Sample Input
2
3
4
Sample Output
7
6
Hint
In the first case, 3 * 3 * 3 = 27, so the rightmost digit is 7. In the second case, 4 * 4 * 4 * 4 = 256, so the rightmost digit is 6.
大意:
看懂题很简单,就是n^n次方mod10
简单思路:pow函数直接暴力写,交了一发超时了。后面想到用快速幂求模,用的不是很熟练,参考了网上的题解。课后问别人发现可以直接打表找规律
———————————————————————————————————————————————————————
快速幂解法:
#include <iostream>
using namespace std;
int rightD(int n){//快速幂求模
int ans=1;
int tmp=n%10;
while (n!=0){
if(n&1==1)//判断二进制最后一位是不是1,等同于n%2==1;
ans=(ans*tmp)%10;//如果是奇数就先乘一次,因为位运算会取整
tmp = (tmp*tmp)%10;//如果n是偶数,直接乘两倍,例如4*4==2*2*2*2,计算次数大幅减少
n = n>>1;//位运算,等同于n/=2; 例如1,2,4,8是做4次计算,倒着来8,4,2,1也是四次计算
}
return ans;
}
//主函数
int main(){
int numcount=0;//数字的个数
int n=0;
cin>>numcount;
while (numcount-- > 0){
cin>>n;
cout<<rightD(n)<<endl;
}
return 0;
}
快速幂模板
ll pow(ll a,ll b,ll mod){
ll ans=1;
while(b!=0){
if(b%2==1)
ans=ans*a%mod;
a=a*a%mod;
b=b/2;
}
return ans;
}
————————————————————————————————————————————————————————
打表找规律解法:
1-9结尾的数中n^n尾数的最大循环周期是4
可以用n%4来计算n mod 4 的余数,然后每个数最多算四次循环即可
#include"bits/stdc++.h"
using namespace std;
int main(){
int T;
cin>>T;
while(T--){
int n;
scanf("%d",&n);
printf("%d\n",(int)pow(n%10, !(n%4) ? 4:n%4 ) %10);//判断n能不能被4整除,如果可以要n^4
} //如果不能整除就n^(n mod 4),记得%10取最后一位
} //pow函数胡返回值是double,用scanf输出要注意强制类型转换
打表解法2
#include<stdio.h>
typedef long long ll;
int main(){
int a[10][4]={{0},{1},{6,2,4,8},{1,3,9,7},{6,4},{5},{6},{1,7,9,3},{6,8,4,2},{1,9}};//存以1-9结尾数的幂次尾数
ll m;
int n,i,h;
while(~scanf("%d",&n)){
for(int i=0;i<n;i++){
scanf("%lld",&m);
h=m%10;
if(h==0||h==1||h==5||h==6)
printf("%d",h);
else if(h==4||h==9)
printf("%d",a[h][m%2]);
else
printf("%d",a[h][m%4]);
printf("\n");
}
}
return 0;
}