首页 > 代码库 > wikioi 1497--求余运算

wikioi 1497--求余运算

题目描述:给定b,p,k要求(b^p)%k

思路:主要是快速求幂运算,有递归和非递归两种思路。

递归有错误,应该是溢出问题

#include <iostream>#include <queue>#include <climits>#include <algorithm>#include <memory.h>#include <stdio.h>#include <ostream>#include <vector>#include <list>#include <cmath>#include <string>#include <stdexcept>#include <stack>#include <map>using namespace std;long long pow(long long a,long long b,long long k){    if(b == 0)        return 1;    if(b == 1)        return a%k;    long long t = pow(a,b>>1);    if((b&1) == 0)    {        return t*t%k;    }    else    {        return t*t*a%k;    }}int main(){    long long b,p,k;    cin>>b>>p>>k;    long long b1 = b;    long long p1 = p;    //long long ans = pow(b,p);    //ans = ans%k;    long long ans = 1;    b = b%k;    while(p>0)    {        if(p%2 == 1)            ans = ans*b%k;        p/=2;        b = b*b%k;    }    cout<<b1<<"^"<<p1<<" mod "<<k<<"="<<ans<<endl;    return 0;}