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.