算法学习——数论

快速幂

下面两种方法的时间复杂度差不多

快速幂之迭代版

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

LL qmi(LL a,LL k,LL p)
{
    LL res=1;
    while(k)
    {
        if(k&1)
        {
            res=(LL)res*a%p;
        }
        k>>=1;
        a=(LL)a*a%p;
    }
    return res;
}

int main()
{
    int T;
    cin>>T;
    while(T--)
    {
    LL a,k,p;
    scanf("%lld %lld %lld",&a,&k,&p);
    cout << qmi(a,k,p)<<endl;
    }
    
    return 0;
}

快速幂——递归版

#include<iostream>
using namespace std;
#define ull unsigned long long
ull quick_pow(ull a,ull k,ull p)
{
    if(k==0) return 1;
    a%=p;
    ull res=quick_pow(a,k>>1,p);
    if(k&1) return res*res%p*a%p;
    return res*res%p;
}
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        int a,k,p;
        cin.tie(0);
        ios::sync_with_stdio(false);
        cin>>a>>k>>p;
        cout<<quick_pow(a,k,p)<<endl;
    }
    return 0;
}

 欧拉函数

活动 - AcWing

在写ans= ans / i * (i - 1);时若调转顺序,写成ans = ans * (i - 1) / i;
可能会使ans的结果int上溢

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    int T;cin>>T;
    while(T--)
    {
        int N;cin>>N;
        int ans=N;
        //判断质数的时候这里是<=
        for(int i=2;i<=N/i;i++)
        {
            //如果N能被i表示
            if(N%i==0)
            {
                ans=ans/i*(i-1);//不能加括号
                while(N%i==0)N/=i;
            }
        }
        if(N>1)ans=ans/N*(N-1);
        cout<<ans<<endl;
    }
    
    return 0;
}

 快速幂和欧拉函数相结合的题目

4968. 互质数的个数 - AcWing题库

这里有个求逆元的题解,有时间也得去学一下AcWing 4968. 互质数的个数(快速幂+乘法逆元+质因数分解+欧拉函数) - AcWing

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

const int MOD = 998244353;

//快速幂模块
LL qmi(LL a, LL b)
{
    LL res = 1;
    while (b)
    {
        if (b & 1) res = res * a % MOD;
        a = a * a % MOD;
        b >>= 1;
    }
    return res;
}

int main()
{
    LL a, b;
    cin >> a >> b;
    //特判
    if (a == 1)
    {
        cout << 0 << endl;
        return 0;
    }
    
    //欧拉函数模块
    LL res = a, x = a;
    for (int i = 2; i * i <= x; i ++ )
        if (x % i == 0)
        {
            while (x % i == 0) x /= i;
            res = res / i * (i - 1);
        }
    if (x > 1) res = res / x * (x - 1);
    
    
    cout << res * qmi(a, b - 1) % MOD << endl;
    return 0;
}

 

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值