PHP program to find the sum of cubes of natural numbers that are odd

To find the sum of cubes of natural numbers that are odd, we iterate through numbers, check if they are odd, and add their cubes to the sum.

Example

The following example calculates the sum of cubes of the first 8 odd natural numbers ?

<?php
function sum_of_cubes_odd($val)
{
    $init_sum = 0;
    $count = 0;
    $i = 1;
    
    while ($count < $val) {
        if ($i % 2 != 0) {
            $init_sum += $i * $i * $i;
            $count++;
        }
        $i++;
    }
    return $init_sum;
}

echo "The sum of cubes of first 8 natural numbers that are odd is ";
echo sum_of_cubes_odd(8);
?>
The sum of cubes of first 8 natural numbers that are odd is 6084

How It Works

The function sum_of_cubes_odd() takes a parameter that specifies how many odd numbers to process. It uses a while loop to iterate through natural numbers starting from 1, checking if each number is odd using the modulo operator (% 2 != 0). When an odd number is found, its cube is calculated and added to the running sum. The process continues until we have processed the required count of odd numbers.

Conclusion

This approach efficiently finds the sum of cubes of odd natural numbers by iterating through numbers sequentially and filtering for odd values. The algorithm ensures we get exactly the specified count of odd numbers.

Updated on: 2026-03-15T09:05:58+05:30

353 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements