Skip to content

Commit ef61ee8

Browse files
fix: reject negative input in SumOfSquares and add tests (#7543)
* fix: reject negative input in SumOfSquares and add tests * style: apply clang-format to SumOfSquares and its test
1 parent af9aad3 commit ef61ee8

2 files changed

Lines changed: 14 additions & 4 deletions

File tree

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
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
*/
109
public 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
}

src/test/java/com/thealgorithms/maths/SumOfSquaresTest.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
package com.thealgorithms.maths;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import org.junit.jupiter.api.Test;
67

78
/**
89
* Test class for SumOfSquares
9-
*
10-
* @author BEASTSHRIRAM
1110
*/
1211
class 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
}

0 commit comments

Comments
 (0)