E - Rightmost Digit
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值是1<=N<=1,000,000,000,数据比较大,而我们要算的是a^b,这样数据就更大
所以用朴素算法就是把a连乘b次就不现实
#include <iostream>
#include<stdio.h>
#include <string>
using namespace std;
long long quick(long long a,long long b,int m)
{
long long ans=1;
while (b!=0)
{
if(b&1==1)
{
ans=ans*a%m;
b--;
}
b/=2;
a=a*a%m;
}
return ans;
}
int main()
{
int N;
long long x;
long long ans;
cin>>N;
while (N--)
{
cin>>x;
ans=1;
ans=quick(x, x, 10);
cout<<ans<<endl;
}
return 0;
}
#include <iostream>
using namespace std;
int pow1(int a,int b)
{
int r=1,base=a;
while(b)
{
if(b&1) //b&1 在这里等效于 b%2==1
/* b&1位运算,&运算通常用于二进制的取位操作,例如
一个数&1 的结果就是取二进制的最末位;还可以用来判断奇偶数,二进制的最末位数如果为0,就是偶数,如果最末位数是1,那么就是奇数。
由于是二进制,就用到了&和<<
&: 取二进制的最末位 b&1==0为偶,b&1==1为奇;
>>:>>运算比较单纯,二进制去掉最后一位;
在我们这一道题目中,我们要找的是最右边的数字
就用到了取模 求a^b%c(这就是著名的RSA公钥的加密方法),当a,b很大时,直接求解这个问题不太可能
利用公式a*b%c=((a%c)*b)%c,这样每一步都进行这种处理,这就解决了a^b可能太大存不下的问题,但这个算法的时间复杂度依然没有得到优化
*/
r=r*base%10;
base=base*base%10;
b=b>>1;//移位操作,取完最后一位后,就再依次取最后一位的前面的数字 b>>=1 等效于b=b/2;
}
return r;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n,n1,ans;
cin>>n;
n1=n%10;
ans=pow1(n1,n);
cout<<ans<<endl;
}
return 0;
}
快速幂算法
int poww(int a,int b){
2 int ans=1,base=a;
3 while(b!=0){
4 if(b&1!=0)
5 ans*=base;
6 base*=base;
7 b>>=1;
8 }
9 return ans;
10 }
以b==11为例,b=>1011,二进制从右向左算,
但乘出来的顺序是 a^(2^0)a^(2^1)*a^(2^3),是从左向右的。我们不断的让base=base目的即是累乘,以便随时对ans做出贡献。
base*=base这一步,base*base==base^2,下一步再乘,就是base^2*base^2==base^4,然后同理 base^4*base4=base^8,,,,,see?是不是做到了base–>base^2–>base^4–>base^8–>base^16–>base^32…….指数正是 2^i 啊,再看上 面的例子,a¹¹= a^(2^0)*a^(2^1)*a^(2^3),这三项是不是完美解决了