Friday, November 4, 2011

Solution to Project Euler Problem 6 - sum of the squares of the first one hundred natural numbers and the square of the sum.

Problem: 
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.

Answer: 
The sum of the squares of the first ten natural numbers is:338350
The square of the sum of the first 100 natural numbers is: 25502500
The difference between the sum of the squares of the first ten natural numbers and the square of the sum is: 25164150

Solution:

#!/usr/bin/perl -w
use strict;
my ($i,$ulimit,$sosq,$sqos);
$ulimit=100;
print "The sum of the squares of the first ten natural numbers is:";
for ( $i=1; $i<=$ulimit;$i++ )
{
        $sosq+=$i*$i;
        $sqos+=$i;
}


print "$sosq \n";
$sqos=$sqos*$sqos;
print "The square of the sum of the first $ulimit natural numbers is: $sqos \n";


my $diff=$sqos-$sosq;
print "The difference between the sum of the squares of the first ten natural nu
mbers and the square of the sum is: $diff \n";



No comments: