Project Euler Problem 3 (PHP)

Problem 3

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

Answer [spoiler]6857[/spoiler]
Script

Execution Time: 18.15 seconds

function isPrime($n)
{
    for ($x=2; $x<=floor($n/2); $x++) {
        if ($n%$x == 0) {
            return false;
        }
    }

    return true;
}

$comp = 600851475143;

for ($x = 3; $x <= ceil($comp/2); $x = $x+2) {
    if ($comp%$x == 0) {
        $y = $comp / $x;
        if (isPrime($y)) {
            echo $y.PHP_EOL;
            break;
        }
    }
}

2 thoughts on “Project Euler Problem 3 (PHP)

    1. You are correct. Somehow I copied the wrong one in. It has been fixed now and shows the correct solution. Thanks for pointing it out.

Comments closed