51nod--1079 中国剩余定理
2016-03-22 10:20
141 查看
题目:
1079 中国剩余定理基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注
一个正整数K,给出K Mod 一些质数的结果,求符合条件的最小的K。例如,K % 2 = 1, K % 3 = 2, K % 5 = 3。符合条件的最小的K = 23。
Input
第1行:1个数N表示后面输入的质数及模的数量。(2 <= N <= 10)
第2 - N + 1行,每行2个数P和M,中间用空格分隔,P是质数,M是K % P的结果。(2 <= P <= 100, 0 <= K < P)
Output
输出符合条件的最小的K。数据中所有K均小于10^9。
Input示例
3
2 1
3 2
5 3
Output示例
23
分析:
若 m1, m2, m3…mi 是两两互素的正整数, 则同余方程组:x = a1 (mod m1)
x = a2 (mod m2)
…
x = an (mod mn)
有模 M = m1 * m2 * m3 * m4 … mn 的唯一解。
令 Mi = M / mi;
易得 (Mi, mi) = 1 , 所以有 MiPi = 1(mod mi)
则 方程组的解 x=∑ni=1ai*Mi*Pi
实现:
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int maxn = 100; LL a[maxn], m[maxn]; void Exgcd(LL a, LL b, LL& d, LL& x, LL& y) { if(b == 0) { d = a, x = 1, y = 0; } else { Exgcd(b, a%b, d, y, x); y -= x * (a/b); } } LL China(int n, LL* a, LL* m) { LL M = 1, d, y, x = 0; for(int i = 0; i < n; ++i) M *= m[i]; for(int i = 0; i < n; ++i) { LL w = M / m[i]; Exgcd(m[i], w, d, d, y); x = (x + y*w*a[i]) % M; } return (x + M) % M; } int main() { int n; while(cin >> n) { for(int i = 0; i < n; ++i) { cin >> m[i] >> a[i]; } cout << China(n, a, m) <<endl; } }
相关文章推荐
- 1.m分解阶乘之和
- 2.几种递推数
- 3.欧拉函数
- 4.快速幂模m算法
- 5.扩展欧几里得&&中国剩余定理
- 6.数论_web
- Project Euler Problem 387 - Harshad Numbers - 深度优先
- 编程之美2015初赛A
- 数论题集
- 原根
- 阶与原根学习笔记
- HDU 1299 Diophantus of Alexandria
- Leftmost Digit(HDU 1060)
- Rightmost Digit(HDU 1061)
- Python-在奇数中寻找素数
- ZOJ 2674 Strange Limit 欧拉定理
- LeetCode-Palindrome Number
- 组合数求模总结
- Sicily 1047 Super Snooker
- 【数论】组合数求模