Sum of the squares natural numbers

The sum of the squares of the first ten natural numbers is,  12 + 22 + … + 102 = 385. The square of the sum of the first ten natural numbers is,  (1 + 2 + … + 10)2 = 552 = 3025.  Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

sum(n) = n(n + 1)/2
sum(n^2) = (2n+1) (n+1) n/6

public class Problem6 {
    //brute force implementation
    public void difference() {
        long sum = 0, sumt=0, evalue=3;
        for (long i=1;i<=evalue;i++) {
            sumt+=i;
            sum +=i*i;
        }
        sumt = sumt*sumt;
        long dif = sumt-sum;
        System.out.println(sum + " - " + sumt + " - " + dif);
    }

    public void differencePE() {
        long sum = 0, sumt=0, n=3;
        long sn = n *(n + 1)/2; 
        long snsqrt = (2*n+1)*(n+1)* n/6;
        sn = sn*sn;
        long dif = sn-snsqrt;
        System.out.println(sn + " - " + snsqrt + " - " + dif);
    }

    public static void main(String[] args) {
        Problem6 p = new Problem6();
        p.difference ();
        p.differencePE();
    }
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: