PHP Program to Find Sum of n Natural Numbers
You can find the sum of n natural numbers in PHP using the formula
$sum = $n * ($n + 1) / 2; or by looping from 1 to n and adding each number.Examples
Input5
OutputSum of first 5 natural numbers is 15
Input10
OutputSum of first 10 natural numbers is 55
Input1
OutputSum of first 1 natural number is 1
How to Think About It
To find the sum of n natural numbers, think of adding all numbers from 1 up to n. You can do this by adding each number one by one or use a simple math formula that calculates the total quickly without adding each number.
Algorithm
1
Get the input number n from the user.2
Calculate the sum using the formula sum = n * (n + 1) / 2.3
Print the result.Code
php
<?php $n = 10; // You can change this value $sum = $n * ($n + 1) / 2; echo "Sum of first $n natural numbers is $sum"; ?>
Output
Sum of first 10 natural numbers is 55
Dry Run
Let's trace the example where n = 5 through the code
1
Set n
$n = 5
2
Calculate sum
$sum = 5 * (5 + 1) / 2 = 5 * 6 / 2 = 30 / 2 = 15
3
Print result
Output: Sum of first 5 natural numbers is 15
| n | Calculation | Sum |
|---|---|---|
| 5 | 5 * (5 + 1) / 2 | 15 |
Why This Works
Step 1: Using the formula
The formula n * (n + 1) / 2 quickly calculates the sum of numbers from 1 to n without looping.
Step 2: Multiplication and division
First multiply n by (n + 1), then divide the result by 2 to get the sum.
Step 3: Output the result
Print the sum with a clear message so the user understands the output.
Alternative Approaches
Using a for loop
php
<?php $n = 10; $sum = 0; for ($i = 1; $i <= $n; $i++) { $sum += $i; } echo "Sum of first $n natural numbers is $sum"; ?>
This method uses a loop to add each number one by one, which is easy to understand but slower for large n.
Using recursion
php
<?php function sumNatural($n) { if ($n == 1) return 1; return $n + sumNatural($n - 1); } $n = 10; echo "Sum of first $n natural numbers is " . sumNatural($n); ?>
Recursion calls the function repeatedly but can be less efficient and harder for beginners.
Complexity: O(1) time, O(1) space
Time Complexity
Using the formula takes constant time because it does a fixed number of operations regardless of n.
Space Complexity
The formula uses only a few variables, so it requires constant space.
Which Approach is Fastest?
The formula approach is fastest and most efficient compared to looping or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Formula | O(1) | O(1) | Fastest and simplest for any n |
| For Loop | O(n) | O(1) | Easy to understand, good for small n |
| Recursion | O(n) | O(n) | Demonstrates recursion, less efficient |
Use the formula
n * (n + 1) / 2 for the fastest and simplest solution.Beginners often forget to use parentheses properly in the formula, causing wrong results.