How to use the formula for the sum of cubes In Javascript

A formula for the sum of cubes of the first ‘n’ natural numbers is used to compute the result directly. The formula is (n * (n + 1) / 2) ^ 2. This formula provides a direct and efficient way to calculate the cube sum. This approach provides a more efficient way to compute the cube sum without iterating through each natural number individually.

Example: Computing the sum of cubes for numbers from 1 to N using a closed-form mathematical formula in JavaScript

Javascript




function cubeSum(n) {
    return ((n * (n + 1)) / 2) ** 2;
  }
   
  console.log(cubeSum(6));


Output

441

Cube Sum of First n Natural Numbers in JavaScript

To find the cube sum, we can iterate over each natural number from 1 to ‘n’. For each number, we will cube it (multiply it by itself twice) and add the result to a running total. This means we are going to add up the cubes of each number from 1 to ‘n’.

There are different methods to cube the sum of the first n natural numbers in JavaScript which are as follows:

Table of Content

  • Using a for-loop
  • Using recursion
  • Using the formula for the sum of cubes
  • Using the reduce() method

Similar Reads

Using a for-loop

The for loop is used to iterate through each natural number from 1 to ‘n’ inclusive, where ‘n’ is the parameter passed to the function. After processing all natural numbers from 1 to ‘n’ in the loop, the function cubeSum returns the final value of sum, which represents the total sum of the cubes of the first ‘n’ natural numbers....

Using recursion

...

Using the formula for the sum of cubes

Recursion is used to calculate the cube sum of the first ‘n’ natural numbers. By using recursion, the function effectively breaks down the problem of finding the cube sum of ‘n’ natural numbers into smaller subproblems, making the code concise and elegant....

Using the reduce() method

...