Skip to content

Commit cd3974c

Browse files
authored
merge: Added Sum of GP (TheAlgorithms#807)
1 parent e83b570 commit cd3974c

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

Maths/SumOfGeometricProgression.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
Returns the sum of a geometric progression
3+
Article on Geometric Progression: https://en.wikipedia.org/wiki/Geometric_series
4+
Examples:
5+
> sumOfGeometricProgression(2, 0.5, 6)
6+
3.9375
7+
> sumOfGeometricProgression(0.5, 10, 3)
8+
55.5
9+
> sumOfGeometricProgression(0.5, 10, Infinity)
10+
Error: The geometric progression is diverging, and its sum cannot be calculated
11+
*/
12+
13+
/**
14+
*
15+
* @param {Number} firstTerm The first term of the geometric progression
16+
* @param {Number} commonRatio The common ratio of the geometric progression
17+
* @param {Number} numOfTerms The number of terms in the progression
18+
*/
19+
function sumOfGeometricProgression (firstTerm, commonRatio, numOfTerms) {
20+
if (!Number.isFinite(numOfTerms)) {
21+
/*
22+
If the number of Terms is Infinity, the common ratio needs to be less than 1 to be a convergent geometric progression
23+
Article on Convergent Series: https://en.wikipedia.org/wiki/Convergent_series
24+
*/
25+
if (Math.abs(commonRatio) < 1) return firstTerm / (1 - commonRatio)
26+
throw new Error('The geometric progression is diverging, and its sum cannot be calculated')
27+
}
28+
29+
if (commonRatio === 1) return firstTerm * numOfTerms
30+
31+
return (firstTerm * (Math.pow(commonRatio, numOfTerms) - 1)) / (commonRatio - 1)
32+
}
33+
34+
export { sumOfGeometricProgression }
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { sumOfGeometricProgression } from '../SumOfGeometricProgression'
2+
3+
describe('Sum Of Geometric Progression', () => {
4+
it('should return the sum of a finite GP', () => {
5+
expect(sumOfGeometricProgression(100, 1.5, 4)).toBe(812.5)
6+
})
7+
8+
it('should return the sum of an infinite GP', () => {
9+
expect(sumOfGeometricProgression(2, 0.5, Infinity)).toBe(4)
10+
})
11+
})

0 commit comments

Comments
 (0)