Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP not working when trying to find largest prime factor of 600851475143 in javascript and java works perfect

Tags:

php

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));
?>
like image 254
user3482288 Avatar asked Nov 02 '22 02:11

user3482288


1 Answers

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

like image 66
emiliano.bovetti Avatar answered Nov 15 '22 05:11

emiliano.bovetti