forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumOfGeometricProgression.js
More file actions
Latest commit
38 lines (34 loc) · 1.28 KB
/
Copy pathSumOfGeometricProgression.js
File metadata and controls
38 lines (34 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
Returns the sum of a geometric progression
Article on Geometric Progression: https://en.wikipedia.org/wiki/Geometric_series
Examples:
> sumOfGeometricProgression(2, 0.5, 6)
3.9375
> sumOfGeometricProgression(0.5, 10, 3)
55.5
> sumOfGeometricProgression(0.5, 10, Infinity)
Error: The geometric progression is diverging, and its sum cannot be calculated
*/
/**
*
* @param {Number} firstTerm The first term of the geometric progression
* @param {Number} commonRatio The common ratio of the geometric progression
* @param {Number} numOfTerms The number of terms in the progression
*/
functionsumOfGeometricProgression(firstTerm,commonRatio,numOfTerms){
if(!Number.isFinite(numOfTerms)){
/*
If the number of Terms is Infinity, the common ratio needs to be less than 1 to be a convergent geometric progression
Article on Convergent Series: https://en.wikipedia.org/wiki/Convergent_series
*/
if(Math.abs(commonRatio)<1)returnfirstTerm/(1-commonRatio)
thrownewError(
'The geometric progression is diverging, and its sum cannot be calculated'
)
}
if(commonRatio===1)returnfirstTerm*numOfTerms
return(
(firstTerm*(Math.pow(commonRatio,numOfTerms)-1))/(commonRatio-1)
)
}
export{sumOfGeometricProgression}