I have the following code to find the largest prime factors of a number, it works good if I use numbers from 11 digits, but when I use this number: 600851475143, it keeps loading and loading and just don't show the result.
Any advice is welcome
<?php
$number = 600851475143;
$prime = 2;
do {
if($number % $prime == 0) {
$number = $number / $prime;
$primes[] = $prime;
} else {
while(true) {
$prime++;
$true = is_prime($prime);
if($true === true) {
break;
}
}
}
if($number < $prime) break;
} while(true);
function is_prime($number, $prime = 2) {
if($number % $prime == 0) {
return false;
} else if ($number % $prime++ == 0) {
return false;
}
return true;
}
var_dump(max($primes));
?>
It should not be related to the overflow problem, but I think your is_prime()
function, doesn't work in fact
var_dump(is_prime(9)); // bool(true)
Anyway to handle arbitrary precision numbers in PHP you should look here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With