Sum all perfect cube values upto n using JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 19-Apr-2021 11:27:42
Advertisements