Rightmost Digit
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 51889 Accepted Submission(s): 19634
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.
第一个方法直接套模版 P26
用大数取模的二进制方法
#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;
/*
* hdu 1061
* by : mazicwong
* creat on: 2016/12/10
*/
/*
求n的n次方的最后一个数字,直接套模版P28
大数取模
*/
int mod_exp(int a, int b0, int n) //return a^b0 & n
{
if (a > n) a %= n;
int i, d = 1, b[35];
for (i = 0; i < 35; i++)
{
b[i] = b0 % 2;
b0 /= 2;
if (b0 == 0) break;
}//b[i] b[i-1] ...b[0]为b0的二进制表示
for (; i >= 0; i--)
{
d = (d*d) % n;
if (b[i] == 1) d = (d*a) % n;
}
return d;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int n;
scanf("%d", &n);
printf("%d\n", mod_exp(n, n, 10));//return n^n % 10
}
return 0;
}
第二个模版
int mod_exp(int a, int b, int c)
{
int ans = 1;
a = a%c;
while (b > 0)
{
if (b & 1)
ans = (ans*a) % c;
b = b >> 1;
a = (a*a) % c;
}
return ans;
}
两个模版都一样,第二个打起来快点,