PHP program to find the sum of odd numbers within a given range

In PHP, you can find the sum of odd numbers within a given range using different approaches. Here's a mathematical approach that uses a formula to calculate the sum efficiently.

Using Mathematical Formula

This method calculates the sum of odd numbers using the mathematical property that the sum of first n odd numbers equals n²?

<?php
function odd_num_sum($val)
{
    $entries = (int)($val + 1) / 2;
    $sum = $entries * $entries;
    return $sum;
}

function num_in_range($low, $high)
{
    return odd_num_sum($high) - odd_num_sum($low - 1);
}

$low = 3;
$high = 23;
echo "The sum of odd natural numbers between " . $low . " and " . $high . " is " . num_in_range($low, $high);
?>
The sum of odd natural numbers between 3 and 23 is 169

Using Loop Method

A simpler approach using a loop to iterate through the range and add odd numbers?

<?php
function sumOddNumbers($start, $end) {
    $sum = 0;
    for ($i = $start; $i <= $end; $i++) {
        if ($i % 2 != 0) {
            $sum += $i;
        }
    }
    return $sum;
}

$low = 3;
$high = 23;
echo "Sum of odd numbers from " . $low . " to " . $high . " is: " . sumOddNumbers($low, $high);
?>
Sum of odd numbers from 3 to 23 is: 143

How It Works

The mathematical method works by calculating the sum of all odd numbers from 1 to the upper limit, then subtracting the sum from 1 to (lower limit - 1). The loop method simply iterates through each number in the range and adds it to the sum if it's odd (remainder when divided by 2 is not zero).

Conclusion

Both methods effectively find the sum of odd numbers in a range. The loop method is more intuitive, while the mathematical approach is more efficient for large ranges.

Updated on: 2026-03-15T09:07:36+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements