Skip to content

Commit de03928

Browse files
add geometric progression
1 parent aa60af5 commit de03928

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.examplehub.maths;
2+
3+
public class GeometricProgression {
4+
5+
/**
6+
* Get nth item of geometric progression.
7+
*
8+
* @param firstItem the first item of geometric progression.
9+
* @param commonRatio the common ratio of geometric progression.
10+
* @param nth the nth.
11+
* @return the nth item of geometric progression.
12+
*/
13+
public static double getNth(double firstItem, double commonRatio, int nth) {
14+
return firstItem * Math.pow(commonRatio, nth - 1);
15+
}
16+
17+
/**
18+
* Sum of geometric progression.
19+
*
20+
* @param firstItem the first item of geometric progression.
21+
* @param commonRatio the common ratio of geometric progression.
22+
* @param nth the nth.
23+
* @return the sum of geometric progression.
24+
*/
25+
public static double sum(double firstItem, double commonRatio, int nth) {
26+
return commonRatio == 1 ?
27+
firstItem * nth :
28+
firstItem * (1 - Math.pow(commonRatio, nth)) / (1 - commonRatio);
29+
}
30+
}
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 GeometricProgressionTest {
8+
@Test
9+
void testGetNth() {
10+
assertEquals(1, GeometricProgression.getNth(1, 1, 100));
11+
assertEquals(8, GeometricProgression.getNth(1, 2, 4));
12+
assertEquals(1024, GeometricProgression.getNth(1, 2, 11));
13+
}
14+
15+
@Test
16+
void testSum() {
17+
assertEquals(15, GeometricProgression.sum(1, 2, 4));
18+
assertEquals(15, GeometricProgression.sum(1, 2, 4));
19+
assertEquals(100, GeometricProgression.sum(1, 1, 100));
20+
}
21+
}

0 commit comments

Comments
 (0)