mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-12 22:56:11 +08:00
Add SumOfOddNumbers (#5730)
This commit is contained in:
25
src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java
Normal file
25
src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
package com.thealgorithms.maths;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This program calculates the sum of the first n odd numbers.
|
||||||
|
*
|
||||||
|
* https://www.cuemath.com/algebra/sum-of-odd-numbers/
|
||||||
|
*/
|
||||||
|
|
||||||
|
public final class SumOfOddNumbers {
|
||||||
|
private SumOfOddNumbers() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculate sum of the first n odd numbers
|
||||||
|
*
|
||||||
|
* @param n the number of odd numbers to sum
|
||||||
|
* @return sum of the first n odd numbers
|
||||||
|
*/
|
||||||
|
public static int sumOfFirstNOddNumbers(final int n) {
|
||||||
|
if (n < 0) {
|
||||||
|
throw new IllegalArgumentException("n must be non-negative.");
|
||||||
|
}
|
||||||
|
return n * n;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.thealgorithms.maths;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.Arguments;
|
||||||
|
import org.junit.jupiter.params.provider.MethodSource;
|
||||||
|
|
||||||
|
public class SumOfOddNumbersTest {
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("inputStream")
|
||||||
|
void sumOfFirstNOddNumbersTests(int expected, int input) {
|
||||||
|
Assertions.assertEquals(expected, SumOfOddNumbers.sumOfFirstNOddNumbers(input));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Stream<Arguments> inputStream() {
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSumOfFirstNOddNumbersThrowsExceptionForNegativeInput() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> SumOfOddNumbers.sumOfFirstNOddNumbers(-1));
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user