euler

Project Euler - Problem 10

Question

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Solution

$sum = 2;
for ($i = 2; $i < 2000000; $i++) {
  if ($i % 2 != 1) {
    continue;
  }
  $d = 3;
  $x = sqrt($i);
  while (($i % $d != 0) && $d < $x) {
    $d += 2;
  }
  if ((($i % $d == 0 && $i != $d) * 1) == 0) {
    $sum += $i;
  }
}
echo $sum;

Time taken to execute: 30.5757 second.

Project Euler - Problem 6

Question

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

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

Project Euler - Problem 5

Question

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Solution


$yes = FALSE;
$limit = 20;
for ($i = $limit; !$yes; $i += $limit) {
for ($j = 2; $j if ($i % $j == 0) {
$yes = TRUE;
}
else {
$yes = FALSE;
break;
}
}
if ($yes) {
echo $i;
break;
}
}

Project Euler - Problem 2

Question

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Solution

$prev = 2;
$prev2 = 1;
$sum = 2;
$_num = 0;
while ($_num < 4000000) {
  $_num = $prev + $prev2;

  $prev2 = $prev;
  $prev = $_num;

Pages