Project Euler Problem 6

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

PHP Script

<?php
for($a = 1; $a < 101; $a++) {
	$sum1 += $a * $a;
}
for($b = 1; $b < 101; $b++) {
	$sum2 += $b;
}
echo $sum2 * $sum2 - $sum1;
?>

C Script

#include <stdio.h>

int main (int argc, const char * argv[]) {
	int a, b, sum1, sum2, sum3;
    for(a = 1; a < 101; a++) {
		sum1+= a * a;
	}
	for(b = 1; b < 101; b++) {
		sum2+=b;
	}
	sum3 = sum2 * sum2 - sum1;
    printf("%dn", sum3);
    return 0;
}

Manual Solving
Knowing that 12 + 22 + 32 + … + n2 is equal to n * (n + 1) * (2n + 1) / 6, we can conclude that 12 + 22 + 32 + … + 52 is equal to 338350. Also knowing 1 + 2 + 3 + … + n is equal to n(n + a) / 2, we know 1 + 2 + 3 + … + 100 is 5050. Squaring 5050 is 25502500. 25502500 – 338350 is 25164150, which is the final answer.

Leave a Reply

Your email address will not be published.