Project Euler - Problem 6 Solution With PHP

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 = 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.

At first the $sum_of_squares and $sums are equal to 1.

After calculating the hardest part (calculating 1) without using programming we are ready to start out for loop from 2 and add the second powers of the $numbers to $sum_of_squares by also adding the $number to $sums each time.

$sum_of_squares = $sums = 1;

for ($number = 2; $number <= 100; $number++) 
{
    $sum_of_squares += ($number * $number);
    $sums += $number;
}

$result = ($sums * $sums) - $sum_of_squares;

At last we will need to get the second power of $sums and subtract $sum_of_squares from it.

Execution time: 0s

Copyright © Ozan Kurt 2015.

Scroll to Top