Project Euler Problem 3 (PHP)

Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Problem 3

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

What is the largest prime factor of the number 600851475143 ?

Answer Show ▼

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;
        }
    }
}

Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
This entry was posted in PHP, Programming, Project Euler and tagged , , , . Bookmark the permalink.

2 Responses to Project Euler Problem 3 (PHP)

  1. Kah Thong says:

    I believe you have the wrong solution here?
    This solution is for problem #2.

    • Joseph says:

      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.