数论

本文深入讲解了数论中几个核心算法的实现,包括最大公约数、扩展欧几里得算法、Lucas定理以及中国剩余定理的应用。通过具体代码示例展示了如何解决基于这些算法的实际问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最大公约数

ll gcd(ll a,ll b)
{
    if(a==0)return b;
    return gcd(b%a,a);
}

扩展欧几里得

ll Extended_Euclid(ll a,ll b,ll &x,ll &y)
{
    // ax + by = d
    ll d;
    if(b==0)
    {
        x=1;y=0;
        return a;
    }
    d=Extended_Euclid(b,a%b,y,x);
    y-=a/b*x;
    return d;
}

Lucas

ll lucas(ll n,ll m,ll p)
{
    if(m==0)return 1;
    return mul(C(n%p,m%p),lucas(n/p,m/p),p);
}

乘法

ll mul(ll a,ll b,ll mod)
{
    ll ret=0;
    while(b)
    {
        if(b&1) ret=(ret+a)%mod;
        a=(a+a)%mod;
        b>>=1;
    }
    return ret;
}

剩余

ll China(ll a[],ll w[],ll len)
{
    ll i,d,x,y,m,n,ret;
    ret=0;
    n=1;
    for (i=0;i<len;i++)
        n*=w[i];
    for (i=0;i<len;i++)
    {
        m=n/w[i];
        d=Extended_Euclid(w[i],m,x,y);
        ret=ret%n+mul(mul(y,m,n),a[i],n);
    }
    return (n+ret%n)%n;
}

hdu 5768 中国剩余定理

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<string>
typedef long long ll;
using namespace std;
ll p,a[20],w[20];
ll mul(ll a,ll b,ll mod)
{
    ll ret=0;
    while(b)
    {
        if(b&1) ret=(ret+a)%mod;
        a=(a+a)%mod;
        b>>=1;
    }
    return ret;
}

ll Extended_Euclid(ll a,ll b,ll &x,ll &y)
{
    ll d;
    if(b==0)
    {
        x=1;y=0;
        return a;
    }
    d=Extended_Euclid(b,a%b,y,x);
    y-=a/b*x;
    return d;
}

ll crt(ll a[],ll w[],ll len)
{
    ll i,d,x,y,m,n,ret;
    ret=0;
    n=1;
    for (i=1;i<=len;i++)
        n*=w[i];
    //printf("n = %I64d\n",n);
    for (i=1;i<=len;i++)
    {
        m=n/w[i];
        d=Extended_Euclid(w[i],m,x,y);
        ret=ret%n+mul(mul(y,m,n),a[i],n);
    }
    return (n+ret%n)%n;
}
ll stw[20],sta[20];
int main()
{

    ll n,x,y;
    ll t;
    scanf("%I64d",&t);
    int cas=0;
    while(t--)
    {
        scanf("%I64d%I64d%I64d",&n,&x,&y);
        for(ll i=1;i<=n;i++)
        {
            scanf("%I64d%I64d",&w[i],&a[i]);
        }
        x--;
        ll ans=0,top,pro;
        for(ll i=0;i<(1<<n);i++)
        {
            top=0;
            pro=1;
            for(ll j=1;j<=n;j++)//下标问题
            {
                if(i&(1LL<<j-1))
                {
                    top++;
                    stw[top]=w[j];
                    sta[top]=a[j];
                    pro*=w[j];
                }
            }
            top++;stw[top]=7;
            sta[top]=0;
            pro*=7;
            ll key=crt(sta,stw,top);
            ll tx=x/pro+(x%pro>=key);
            ll ty=y/pro+(y%pro>=key);
            if(top&1)
                ans+=ty-tx;
            else ans-=ty-tx;
        }
        printf("Case #%d: %I64d\n",++cas,ans);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值