How to usethe Formula in PHP

A more efficient way to solve this problem, especially for large values of n, is by using a direct mathematical formula: S = n(n + 1)(2n + 1) / 6.

PHP




<?php
  
function sumOfSquares($n) {
    return ($n * ($n + 1) * (2 * $n + 1)) / 6;
}
  
// Driver code
$n = 5;
echo "Sum of squares of first $n natural numbers is: " 
    . sumOfSquares($n);
  
?>


Output

Sum of squares of first 5 natural numbers is: 55

PHP Program for Sum of Squares of First N Natural Numbers

Calculating the sum of squares of the first n natural numbers is a common problem in programming, demonstrating the application of mathematical formulas, loops, and PHP functions. This article explores various methods to solve this problem in PHP, providing insights into basic arithmetic operations, iterative solutions, and direct formula application.

Similar Reads

Understanding the Problem

The task is to find the sum of squares of the first n natural numbers. Mathematically, it is represented as the sum S = 1^2 + 2^2 + 3^2 + … + n^2. This problem has both iterative and formula-based solutions, offering a good opportunity to explore different programming techniques....

Approach 1: Using a Loop

The simplest way to approach this problem is by using a loop to iterate through the first n natural numbers, squaring each number and adding it to a sum variable....

Approach 2: Using the Formula

...

Approach 3: Using Array Functions

A more efficient way to solve this problem, especially for large values of n, is by using a direct mathematical formula: S = n(n + 1)(2n + 1) / 6....

Approach 4: Recursive Solution

...