1. 程式人生 > >快速冪演算法 取餘運算 a^b mod c

快速冪演算法 取餘運算 a^b mod c

題目描述Description

輸入bpk的值,程式設計計算bp mod k的值。其中的bpk*k為長整型數(2^31範圍內)。

輸入描述Input Description

b p k 

輸出描述Output Description

輸出b^p mod k=?

=左右沒有空格

樣例輸入Sample Input

2  10  9

樣例輸出Sample Output

2^10 mod 9=7

這道題目如果就這樣直接求下去的話,當a,b稍微大一點的時候發生溢位,和超時,故應該用更好的方法來求解,快速冪當然是最好的選擇了。

話說這裡有模板,但也應該自己努力去完全理解模板。哈哈,網上有詳細的講解,這裡不再羅嗦,直接上程式碼吧!;

我的程式碼如下:

#include<iostream>
using namespace std;

int powermod(long a, long b, long c)
{
    long ans=1;
    a=a%c;
    while(b>0)
    {
        if(b%2==1)
        {
            ans=(ans*a)%c;
        }
        b=b/2;
        a=(a*a)%c;
    }
    return ans;
}

int main(void)
{
    long A,B,C;
    while(cin>>A>>B>>C)
    {
        int Re;
        Re=powermod(A,B,C);
        cout<<A<<'^'<<B<<" mod "<<C<<'='<<Re<<endl;
    }
    return 0;
}