Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Understanding Perfect Cubes
Perfect cubes are numbers that can be expressed as n³ where n is an integer. For example: 1³ = 1, 2³ = 8, 3³ = 27, 4³ = 64, etc.
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
How It Works
The function starts with i = 1 and continues while i³ ? n. For our example with n = 23546:
// Let's trace through smaller example (n = 100)
const traceExample = (num) => {
let i = 1;
let sum = 0;
console.log(`Finding perfect cubes up to ${num}:`);
while(i * i * i <= num){
const cube = i * i * i;
sum += cube;
console.log(`${i}³ = ${cube}, running sum = ${sum}`);
i++;
}
return sum;
};
console.log("Final result:", traceExample(100));
Finding perfect cubes up to 100: 1³ = 1, running sum = 1 2³ = 8, running sum = 9 3³ = 27, running sum = 36 4³ = 64, running sum = 100 Final result: 100
Optimized Version
We can make the code more readable by calculating the cube once per iteration:
const sumPerfectCubesOptimized = (num = 1) => {
let i = 1;
let sum = 0;
let cube = 1;
while(cube <= num){
sum += cube;
i++;
cube = i * i * i;
}
return sum;
};
console.log(sumPerfectCubesOptimized(23546));
164836
Edge Cases
console.log(sumPerfectCubes(0)); // No perfect cubes ? 0 console.log(sumPerfectCubes(1)); // Only 1³ = 1 console.log(sumPerfectCubes(8)); // 1³ + 2³ = 1 + 8 = 9
0 1 9
Conclusion
This algorithm efficiently finds all perfect cubes up to n by iterating through integers and checking if their cubes are within the limit. The time complexity is O(?n) since we only iterate up to the cube root of n.
Advertisements
