Editorial
The specified sum can be computed using a loop. However, we will also derive the formula. Let . Consider the sum:
Expand the sum as follows:
Then, equate the right-hand sides of both equations:
Algorithm realization
Implement the program using a loop.
scanf("%lld",&n); for(i = 1; i <= n; i++) sum += i * i; printf("%lld\n",sum);
Algorithm realization – formula
Implement the program using the formula.
scanf("%lld",&n); sum = n * (n + 1) * (2 * n + 1) / 6; printf("%lld\n",sum);
Java realization
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 realization — formula
Implement the program using the formula.
n = int(input()) sum = n * (n + 1) * (2 * n + 1) // 6; print(sum)
Python realization — loop
Implement the program using a loop.
n = int(input()) sum = 0 for i in range(1, n + 1): sum += i * i; print(sum)