51nod 1079 中国剩余定理

本文介绍了解决51nod1079题目中关于中国剩余定理的应用方法,通过逐级满足法实现了多个同余方程组的求解。文章提供了一段使用C++编写的扩展欧几里德算法实现代码,该算法能够有效地找到满足特定条件的最小正整数解。

51nod 1079 中国剩余定理

逐级满足法:
具体:http://blog.youkuaiyun.com/qq_33199236/article/details/51494157

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
#define LL long long
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define E 2.71828
//#define MOD 1000000007
#define N 1010

int exgcd(int a,int b,int &x,int &y)
{
    if(b == 0)
    {
        x = 1;
        y = 0;
        return a;
    }
    int d = exgcd(b,a%b,x,y);
    int t = x;
    x = y;
    y = t - a/b*y;
    return d;
}
int ni[20],c[20];
int main()
{
    int t;
    scanf("%d",&t);
    for(int i =0;i < t; i++)
        scanf("%d%d",&ni[i],&c[i]);
//ni[]为ni;
//c[]为ai; 这里因为x≡ai (%ni)就为 x + ni*y = ai;作为不定方程ax + by = c来看,ai就为ci。
    int now_mod = ni[0]; //n1第一个方程
    int now_c = c[0];     //a1第一个方程
    for(int i = 1; i < t; i++)
    {
//n1*x+n2*y==a2-a1,这里由于在用扩展欧几里德时,a,b会变化,   所以再引用了变量now_mod。下面只作方程一和二的讲解
        int a = now_mod;  //n1
        int b = ni[i];   //n2
        int c_real = c[i] - now_c; //a2-a1
        int x,y;
        int d = exgcd(a,b,x,y);
        x = x * c_real/d;
        int r = b/d;
        x = (x%r+r)%r;    //得到最小正的x。
        now_c = now_mod * x + now_c; //变化的C
        now_mod = now_mod * (ni[i]/d); //变化的n
//得到第一和第二合并的式子就是 c(这个其实无所谓,重点在下面俩的变化) ≡ now_c (mod now_mod)
    }
    int ans = now_c;
    printf("%d\n",ans);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值