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 calculate the sum of square of first n natural numbers
To calculate the sum of square of first n natural numbers in PHP, we can use a simple loop to iterate through each number and add its square to the running total.
Example
Here's a PHP function that calculates the sum of squares ?
<?php
function sum_of_squares($limit)
{
$ini_sum = 0;
for ($i = 1; $i <= $limit; $i++)
$ini_sum += ($i * $i);
return $ini_sum;
}
$limit = 5;
print_r("The sum of square of first 5 natural numbers is ");
echo sum_of_squares($limit);
?>
Output
The sum of square of first 5 natural numbers is 55
How It Works
A function named sum_of_squares is defined that takes the limit up to which square of natural numbers needs to be found. In this function, a sum value is initialized to 0. A for loop runs from 1 to the limit value. In each iteration, the square of the current number ($i * $i) is added to the sum variable. When the loop completes, the function returns the total sum.
Mathematical Formula
The sum of squares of first n natural numbers can also be calculated using the formula: n(n+1)(2n+1)/6. Here's an alternative implementation ?
<?php
function sum_of_squares_formula($n)
{
return ($n * ($n + 1) * (2 * $n + 1)) / 6;
}
$limit = 5;
echo "Using formula: " . sum_of_squares_formula($limit);
?>
Using formula: 55
Conclusion
Both approaches give the same result. The loop method is easier to understand, while the mathematical formula is more efficient for large values of n.
