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 −

 Live Demo

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

Updated on: 19-Apr-2021

213 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements