Computer >> Computer tutorials >  >> Programming >> Javascript

Sum all perfect cube values upto n using JavaScript


Problem

We are required to write a JavaScript function that takes in a number n and returns the sum of all perfect cube numbers smaller than or equal to n.

Example

Following is the code −

const num = 23546;
const sumPerfectCubes = (num = 1) => {
   let i = 1;
   let sum = 0;
   while(i * i * i <= num){
      sum += (i * i * i);
      i++;
   };
   return sum;
};
console.log(sumPerfectCubes(num));

Output

164836