PHP program to find the sum of the 5th powers of first n natural numbers

To find the sum of the 5th powers of first n natural numbers, we need to calculate 15 + 25 + 35 + ... + n5. This can be implemented using a simple loop to iterate through numbers and accumulate their fifth powers.

Example

Here's a PHP function that calculates the sum of fifth powers of the first n natural numbers ?

<?php
function sum_of_fifth_pow($val)
{
    $init_sum = 0;
    for ($i = 1; $i <= $val; $i++)
        $init_sum = $init_sum + ($i * $i * $i * $i * $i);
    return $init_sum;
}
$val = 89;
print_r("The sum of fifth powers of the first n natural numbers is ");
echo(sum_of_fifth_pow($val));
?>

Output

The sum of fifth powers of the first n natural numbers is 85648386825

How It Works

The function sum_of_fifth_pow initializes a sum variable to 0. It then uses a for loop to iterate from 1 to n, calculating the fifth power of each number by multiplying it five times ($i * $i * $i * $i * $i) and adding it to the running sum. Finally, it returns the total sum.

Alternative Using pow() Function

You can also use PHP's built−in pow() function for cleaner code ?

<?php
function sum_of_fifth_pow_alt($val)
{
    $init_sum = 0;
    for ($i = 1; $i <= $val; $i++)
        $init_sum += pow($i, 5);
    return $init_sum;
}
$val = 10;
echo "Sum of fifth powers of first $val natural numbers: " . sum_of_fifth_pow_alt($val);
?>
Sum of fifth powers of first 10 natural numbers: 220825

Conclusion

Both approaches effectively calculate the sum of fifth powers. The manual multiplication method is more explicit, while using pow() makes the code more readable and maintainable.

Updated on: 2026-03-15T09:06:20+05:30

282 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements