目录
POJ 2891 Strange Way to Express Integers
一,狭义剩余定理

二,OJ实战
POJ 2891 Strange Way to Express Integers
题目:
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 ≤ i ≤ k) 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 ≤ i ≤ k).
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>
using namespace std;
#define l long long
l x, y;
l gcd(l a, l b)
{
if (a == 0 || b == 0)
{
x = (b == 0);
y = (a == 0);
return a + b;
}
l r;
if (a < 0)
{
r = gcd(-a, b);
x *= -1;
return r;
}
if (b < 0)
{
r = gcd(a, -b);
y *= -1;
return r;
}
if (a >= b)r = gcd(a%b, b);
else r = gcd(a, b%a);
y -= a / b*x;
x -= b / a*y;
return r;
}
l cheng(l a, l b, l p)
{
if (b == 0)return 0;
if (b < 0)return cheng(a, -b, p)*-1;
l c = cheng(a, b / 2, p);
c = c + c;
if (b % 2)c += a;
return c%p;
}
int main()
{
l t, a1, r1, a2, r2;
while (cin >> t)
{
a1 = 1, r1 = 0;
while (t--)
{
cin >> a2 >> r2;
if (r1 >= 0)
{
l g = gcd(a1, a2);
if ((r2 - r1) % g)r1 = -1;
else
{
l a3 = a1 / g*a2;
r1 += cheng(cheng((r2 - r1) / g, x, a3), a1, a3);
r1 = (r1%a3 + a3) % a3;
a1 = a3;
}
}
}
cout << r1 << endl;
}
return 0;
}
三,广义剩余定理
如果模数不互质,那怎么办?
1,分解方程
常见的分解方法是把模数分解成素数幂的乘积
例如x=3(mod 18)可以分解成x=1(mod2)和x=3(mod9)
这样方程组就会变成由更多方程组成的方程组,但是每个模数都是素数幂
2,合并方程
x=a(mod p^b)和x=c(mod p^d),0<b<d
如果c=a(mod p^b),则合并后的方程是x=c(mod p^d)
否则,整个方程组无解
全部合并操作完成之后,直接退化成狭义剩余定理的情况。
本文介绍了一种使用中国剩余定理解决在线编程挑战(OJ)中 Strange Way to Express Integers 问题的方法。代码示例展示了如何通过求解非负整数的余数对来找到原始数值,同时提供了输入输出样例和代码实现,涉及的主要算法包括中国剩余定理和欧几里得算法。
1068





