Coder100
Coder100

Reputation: 305

JavaScript: BigInteger implementation of a geometric sum

Say I have this equation here:

a * (1 - r ^ n) / (1 - r)

Basically, it is the formula for the sum of a geometric sequence. In our case, r is a decimal (float).

I am expecting the resulting number to be greater than the maximum safe integer, so BigInt will have to be used.

Is there a BigInt implementation of the Geometric Sum?

Thanks in advance!

This is what I have tried:

function geoSum(a, r, n) {
  return BigInt(a * ((1 - r ** n) / (1 - n)));
}

Which already becomes Infinity before it can be converted into a BigInt.

Thanks in advance!

Upvotes: 0

Views: 266

Answers (2)

iAmOren
iAmOren

Reputation: 2804

I just wrapped everything with BigInt.

function geoSum(a, r, n) {
  return BigInt(BigInt(a) * (BigInt(BigInt(1) - BigInt(BigInt(r) ** BigInt(n))) /
         BigInt(BigInt(1) - BigInt(n))));
}
geoSum(2,5,10)

returned:

2170138n

I don't know if the result makes sense to you.

Upvotes: 0

Patrick Roberts
Patrick Roberts

Reputation: 51916

You should convert each of the parameters to BigInt before applying the operations:

function geoSum(a, r, n) {
  const an = BigInt(a);
  const rn = BigInt(r);
  const nn = BigInt(n);

  return an * ((1n - rn ** nn) / (1n - nn));
}

const result = geoSum(150, 151, 152);

console.log(String(result));
console.log(Number(result));

Upvotes: 1

Related Questions