Skip to content

Commit 13d6561

Browse files
authored
Update ChineseRemainderTheorem.java
1 parent 09012d5 commit 13d6561

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

src/main/java/com/thealgorithms/maths/ChineseRemainderTheorem.java

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ public class ChineseRemainderTheorem
44

55
//function to find the greatest common divisor (GCD) of two numbers using the Extended Euclidean Algorithm
66
private static long gcd(long a, long b)
7-
{
7+
{
88
if(b == 0)
99
return a; //base case: if b is 0, a is the GCD
1010

@@ -13,7 +13,7 @@ private static long gcd(long a, long b)
1313

1414
//function to find the modular inverse of 'a' under modulo 'm' using the Extended Euclidean Algorithm
1515
private static long extendedGCD(long a, long b)
16-
{
16+
{
1717
long originalB = b; //keeping original 'b' for later use
1818
long x1 = 1, x2 = 0; //x1 and x2 are coefficients for 'a'
1919
long y1 = 0, y2 = 1; //y1 and y2 are coefficients for 'b'
@@ -40,7 +40,7 @@ private static long extendedGCD(long a, long b)
4040

4141
//function to implement the Chinese Remainder Theorem
4242
public static long chineseRemainder(int[] n, int[] a)
43-
{
43+
{
4444
long N = 1; //variable to hold the product of all moduli
4545
for(int ni : n)
4646
N *= ni; //calculating the product of all moduli
@@ -49,22 +49,22 @@ public static long chineseRemainder(int[] n, int[] a)
4949
for (int i = 0; i < n.length; i++)
5050
{
5151
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]
5353
//updating the result
54-
result += a[i]*Ni*mi;
54+
result += a[i]*Ni*modularInverse;
5555
}
5656

5757
return result%N; //returning final answer
5858
}
5959

6060
public static void main(String[] args)
61-
{
61+
{
6262
//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};
6565

6666
//calculating the solution using the Chinese Remainder Theorem
67-
long solution = chineseRemainder(n, a);
67+
long solution = chineseRemainder(moduli, remainder);
6868
//output
6969
System.out.println("The solution is: " + solution); //expected output: 23
7070
}

0 commit comments

Comments
 (0)