码迷,mamicode.com
首页 > 其他好文 > 详细

快速幂

时间:2019-12-24 20:16:08      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:printf   def   include   return   快速   space   i++   turn   递归   

快速幂

无函数快速幂

#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
    long long b, p, k;
    scanf("%lld%lld%lld", &b, &p, &k);
    long long s, a;
    s = b%k;
    a = 1;
    for(int i=1; i<=p; i++)
    {
        s = s*b%k;
        if(s==b%k) break;
        a++;
    }
    printf("%lld^%lld mod %lld=", b, p, k);
    p = p%a;
    s = 1;
    if(p==0) p=a;
    for(int i=1; i<=p; i++) s=s*b%k;
    printf("%lld", s);
    return 0;
}

递归

  • 递归求快速幂
#include<cstdio>
using namespace std;
int f(int x, int n, int m)
{
    if(n == 0) return 1%m;
    if(n == 1) return x%m;
    long long y = f(x, n/2, m);
    y = (y%m)*(y%m)%m;
    if(n%2==1) y = (y%m)*(x%m)%m;
    return y;
}
int main()
{
    int x, n, m;
    long long z;
    scanf("%d %d %d", &x, &n, &m);
    z = f(x, n, m);
    printf("%d^%d mod %d=%lld", x, n, m, z);
    return 0;
}

递推

  • 非递归求快速幂[(a^b)%n]
#include<cstdio>
#define ll long long
using namespace std;
ll pow(ll a, ll b, ll n)
{
    ll ans=1;
    while(b)
    {
        if(b%2 == 1) ans*=a;
        a = (a*a)%n;
        b=b/2;
    }
    return ans;
}
ll a, b, n;
int main()
{
    scanf("%lld%lld%lld", &a, &b, &n);
    printf("%lld", pow(a, b, n));
    return 0;
}

快速幂

标签:printf   def   include   return   快速   space   i++   turn   递归   

原文地址:https://www.cnblogs.com/orange-233/p/12093222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!