Files
JavaScript/Maths/SumOfGeometricProgression.js
Roland Hummel 86d333ee94 feat: Test running overhaul, switch to Prettier & reformat everything (#1407)
* chore: Switch to Node 20 + Vitest

* chore: migrate to vitest mock functions

* chore: code style (switch to prettier)

* test: re-enable long-running test

Seems the switch to Node 20 and Vitest has vastly improved the code's and / or the test's runtime!

see #1193

* chore: code style

* chore: fix failing tests

* Updated Documentation in README.md

* Update contribution guidelines to state usage of Prettier

* fix: set prettier printWidth back to 80

* chore: apply updated code style automatically

* fix: set prettier line endings to lf again

* chore: apply updated code style automatically

---------

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
2023-10-04 02:38:19 +05:30

39 lines
1.3 KiB
JavaScript

/*
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
*/
function sumOfGeometricProgression(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) return firstTerm / (1 - commonRatio)
throw new Error(
'The geometric progression is diverging, and its sum cannot be calculated'
)
}
if (commonRatio === 1) return firstTerm * numOfTerms
return (
(firstTerm * (Math.pow(commonRatio, numOfTerms) - 1)) / (commonRatio - 1)
)
}
export { sumOfGeometricProgression }