日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

震惊! Rightmost Digit 快速幂解决

發布時間:2025/3/12 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 震惊! 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,然后循環乘就行,
至于什么時候算在最終結果之內,只要看指數對應的位是否為一

int poww(int a,int b){int ans=1,base=a;while(b!=0){if(b&1!=0)ans*=base;base*=base;b>>=1;}return ans; }

我解釋不太清楚,看看別人怎么解釋的吧

由于是二進制,很自然地想到用位運算這個強大的工具: & 和 >> ,&運算通常用于二進制取位操作,例如一個數 & 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 快速幂解决的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。