[二分] 洛谷P1226 快速幂

题目

输入b,p,k的值,求b^p mod k的值。其中b,p,k*k为长整型数。

做法

快速幂讲解

代码

代码1:没有位运算

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#define _for(i,a,b) for(int i = (a); i<(b); i++)
#define _rep(i,a,b) for(int i = (a); i<=(b); i++)
#define ll long long
using namespace std;

ll b,p,k;

int main(){
    scanf("%lld%lld%lld",&b,&p,&k);
    ll ans = 1, x = b, n = p;
    while(n>0){
        if (n%2 == 1){
            ans *= x;
            ans %= k;
        }
        x*=x;
        x%=k;
        n>>=1;
    }
    if (p == 0)  printf("%lld^%lld mod %lld=%lld",b,p,k,0);   // 对于0的特判 
    else  printf("%lld^%lld mod %lld=%lld",b,p,k,ans);

    return 0;
}

代码2:有位运算

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;
}

猜你喜欢

转载自blog.csdn.net/icecab/article/details/81452517
今日推荐