Difference between sum of the squares of first n natural numbers and square of sum
Given an integer n, find the absolute difference between sum of the squares of first n natural numbers and square of sum of first n natural numbers.
Input : n = 3 Output : 22.0 Sum of first three numbers is 3 + 2 + 1 = 6 Square of the sum = 36 Sum of squares of first three is 9 + 4 + 1 = 14 Absolute difference = 36 - 14 = 22 Input : n = 10 Output : 2640.0
Asked in : biwhiz Company
1. Find the sum of square of first n natural numbers.
2. Find the sum of first n numbers and square it.
3. Find the absolute difference between both the sums and print it.
Below is the implementation of above approach :
// PHP program to find the difference
// between sum of the squares of the
// first n natural numbers and square
// of sum of first n natural number
// Sum of the squares of the
// first n natural numbers is
$l = ($n * ($n + 1) *
(2 * $n + 1)) / 6;
// Sum of n naturals numbers
$k = ($n * ($n + 1)) / 2;
// Square of k
$k = $k * $k;
// Differences between
// l and k
$m = abs($l - $k);
// Driver Code
$n = 10;
// This code is contributed by anuj_67 .
Attention reader! Don’t stop learning now. Participate in the Scholorship Test for First-Step-to-DSA Course for Class 9 to 12 students.