HDOJ 1061 Rightmost Digit
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.
大概题意就是输出一个数的本身次方的个位数,例如3的3次方的个位数是7.
这个题有两种解法:
第一种是经典的快速幂算法:
快速幂我这里就不多介绍了,关于快速幂算法我单独出l一个博客做详细介绍的了感兴趣的朋友可以去看看。
#include <stdio.h>
// 公式:(a * b) % p = (a % p * b % p) % p
//快速求幂
long long npower4(long long base, long long power);//快速求幂优化版pro
int main(void)
{
int n;
scanf("%d", &n);
while (n--)
{
int num;
scanf("%d", &num);
printf("%lld\n",npower4(num, num));
}
return 0;
}
long long npower4(long long base, long long power)
{
long long result = 1;
while (power > 0)
{
if (power & 1)
result = result * base % 10;
power >>= 1;
base = base * base % 10;
}
return result;
}
第二种解法是找规律:
不难看出个位数出现是固定组合,每二十个数一次循环,根据这个我们可以写代码了。
#include <stdio.h>
const int arr[21] = { 0,1,4,7,6,5,6,3,6,9,0,1,6,3,6,5,6,7,4,9,0 };
//保存个位数出现组合方便调用
int main(void)
{
int n;
scanf("%d", &n);
while (n--)
{
int num;
scanf("%d", &num);
printf("%d\n",arr[num % 20]);
}
return 0;
}