Open In App

Sum of First N Natural Number in PHP

Given a number N, the task is to find the sum of the first N natural numbers in PHP.



Examples:

Input: N = 5
Output: 15
Explanation: We will Add the Numbers till N
i.e. 1 + 2 + 3 + 4 + 5 = 15
Input: N = 10
Output: 55

There are different methods to find the sum of first N natural numbers, these are:



Using for Loop

We will iterate a loop from 1 to N and add all elements to get the sum of first N natural numbers.

Example:




<?php
  
$N = 5;
$sum = 0;
  
for ($i = 1; $i <= $N; $i++) 
    $sum = $sum + $i;
      
echo "Sum of first " . $N
    " Natural Numbers : " . $sum;
  
?>

Output
Sum of first 5 Natural Numbers : 15

Using Mathematical Formulae

The mathematical formula to find the sum of first N natural number is N * (N + 1) / 2.

Example:




<?php
  
$N = 5;
  
$sum = $N * ($N + 1) / 2;
  
echo "Sum of first " . $N
    " Natural Numbers : " . $sum;
  
?>

Output
Sum of first 5 Natural Numbers : 15

Article Tags :