How to use Mathematical Formulae In PHP
The mathematical formula to find the sum of first N natural number is N * (N + 1) / 2.
Example:
PHP
<?php $N = 5; $sum = $N * ( $N + 1) / 2; echo "Sum of first " . $N . " Natural Numbers : " . $sum ; ?> |
Output
Sum of first 5 Natural Numbers : 15
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:
Table of Content
- Using for Loop
- Using Mathematical Formulae