Skip to content

Commit aa60af5

Browse files
add arithmetic progression
1 parent 567252d commit aa60af5

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.examplehub.maths;
2+
3+
/**
4+
* https://en.wikipedia.org/wiki/Arithmetic_progression
5+
*/
6+
public class ArithmeticProgression {
7+
8+
/**
9+
* Get nth item.
10+
*
11+
* @param firstItem the initial term of an arithmetic progression.
12+
* @param commonDifference the common difference of successive members.
13+
* @param nth the nth term of the sequence.
14+
* @return the nth tern.
15+
*/
16+
public static int getNth(int firstItem, int commonDifference, int nth) {
17+
return firstItem + (nth - 1) * commonDifference;
18+
}
19+
20+
/**
21+
* Sum of n items of arithmetic progression.
22+
*
23+
* @param firstItem the initial term of an arithmetic progression.
24+
* @param commonDifference the common difference of successive members.
25+
* @param n the numbers of arithmetic progression.
26+
* @return sum of arithmetic progression.
27+
*/
28+
public static int sum(int firstItem, int commonDifference, int n) {
29+
return (2 * firstItem + (n - 1) * commonDifference) * n / 2;
30+
}
31+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.examplehub.maths;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class ArithmeticProgressionTest {
8+
@Test
9+
void testGetNth() {
10+
assertEquals(10, ArithmeticProgression.getNth(1, 1, 10));
11+
assertEquals(19, ArithmeticProgression.getNth(1, 2, 10));
12+
assertEquals(90, ArithmeticProgression.getNth(100, -2, 6));
13+
}
14+
15+
@Test
16+
void testSum() {
17+
assertEquals(55, ArithmeticProgression.sum(1, 1, 10));
18+
assertEquals(5050, ArithmeticProgression.sum(1, 1, 100));
19+
assertEquals(5050, ArithmeticProgression.sum(100, -1, 100));
20+
}
21+
}

0 commit comments

Comments
 (0)