The specified sum can be computed using a loop. However, we will also derive the formula. Let f(n) = 1^2 + 2^2 + 3^2 + ... + n^2. Consider the sum:
Expand the sum as follows:
Then, equate the right-hand sides of both equations:
Algorithm implementation
Implement the program using a loop.
scanf("%lld",&n);
for(i = 1; i <= n; i++)
sum += i * i;
printf("%lld\n",sum);Algorithm implementation — formula
Implement the program using the formula.
scanf("%lld",&n);
sum = n * (n + 1) * (2 * n + 1) / 6;
printf("%lld\n",sum);Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
long n = con.nextLong();
long sum = n * (n + 1) * (2 * n + 1) / 6;
System.out.println(sum);
con.close();
}
}Python implementation — formula
Implement the program using the formula.
n = int(input())
sum = n * (n + 1) * (2 * n + 1) // 6;
print(sum)Python implementation — loop
Implement the program using a loop.
n = int(input())
sum = 0
for i in range(1, n + 1):
sum += i * i;
print(sum)