TheAlgorithms / Java

All Algorithms implemented in Java
MIT License
60.2k stars 19.47k forks source link

[FEATURE REQUEST] Implement Chinese Remainder Theorem #5772

Closed SuprHUlk closed 1 week ago

SuprHUlk commented 1 month ago

What would you like to Propose?

Problem Statement:
Given several pairwise coprime moduli ( n1, n2, ..., nk ) and integers ( a1, a2, ..., ak ), the goal is to find an integer ( x ) such that:

x = a1 ( mod n1) x = a2 ( mod n2) . . . x = ak ( mod nk)

This problem can be efficiently solved using the Chinese Remainder Theorem (CRT). The CRT provides a method for finding a unique solution modulo the product of the moduli ( N = n1 X n2 X ... X nk ), where ( N ) is the least common multiple of all moduli.

Issue details

The Chinese Remainder Theorem is a powerful algorithm used for solving systems of simultaneous congruences. It has applications in cryptography (like RSA), distributed computing, and error correction. The algorithm uses modular arithmetic and the extended Euclidean algorithm to find the modular inverses of the product of all moduli except one.

Approach:

Steps:

  1. Compute ( N = n1 X n2 X ... X nk ).
  2. For each ( ni ), compute ( Ni = N/ni ) and the modular inverse ( mi ) of ( Ni ) modulo ( ni ).
  3. Sum the terms ( ai X Ni X mi ) for all ( i ), and reduce the result modulo ( N ).

Test Case

Input:

moduli: [3, 5, 7]

remainders: [2, 3, 2]

Explanation:
We are given the system of congruences:

x = 2 ( mod 3 )

x = 3 ( mod 5 )

x = 2 ( mod 7 )

Final solution:

x = (2 X 35 X 2) + (3 X 21 X 1) + (2 X 15 X 1) (mod 105) = 233 (mod 105) = 23

Expected Output:
The smallest solution ( x = 23 ).

Additional Information

This algorithm is highly efficient and has many practical applications, particularly in cryptography (such as RSA key generation), error detection in communication, and scheduling problems.

07-Atharv commented 1 month ago

Can i take this issue?

saiteja9078 commented 1 month ago

i would like to take the issue ,can i? @SuprHUlk

github-actions[bot] commented 2 weeks ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contribution!

github-actions[bot] commented 1 week ago

Please reopen this issue once you have made the required changes. If you need help, feel free to ask in our Discord server or ping one of the maintainers here. Thank you for your contribution!