poj2891(线性同余方程组)

一个exgcd解决一个线性同余问题,多个exgcd解决线性同余方程组。

Strange Way to Express Integers
Time Limit: 1000MS   Memory Limit: 131072K
Total Submissions: 12001   Accepted: 3797

Description

Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:

Choose k different positive integers a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ ik) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) can be used to express m.

“It is easy to calculate the pairs from m, ” said Elina. “But how can I find m from the pairs?”

Since Elina is new to programming, this problem is too difficult for her. Can you help her?

Input

The input contains multiple test cases. Each test cases consists of some lines.

  • Line 1: Contains the integer k.
  • Lines 2 ~ k + 1: Each contains a pair of integers ai, ri (1 ≤ ik).

Output

Output the non-negative integer m on a separate line for each test case. If there are multiple possible values, output the smallest one. If there are no possible values, output -1.

Sample Input

2
8 7
11 9

Sample Output

31

Hint

All integers in the input and the output are non-negative and can be represented by 64-bit integral types.

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
using namespace std;
#define N 10100

long long a[N],r[N];

long long cal_axb(long long a,long long b,long long mod)
{
    long long sum=0;
    while(b)
    {
        if(b&1) sum=(sum+a)%mod;
        b>>=1;
        a=(a+a)%mod;
    }
    return sum;
}

// ax+by = gcd(a,b) ->求解x,y 其中a,b不全为0,可以为负数
// 复杂度:O(log2a)
void extendgcd(long long a,long long b,long long &x,long long &y)
{
    if(a%b==0)
    {
        //到了终止条件
        x=0; y=1;
        return ;
    }
    extendgcd(b,a%b,x,y);
    long long tmpx;
    tmpx=y;
    y=x - (a/b)*y;
    x=tmpx;
}



long long Multi_ModX(long long m[],long long r[],int n)
{
    long long m0,r0;
    m0=m[0]; r0=r[0];
    for(int i=1;i<n;i++)
    {
        long long m1=m[i],r1=r[i];
        long long tmpd=__gcd(m0,m1);
        if( (r1 - r0)%tmpd!=0 ) return -1;
        long long k0,k1;
        extendgcd(m0,m1,k0,k1);
        k0 *= (r1-r0)/tmpd;
        //k0会不会很大
        m1 *= m0/tmpd;
        r0 = (cal_axb(k0,m0,m1)+r0)%m1;
        m0=m1;
    }
    return (r0%m0+m0)%m0;
}

int main()
{
    int k;
    while(cin>>k)
    {
        for(int i=0;i<k;i++)
            cin>>a[i]>>r[i];
        cout<<Multi_ModX(a,r,k)<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/chenhuan001/p/4991869.html