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
PHP program to find the sum of cubes of the first n natural numbers
To find the sum of cubes of the first n natural numbers, we can use a loop to iterate through each number and calculate its cube. The formula for the cube of a number is n³ = n × n × n.
Example
Here's a PHP program that calculates the sum of cubes for the first n natural numbers ?
<?php
function sum_of_cubes($val)
{
$init_sum = 0;
for ($x = 1; $x <= $val; $x++)
$init_sum += $x * $x * $x;
return $init_sum;
}
print_r("The sum of cubes of first 8 natural numbers is ");
echo sum_of_cubes(8);
?>
Output
The sum of cubes of first 8 natural numbers is 1296
How It Works
The sum_of_cubes() function takes a parameter $val representing the number of natural numbers to process. It initializes $init_sum to 0, then uses a for loop to iterate from 1 to $val. For each number $x, it calculates the cube ($x * $x * $x) and adds it to the running sum.
Alternative Method Using Formula
There's also a mathematical formula: sum of cubes of first n natural numbers = [n(n+1)/2]² ?
<?php
function sum_of_cubes_formula($n)
{
$sum = ($n * ($n + 1) / 2);
return $sum * $sum;
}
echo "Using formula: " . sum_of_cubes_formula(8);
?>
Using formula: 1296
Conclusion
Both methods produce the same result, but the formula approach is more efficient for large values of n as it runs in constant time O(1) instead of O(n).
