Rightmost Digit
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 39128 Accepted Submission(s): 14753
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).
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 6HintIn 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次方的个位数,想当然的就是每次累乘后都%10
#include<stdio.h>
int main(void)
{
long n,a,s,i;
scanf("%ld",&n);
while(n --)
{
s = 1;
scanf("%ld",&a);
i = a;
while(i --)
s = (s*(a%10))%10;
printf("%ld\n",s);
}
return 0;
}
但时间会超限,英文N的数目可以达到1*10^9,只能向更简单的方法,我们把一个数字N转换成二进制,如69 转换为二进制:1000101。如69^69 = 69^(2^0) * 69^(2^2) * 69^(2^6)。二进制后一位数上的大小是前一位树的两倍,在指数上体现为平方。用一个数组储存二进制,为零的位数在数组里就记为1,否则记录该数的个位数。
#include<stdio.h>
int main(void)
{
long n,a,s,i,j,v[32];
scanf("%ld",&n);
while(n --)
{
i = 1;
scanf("%d",&a);
s = a%10;
if(a%2 == 0)
v[0] = 1;
else
v[0] = s;
a /= 2;
while(a)
{
s = (s*s)%10;
if(a%2 == 0)
v[i++] = 1;
else
v[i++] = s;
a /= 2;
}
s = 1;
for(j = 0;j < i;j ++)
s = (s*v[j]%10)%10;
printf("%ld\n",s);
}
return 0;
}
这样就从循环N次变成循环log2(N).