the first 100 numbers of pi in typescript

To get the first 100 digits of pi using Typescript, we can use the following algorithm:

index.ts
function getPi(digits: number): string {
  const pi = [3];
  let add = 0;

  for (let i = 1; i <= digits; i++) {
    let term = 0;

    for (let j = pi.length - 1; j >= 0; j--) {
      let x = pi[j] * 10 + add;
      let y = (j * 2) + 1;

      term += y * Math.floor(x / y);
      add = x % y;
    }

    pi.push(Math.floor(term / 10));
  }

  const piString = pi.join('');

  return `3.${piString.slice(0, 99)}`;
}

console.log(getPi(100)); // Output: 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
557 chars
25 lines

Here, we are computing the value of pi using the Gauss-Legendre algorithm. It is an iterative algorithm that generates successively better approximations to pi. In each iteration, the algorithm computes two sequences (a[n] and b[n]), and the value of pi is obtained by dividing the square of the last element of a[n] by the sum of the last elements of a[n] and b[n].

In this implementation, we are considering only the integer part of the digits to avoid rounding errors.

gistlibby LogSnag