File tree Expand file tree Collapse file tree
main/java/com/thealgorithms/maths
test/java/com/thealgorithms/maths Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1616 runs-on : ubuntu-latest
1717 steps :
1818 - uses : actions/checkout@v7
19- - uses : actions/setup-python@v6.3 .0
19+ - uses : actions/setup-python@v7.0 .0
2020 with :
2121 python-version : ' 3.13'
2222
Original file line number Diff line number Diff line change 55 * Find minimum number of perfect squares that sum to given number
66 *
77 * @see <a href="https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem">Lagrange's Four Square Theorem</a>
8- * @author BEASTSHRIRAM
98 */
109public final class SumOfSquares {
1110
@@ -16,10 +15,15 @@ private SumOfSquares() {
1615 /**
1716 * Find minimum number of perfect squares that sum to n
1817 *
19- * @param n the target number
18+ * @param n the target number (must be non-negative)
2019 * @return minimum number of squares needed
20+ * @throws IllegalArgumentException if n is negative
2121 */
2222 public static int minSquares (int n ) {
23+ if (n < 0 ) {
24+ throw new IllegalArgumentException ("Input must be non-negative" );
25+ }
26+
2327 if (isPerfectSquare (n )) {
2428 return 1 ;
2529 }
Original file line number Diff line number Diff line change 11package com .thealgorithms .maths ;
22
33import static org .junit .jupiter .api .Assertions .assertEquals ;
4+ import static org .junit .jupiter .api .Assertions .assertThrows ;
45
56import org .junit .jupiter .api .Test ;
67
78/**
89 * Test class for SumOfSquares
9- *
10- * @author BEASTSHRIRAM
1110 */
1211class SumOfSquaresTest {
1312
@@ -65,4 +64,11 @@ void testEdgeCases() {
6564 // Test edge case
6665 assertEquals (1 , SumOfSquares .minSquares (0 )); // 0^2
6766 }
67+
68+ @ Test
69+ void testNegativeInput () {
70+ // Negative inputs should throw IllegalArgumentException
71+ assertThrows (IllegalArgumentException .class , () -> SumOfSquares .minSquares (-1 ));
72+ assertThrows (IllegalArgumentException .class , () -> SumOfSquares .minSquares (-10 ));
73+ }
6874}
You can’t perform that action at this time.
0 commit comments