hdu 2035 人見人愛A^B(快速冪)
Problem Description
求A^B的最後三位數表示的整數。
說明:A^B的含義是“A的B次方”
Input
輸入資料包含多個測試例項,每個例項佔一行,由兩個正整數A和B組成(1<=A,B<=10000),如果A=0, B=0,則表示輸入資料的結束,不做處理。
Output
對於每個測試例項,請輸出A^B的最後三位表示的整數,每個輸出佔一行。
Sample Input
2 3
12 6
6789 10000
0 0
Sample Output
8
984
1
解析:中文題,就是求次方,結果對1000取餘,利用二分,進行位運算判斷,直接給程式碼:
#include<iostream>
using namespace std;
#define a 1000
int mod(int m,int n)
{
int k=m%a,sum=1;
while(n)
{
if(n&1) //位運算進行判斷
sum=sum*k%a; //結果累乘取模
k=k*k%a; //乘數不斷增大,目的是減少迴圈次數,使得時間複雜度為O(lgn)
n>>=1;
}
return sum;
}
int main()
{
int m,n;
while(cin>>m>>n&&(m&&n))
{
cout<<mod (m,n)<<endl;
}
return 0;
}
接下來再看一道更水的:
A hard puzzle hdu 1097
Problem Description
lcy gives a hard puzzle to feng5166,lwg,JGShining and Ignatius: gave a and b,how to know the a^b.everybody objects to this BT problem,so lcy makes the problem easier than begin.
this puzzle describes that: gave a and b,how to know the a^b’s the last digit number.But everybody is too lazy to slove this problem,so they remit to you who is wise.
Input
There are mutiple test cases. Each test cases consists of two numbers a and b(0大於a,b小於或者等於2^30)
Output
For each test case, you should output the a^b’s last digit number.
Sample Input
7 66
8 800
Sample Output
9
6
沒什麼好說的了,帶模板對10取模
#include<iostream>
using namespace std;
#define a 10
int mod(int m,int n)
{
int k=m%a,sum=1;
while(n)
{
if(n&1)
sum=(sum*k)%a;
k=(k*k)%a;
n>>=1;
}
return sum;
}
int main()
{
int m,n;
while(cin>>m>>n)
{
cout<<mod(m,n)<<endl;
}
return 0;
}
另外,快速冪取模還常常用於矩陣,具體的分析和程式碼可以看我的文章“矩陣快速冪”。