震惊! 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.
分析
1.快速冪
先看看怎么求a的a次方更快:
你看,只有指數對應的位為1,才相乘
而且每個乘的數都有規律,
假設a^2^0=c,a^2^1=c*c=c1,
a^2^2=c1*c1
那就用一個數存c,然后循環乘就行,
至于什么時候算在最終結果之內,只要看指數對應的位是否為一
我解釋不太清楚,看看別人怎么解釋的吧
由于是二進制,很自然地想到用位運算這個強大的工具: & 和 >> ,&運算通常用于二進制取位操作,例如一個數 & 1 的結果就是取二進制的最末位。還可以判斷奇偶x&1==0為偶,x&1==1為奇。>>運算比較單純,二進制去掉最后一位
以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 啊,再看上面的例子,a11 = a^(2^0) * a^(2^1) * a^(2^3),這三項是不是完美解決了,,嗯,快速冪就是這樣。
2.取模運算
定理:
(a*b)%c=(a%c)*(b%c)%c
于是,求最后n位
int quick(int a,int b,int c) { int ans=1; //記錄結果 a=a%c; //預處理,使得a處于c的數據范圍之下 while(b!=0) { if(b&1) ans=(ans*a)%c; //如果b的二進制位不是0,那么我們的結果是要參與運算的 b>>=1; //二進制的移位操作,相當于每次除以2,用二進制看,就是我們不斷的遍歷b的二進制位 a=(a*a)%c; //不斷的加倍 } return ans; }本題代碼
#include<iostream> using namespace std;int quick(int a,int b,int n) { int ans =1;a=a%n;while(b!=0){if(b&1)ans=(ans*a)%n;a=a*a%n;b>>=1;} return ans; } int main(){int n,a;cin>>n;while(n--){cin>>a;cout<<quick(a,a,10)<<endl;} }總結
以上是生活随笔為你收集整理的震惊! Rightmost Digit 快速幂解决的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: k3 审核流程图_K3操作流程图
- 下一篇: 震惊! Leftmost Digit