codingtests/solutions/ProjectEuler/046/solve.php

62 lines
1.1 KiB
PHP
Raw Normal View History

2024-07-23 09:13:29 +00:00
<?php
/*
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2 * 1^2
15 = 7 + 2 * 2^2
21 = 3 + 2 * 3^2
25 = 7 + 2 * 3^2
27 = 19 + 2 * 2^2
33 = 31 + 2 * 1^2
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
*/
$primes = [2];
$composites = [];
$twicesquares = [];
function is_prime(int $n) :bool{for($i=$n**.5|1;$i&&$n%$i--;);return!$i&&$n>1;}
for ($i= 3; $i<6000; $i += 2) {
if (is_prime($i))
{
$primes[] = $i;
}
else
{
$composites[] = $i;
}
}
for($i=1; $i<100; $i++)
{
$twicesquares[] = 2*($i*$i);
}
foreach($composites as $composite)
{
$count = 0;
foreach($primes as $prime)
{
if($prime > $composite)
{
break;
}
if(in_array($composite-$prime, $twicesquares))
{
$count++;
break;
}
}
if($count == 0)
{
echo "Found $composite\n";
die;
}
}