http://acm.hdu.edu.cn/showproblem.php?pid=1061
Rightmost Digit
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 39858 Accepted Submission(s): 15045
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.
题意:简单的快速幂题目。求a的b次方所得结果的最后一位数。
解题思路:这是一题较简单的快速幂。以下是我对快速幂的理解,具体看代码。
快速幂思路:
• 求a^b,是不是要把a乘b次呢?这样也行, 只是慢了点 • 例如求a^8,先把a乘a一次,得到a^2,然后把 a^2和a^2乘一次,得到a^4,然后把a^4和a^4乘一 下就得到a^8了 • 假如要求a^10呢?10=8+2,a^10=a^8*a^2 • 把10化为二进制, 10=1010(2),1010(2)=1000(2)+10(2)
类似的题型有:http://blog.youkuaiyun.com/hellohelloc/article/details/47725353
<span style="font-size:18px;"><span style="font-size:24px;">#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int q_pow(int a,int b)
{
int ans=1;//ans初始化为1
while(b>0)
{
if(b&1) ans =(ans*a)%10;//如果b为奇数,把ans乘于a
a =(a*a)%10;//把a变成a^a,并且%10,防止溢出
b>>=1;//b右移一位,相当于除于2
}
return ans;
}
int main()
{
int n,cas;
cin>>n;
while(n--)
{
cin>>cas;
printf("%d\n",q_pow(cas%10,cas));//a%10在这是为了提速,原因自己想想
}
return 0;
}
</span>
</span>