P.E.6: Sum Square Difference

The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385

The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 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.


This problem is from Project Euler.


The answer is 25164150.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

5 solutions

Diego Barreto
Mar 17, 2015

C++ solution:

#include<iostream>

using namespace std;

int main (){
    int S1=0, S2=0;
    int i=1, j=1;

    while(i<=100){
        S1=S1+i*i;
        i++;
    }

    while(j<=100){
        S2=S2+j;
         j++;   
    }

    cout << S2*S2-S1;

    return 0;
}
Aryan Gaikwad
Feb 25, 2015

Java solution (Try online https://ideone.com/onQ94s) -

int sum1 = 0, sum2 = 0, j;
for(int i = 1; i <= 100; i++)
    sum1 += i*i;
for(j = 1; j <= 100; j++)
    sum2 += j;
sum2 *= sum2;

System.out.println(sum2 - sum1);
Brian Brooks
Dec 1, 2014

Naive direct translation in Python:

(sum(range(1,101))**2) - sum([x**2 for x in range(1,101)])
Daniel Barnhurst
Nov 13, 2014

It's simple in Haskell:

1
(sum [1..100])^2 - sum [ x*x | x <- [1..100]] 

Arvind Srinivasan
Oct 21, 2014

My python code is as follows:

# -*- coding: utf-8 -*-
 """
Euler Problem #6:
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 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.
"""
 prod=0 
 for i in range(1,101):
    square_of_each= i*i
    prod = prod + square_of_each #Sum of squares of first 100 natural numbers
print "The sum of the squares of the first 100 natural numbers is: ", prod
n=100
sum = n*(n + 1)//2
square_of_all= sum*sum
print "The sum of the squares of the first 100 natural numbers is: ", square_of_all
print "The difference between them is: ",square_of_all - prod
raw_input()

Hope this helps!!

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...