|
| 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 } |
0 commit comments