@@ -4,7 +4,7 @@ public class ChineseRemainderTheorem
4
4
5
5
//function to find the greatest common divisor (GCD) of two numbers using the Extended Euclidean Algorithm
6
6
private static long gcd (long a , long b )
7
- {
7
+ {
8
8
if (b == 0 )
9
9
return a ; //base case: if b is 0, a is the GCD
10
10
@@ -13,7 +13,7 @@ private static long gcd(long a, long b)
13
13
14
14
//function to find the modular inverse of 'a' under modulo 'm' using the Extended Euclidean Algorithm
15
15
private static long extendedGCD (long a , long b )
16
- {
16
+ {
17
17
long originalB = b ; //keeping original 'b' for later use
18
18
long x1 = 1 , x2 = 0 ; //x1 and x2 are coefficients for 'a'
19
19
long y1 = 0 , y2 = 1 ; //y1 and y2 are coefficients for 'b'
@@ -40,7 +40,7 @@ private static long extendedGCD(long a, long b)
40
40
41
41
//function to implement the Chinese Remainder Theorem
42
42
public static long chineseRemainder (int [] n , int [] a )
43
- {
43
+ {
44
44
long N = 1 ; //variable to hold the product of all moduli
45
45
for (int ni : n )
46
46
N *= ni ; //calculating the product of all moduli
@@ -49,22 +49,22 @@ public static long chineseRemainder(int[] n, int[] a)
49
49
for (int i = 0 ; i < n .length ; i ++)
50
50
{
51
51
long Ni = N /n [i ]; //calculating Ni (the product of all moduli except n[i])
52
- long mi = extendedGCD (Ni , n [i ]); //finding the modular inverse of Ni modulo n[i]
52
+ long modularInverse = extendedGCD (Ni , n [i ]); //finding the modular inverse of Ni modulo n[i]
53
53
//updating the result
54
- result += a [i ]*Ni *mi ;
54
+ result += a [i ]*Ni *modularInverse ;
55
55
}
56
56
57
57
return result %N ; //returning final answer
58
58
}
59
59
60
60
public static void main (String [] args )
61
- {
61
+ {
62
62
//example test case
63
- int [] n = {3 , 5 , 7 }; //moduli
64
- int [] a = {2 , 3 , 2 }; //remainders
63
+ int [] moduli = {3 , 5 , 7 };
64
+ int [] remainder = {2 , 3 , 2 };
65
65
66
66
//calculating the solution using the Chinese Remainder Theorem
67
- long solution = chineseRemainder (n , a );
67
+ long solution = chineseRemainder (moduli , remainder );
68
68
//output
69
69
System .out .println ("The solution is: " + solution ); //expected output: 23
70
70
}
0 commit comments