Repository: TheAlgorithms/Java
Pull request #5873 (2024-10-16 11:54:52)

Implemented chinese remainder theorem with test file
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

#### Description of Change

This pull request implements the **Chinese Remainder Theorem (CRT)** algorithm to solve [issue #5772](https://github.com/TheAlgorithms/Java/issues/5772). 

The implementation includes:
- A function (`solveCRT`) that calculates the solution using the product of moduli and their modular inverses.
- A helper method (`modInverse`) that computes the modular inverse using the Extended Euclidean Algorithm.
- Detailed documentation adhering to Doxygen standards, with a reference to [Wikipedia](https://en.wikipedia.org/wiki/Chinese_remainder_theorem) for further details.
- Comprehensive unit tests that verify the implementation across different scenarios, including simple cases, larger numbers, and edge cases to ensure accuracy and reliability.

#### Checklist

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`.

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5873?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `0%` with `24 lines` in your changes missing coverage. Please review.
> Project coverage is 66.64%. Comparing base [(`169a01e`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/169a01e0c803cc5ccfb739a85c70ee46ea228337?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`2a2d965`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/2a2d96525090a4cf6c49c6afd210b61914d27261?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5873?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...m/thealgorithms/maths/ChineseRemainderTheorem.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5873?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fmaths%2FChineseRemainderTheorem.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9tYXRocy9DaGluZXNlUmVtYWluZGVyVGhlb3JlbS5qYXZh) | 0.00% | [24 Missing :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5873?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5873      +/-   ##
============================================
- Coverage     66.74%   66.64%   -0.11%     
+ Complexity     4489     4488       -1     
============================================
  Files           610      611       +1     
  Lines         16929    16953      +24     
  Branches       3267     3272       +5     
============================================
- Hits          11299    11298       -1     
- Misses         5182     5206      +24     
- Partials        448      449       +1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5873?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/maths/ChineseRemainderTheorem.java b/src/main/java/com/thealgorithms/maths/ChineseRemainderTheorem.java
new file mode 100644
index 00000000..c26e67cf
--- /dev/null
+++ b/src/main/java/com/thealgorithms/maths/ChineseRemainderTheorem.java
@@ -0,0 +1,84 @@
+package com.thealgorithms.maths;
+
+import java.util.List;
+
+/**
+ * @brief Implementation of the Chinese Remainder Theorem (CRT) algorithm
+ * @details
+ * The Chinese Remainder Theorem (CRT) is used to solve systems of
+ * simultaneous congruences. Given several pairwise coprime moduli
+ * and corresponding remainders, the algorithm finds the smallest
+ * positive solution.
+ */
+public final class ChineseRemainderTheorem {
+    private ChineseRemainderTheorem() {
+    }
+
+    /**
+     * @brief Solves the Chinese Remainder Theorem problem.
+     * @param remainders The list of remainders.
+     * @param moduli The list of pairwise coprime moduli.
+     * @return The smallest positive solution that satisfies all the given congruences.
+     */
+    public static int solveCRT(List<Integer> remainders, List<Integer> moduli) {
+        int product = 1;
+        int result = 0;
+
+        // Calculate the product of all moduli
+        for (int mod : moduli) {
+            product *= mod;
+        }
+
+        // Apply the formula for each congruence
+        for (int i = 0; i < moduli.size(); i++) {
+            int partialProduct = product / moduli.get(i);
+            int inverse = modInverse(partialProduct, moduli.get(i));
+            result += remainders.get(i) * partialProduct * inverse;
+        }
+
+        // Adjust result to be the smallest positive solution
+        result = result % product;
+        if (result < 0) {
+            result += product;
+        }
+
+        return result;
+    }
+
+    /**
+     * @brief Computes the modular inverse of a number with respect to a modulus using
+     * the Extended Euclidean Algorithm.
+     * @param a The number for which to find the inverse.
+     * @param m The modulus.
+     * @return The modular inverse of a modulo m.
+     */
+    private static int modInverse(int a, int m) {
+        int m0 = m;
+        int x0 = 0;
+        int x1 = 1;
+
+        if (m == 1) {
+            return 0;
+        }
+
+        while (a > 1) {
+            int q = a / m;
+            int t = m;
+
+            // m is remainder now, process same as Euclid's algorithm
+            m = a % m;
+            a = t;
+            t = x0;
+
+            x0 = x1 - q * x0;
+            x1 = t;
+        }
+
+        // Make x1 positive
+        if (x1 < 0) {
+            x1 += m0;
+        }
+
+        return x1;
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/maths/ChineseRemainderTheoremTest.java b/src/test/java/com/thealgorithms/maths/ChineseRemainderTheoremTest.java
new file mode 100644
index 00000000..31c676d6
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/ChineseRemainderTheoremTest.java
@@ -0,0 +1,54 @@
+package com.thealgorithms.maths;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Arrays;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+
+public class ChineseRemainderTheoremTest {
+    @Test
+    public void testCRTSimpleCase() {
+        List<Integer> remainders = Arrays.asList(2, 3, 2);
+        List<Integer> moduli = Arrays.asList(3, 5, 7);
+        int expected = 23;
+        int result = ChineseRemainderTheorem.solveCRT(remainders, moduli);
+        assertEquals(expected, result);
+    }
+
+    @Test
+    public void testCRTLargeModuli() {
+        List<Integer> remainders = Arrays.asList(1, 2, 3);
+        List<Integer> moduli = Arrays.asList(5, 7, 9);
+        int expected = 156;
+        int result = ChineseRemainderTheorem.solveCRT(remainders, moduli);
+        assertEquals(expected, result);
+    }
+
+    @Test
+    public void testCRTWithSingleCongruence() {
+        List<Integer> remainders = Arrays.asList(4);
+        List<Integer> moduli = Arrays.asList(7);
+        int expected = 4;
+        int result = ChineseRemainderTheorem.solveCRT(remainders, moduli);
+        assertEquals(expected, result);
+    }
+
+    @Test
+    public void testCRTWithMultipleSolutions() {
+        List<Integer> remainders = Arrays.asList(0, 3);
+        List<Integer> moduli = Arrays.asList(4, 5);
+        int expected = 8;
+        int result = ChineseRemainderTheorem.solveCRT(remainders, moduli);
+        assertEquals(expected, result);
+    }
+
+    @Test
+    public void testCRTLargeNumbers() {
+        List<Integer> remainders = Arrays.asList(0, 4, 6);
+        List<Integer> moduli = Arrays.asList(11, 13, 17);
+        int expected = 550;
+        int result = ChineseRemainderTheorem.solveCRT(remainders, moduli);
+        assertEquals(expected, result);
+    }
+}