C Program for cube sum of first n natural numbers?

In this problem we will see how we can get the sum of cubes of first n natural numbers. Here we are using one for loop that runs from 1 to n. In each step we are calculating cube of the term and then add it to the sum. This program takes O(n) time to complete. But if we want to solve this in O(1) or constant time, we can use the mathematical formula.

Syntax

sum = 1³ + 2³ + 3³ + ... + n³
sum = [n(n+1)/2]²

Method 1: Using Loop (O(n) Time)

This approach uses a for loop to iterate through each number and calculate its cube −

#include <stdio.h>

long cube_sum_n_natural(int n) {
    long sum = 0;
    int i;
    for (i = 1; i <= n; i++) {
        sum += i * i * i; // cube i and add it with sum
    }
    return sum;
}

int main() {
    int n = 6;
    printf("Sum of cubes of first %d natural numbers: %ld
", n, cube_sum_n_natural(n)); return 0; }
Sum of cubes of first 6 natural numbers: 441

Method 2: Using Mathematical Formula (O(1) Time)

The mathematical formula states that sum of cubes equals the square of sum of natural numbers −

1³ + 2³ + 3³ + ... + n³ = [n(n+1)/2]² where n(n+1)/2 is the sum of first n natural numbers
#include <stdio.h>

long cube_sum_formula(int n) {
    long sum_natural = (long)n * (n + 1) / 2;
    return sum_natural * sum_natural;
}

int main() {
    int n = 6;
    printf("Sum of cubes using formula: %ld
", cube_sum_formula(n)); // Verify with loop method long loop_result = 0; for (int i = 1; i <= n; i++) { loop_result += i * i * i; } printf("Sum of cubes using loop: %ld
", loop_result); return 0; }
Sum of cubes using formula: 441
Sum of cubes using loop: 441

Comparison

Method Time Complexity Space Complexity Best For
Loop Method O(n) O(1) Small values, understanding logic
Formula Method O(1) O(1) Large values, efficiency

Conclusion

Both methods give the same result, but the mathematical formula approach is more efficient for large values of n. The formula leverages the relationship between sum of cubes and square of natural number sums.

Updated on: 2026-03-15T11:02:24+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements