# Calculate the value of PI in JS

I have created an algorithm which calculates the value of PI in JavaScript.

Can this algorithm to be improved?

let PI = 0;
for(let i=0; i<80; i++){
let numerator = Math.pow(factorial(i), 2) *  Math.pow(2, i+1);
let denominator = factorial((2 * i + 1));
PI += numerator / denominator;
}

function factorial(n){
return(n<2)?1:factorial(n-1)*n;
}

console.log("Value of pi: " + PI);

• We can review your code for improvements. However, if you want to store the digits to an array but you don't already have code that does that, then that part of the question is not a code review and should be removed from the question. May 11, 2022 at 19:54
• (It's easier to know some error limit has been "sous"passed for good with alternating series: The (Gregory-)Leibniz series looks promising.) May 12, 2022 at 11:57
• (It may improve precision to sum starting from small terms.) May 12, 2022 at 12:04

There's no need to recalculate the factorials and powers from scratch each time around the loop. Remember the last values and just multiply to get the next value.

Approximate idea (untested, and by a Javascript novice, so likely containing some mistakes):

let PI = 0;
let top = 1;
let pow2 = 2;
let denominator = 1;
for (let i = 1;  i <= 80;  i++) {
PI += top * top * pow2 / denominator;
top *= i;
pow2 *= 2;
denominator *= (2 * i) * (2 * i + 1);
}