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 average of the first n natural numbers that are even
To find the average of the first n natural numbers that are even, we need to calculate the sum of the first n even natural numbers and divide by n. The first n even natural numbers are 2, 4, 6, 8, ..., 2n.
Mathematical Formula
The average of the first n even natural numbers can be calculated using the formula: Average = (n + 1). This is because the sum of first n even numbers is n(n+1) and dividing by n gives us (n+1).
Example
<?php
function even_nums_avg($n)
{
return $n + 1;
}
$n = 11;
echo "The average of the first " . $n . " natural numbers that are even is: ";
echo even_nums_avg($n);
?>
Output
The average of the first 11 natural numbers that are even is: 12
How It Works
The function 'even_nums_avg' uses the mathematical formula where the average of first n even natural numbers equals (n + 1). For n = 11, the first 11 even numbers are: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22. Their sum is 132, and 132 รท 11 = 12, which matches our formula result.
Alternative Approach
Here's another implementation that calculates the sum explicitly ?
<?php
function even_nums_avg_manual($n)
{
$sum = 0;
for ($i = 1; $i <= $n; $i++) {
$sum += 2 * $i; // 2*i gives us the i-th even number
}
return $sum / $n;
}
$n = 5;
echo "Using manual calculation for n = " . $n . ": ";
echo even_nums_avg_manual($n);
?>
Using manual calculation for n = 5: 6
Conclusion
The average of the first n even natural numbers is simply (n + 1). This mathematical insight allows for an efficient O(1) solution instead of calculating the sum iteratively.
