Skip to content

Commit 3af4cfd

Browse files
authored
Add SumOfOddNumbers (#5730)
1 parent 6ef1f7c commit 3af4cfd

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.thealgorithms.maths;
2+
3+
/**
4+
* This program calculates the sum of the first n odd numbers.
5+
*
6+
* https://www.cuemath.com/algebra/sum-of-odd-numbers/
7+
*/
8+
9+
public final class SumOfOddNumbers {
10+
private SumOfOddNumbers() {
11+
}
12+
13+
/**
14+
* Calculate sum of the first n odd numbers
15+
*
16+
* @param n the number of odd numbers to sum
17+
* @return sum of the first n odd numbers
18+
*/
19+
public static int sumOfFirstNOddNumbers(final int n) {
20+
if (n < 0) {
21+
throw new IllegalArgumentException("n must be non-negative.");
22+
}
23+
return n * n;
24+
}
25+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.junit.jupiter.api.Assertions.assertThrows;
4+
5+
import java.util.stream.Stream;
6+
import org.junit.jupiter.api.Assertions;
7+
import org.junit.jupiter.api.Test;
8+
import org.junit.jupiter.params.ParameterizedTest;
9+
import org.junit.jupiter.params.provider.Arguments;
10+
import org.junit.jupiter.params.provider.MethodSource;
11+
12+
public class SumOfOddNumbersTest {
13+
14+
@ParameterizedTest
15+
@MethodSource("inputStream")
16+
void sumOfFirstNOddNumbersTests(int expected, int input) {
17+
Assertions.assertEquals(expected, SumOfOddNumbers.sumOfFirstNOddNumbers(input));
18+
}
19+
20+
private static Stream<Arguments> inputStream() {
21+
return Stream.of(Arguments.of(1, 1), Arguments.of(4, 2), Arguments.of(9, 3), Arguments.of(16, 4), Arguments.of(25, 5), Arguments.of(100, 10));
22+
}
23+
24+
@Test
25+
public void testSumOfFirstNOddNumbersThrowsExceptionForNegativeInput() {
26+
assertThrows(IllegalArgumentException.class, () -> SumOfOddNumbers.sumOfFirstNOddNumbers(-1));
27+
}
28+
}

0 commit comments

Comments
 (0)