Sum of Squares and Cubes

Problem

Read n and print the sum of the squares 1^2 + 2^2 + ... + n^2 on the first line and the sum of the cubes 1^3 + 2^3 + ... + n^3 on the second line.

Constraints

  • 0 <= n <= 1000

Examples

Input

3

Output

Sum of squares: 14
Sum of cubes: 36

Solutions

Best approachTime O(1)Space O(1)

Two known formulas give both sums in constant time. The sum of the cubes is the square of the sum of the numbers.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Find 1^2 + 2^2 + ... + n^2 and 1^3 + 2^3 + ... + n^3.
 * Input   : One integer n (n >= 0).
 * Output  : Two lines: Sum of squares and Sum of cubes.
 * Approach: Use the formulas n(n+1)(2n+1)/6 and (n(n+1)/2)^2.
 * Time    : O(1)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        long n = new Scanner(System.in).nextLong();

        // Step 1: Sum of squares is n(n+1)(2n+1)/6. Example: n = 3 gives 14.
        long squares = n * (n + 1) * (2 * n + 1) / 6;

        // Step 2: Sum of cubes is the square of 1 + 2 + ... + n. Example: n = 3 gives 36.
        long triangular = n * (n + 1) / 2;
        long cubes = triangular * triangular;

        // Step 3: Print both results.
        System.out.println("Sum of squares: " + squares);
        System.out.println("Sum of cubes: " + cubes);
    }
}
Hints (1)
  1. Test the formula for n = 3 by hand.