您的位置:首页 > 其它

51nod - -1079 中国剩余定理

2017-05-03 13:58 363 查看

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

//方法1:枚举,不用多想,肯定超时
代码如下:
import java.util.Scanner;
public class Main{

public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int
;
int[] b = new int
;
//input
for(int i=0; i<n; ++i){
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
//process
long  p = (long)10e9;
//      System.out.println(p);
boolean flag  = true;
for(long i=1; i<=p; ++i){
flag = true;
for(int j=0; j<n; ++j){
if((i % a[j]) != b[j]){
flag = false;
break;
}
}
if(flag == false)
continue;
else{
System.out.println(i);
break;
}
}
}
}

//方法2:利用中国剩余定理模板:

//注意这里要用long型,不然后面会溢出
public class Main{
static long x ;
static long y;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int
;
int[] b = new int
;
//inout
for(int i=0; i<n; ++i){
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
//process
long result = china(a,b,n);
//output
System.out.println(result);
}
public static long china(int[] a, int[] b, int n){
long total=1, m = 0;
long ans = 0;
for(int i=0; i<n; ++i)
total *= a[i];
for(int i=0; i<n; ++i){
m = total / a[i];
extgcd(a[i], m, x, y);
ans = (ans + y*m*b[i]) % total;
}
return (ans + total) % total;
}
public static void extgcd(long a, long b, long a1, long b1){
if(b==0){
x = 1;
y = 0;
}else{
extgcd(b, a%b ,x, y);
long t = x;
x = y;
y = t - a/b*y;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: