Rightmost Digit
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 48094 Accepted Submission(s): 18239
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.
复杂吧,这里给大家看下一个我以前写的超牛逼的算法,不过这次没有想起来(装逼一下,大神们直接忽略)
其实跟上面的差不多,只是将代码精简了
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 48094 Accepted Submission(s): 18239
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最后面的一位,最直接的方法就是找规律
尾数为0,1,5,6不论有多少个数相乘都不会变
尾数为 4,9两个一次循环,例如4就是 4,6,4,6
位数为2,3,7,8 就是4个一次循环,例如2就是 2,4,8,6,2,4,8,6
最后要记得用long long或者__int64
代码:
<span style="font-size:18px;">
#include <iostream>
#include<cstdio>
using namespace std;
int main()
{
__int64 n;
int t;
scanf("%d",&t);
while(t--)
{
scanf("%I64d",&n);
__int64 m=n%10;
if(m==0||m==1||m==5||m==6)
printf("%I64d\n",m);
else{
if(m==2)
{
if(n%4==1)
printf("2\n");
if(n%4==2)
printf("4\n");
if(n%4==3)
printf("8\n");
if(n%4==0)
printf("6\n");
}
if(m==3)
{
if(n%4==1)
printf("3\n");
if(n%4==2)
printf("9\n");
if(n%4==3)
printf("7\n");
if(n%4==0)
printf("1\n");
}
if(m==4)
{
if(m%2==1)
printf("4\n");
if(m%2==0)
printf("6\n");
}
if(m==7)
{
if(n%4==1)
printf("7\n");
if(n%4==2)
printf("9\n");
if(n%4==3)
printf("3\n");
if(n%4==0)
printf("1\n");
}
if(m==8)
{
if(n%4==1)
printf("8\n");
if(n%4==2)
printf("4\n");
if(n%4==3)
printf("2\n");
if(n%4==0)
printf("6\n");
}
if(m==9)
{
if(m%2==1)
printf("9\n");
if(m%2==0)
printf("1\n");
}
}
}
return 0;
}
</span>
复杂吧,这里给大家看下一个我以前写的超牛逼的算法,不过这次没有想起来(装逼一下,大神们直接忽略)
<span style="font-size:18px;">
#include <iostream>
#include<cstdio>
using namespace std;
int main()
{
long n,m,num,p;
cin>>num;
while(num--){
cin>>n;
m = p = n % 10;
if (n % 4 == 0) n = 4;
else n = n % 4;
while(--n) p = (p * m) % 10;
cout<<p<<endl;
}
return 0;
}</span>
其实跟上面的差不多,只是将代码精简了