Summing cubes of natural numbers within a range in JavaScript

Problem

We are required to write a JavaScript function that takes in a range array of two numbers. Our function should find the sum of all the cubes of the numbers that falls in the specified range.

Understanding the Problem

Given a range [a, b], we need to calculate a³ + (a+1)³ + (a+2)³ + ... + b³. For example, with range [4, 11], we calculate 4³ + 5³ + 6³ + 7³ + 8³ + 9³ + 10³ + 11³.

Solution Using For Loop

Here's the implementation that iterates through the range and sums the cubes:

const range = [4, 11];

const sumCubes = ([l, h]) => {
    const findCube = num => num * num * num;
    let sum = 0;
    for(let i = l; i 

Output

4320

Step-by-Step Breakdown

Let's trace through the calculation for range [4, 11]:

const sumCubesWithTrace = ([l, h]) => {
    let sum = 0;
    for(let i = l; i 

4³ = 64
5³ = 125
6³ = 216
7³ = 343
8³ = 512
9³ = 729
10³ = 1000
11³ = 1331
Total sum: 4320

Alternative Solution Using Array Methods

We can also solve this using functional programming approach with array methods:

const sumCubesArray = ([l, h]) => {
    return Array.from({length: h - l + 1}, (_, i) => l + i)
                .map(num => num ** 3)
                .reduce((sum, cube) => sum + cube, 0);
};

console.log(sumCubesArray([4, 11]));
console.log(sumCubesArray([1, 5]));
4320
225

Comparison of Methods

Method Readability Performance Memory Usage
For Loop High Faster Lower
Array Methods Medium Slower Higher

Testing with Different Ranges

const testRanges = [[1, 3], [2, 4], [0, 2]];

testRanges.forEach(range => {
    const result = sumCubes(range);
    console.log(`Range [${range[0]}, ${range[1]}]: ${result}`);
});
Range [1, 3]: 36
Range [2, 4]: 99
Range [0, 2]: 9

Conclusion

The for loop approach is the most efficient method for summing cubes within a range. It provides clear logic, good performance, and minimal memory usage for calculating the sum of cubes of natural numbers.

Updated on: 2026-03-15T23:19:00+05:30

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements