The largest prime factor with php

ぐ巨炮叔叔 提交于 2019-12-10 23:13:05

问题


I wrote a program in PHP to find the largest prime factor. I think it is quite optimized, because it loads quite fast. But, there is a problem: it doesn't count the prime factors of very big numbers. Here is the program:

function is_even($s) {      
    $sk_sum = 0;        
    for($i = 1; $i <= $s; $i++) {           
        if($s % $i == 0) { $sk_sum++; }         
    }   
    if($sk_sum == 2) {          
        return true;            
    }          
}

$x = 600851475143; $i = 2; //x is number    
while($i <= $x) {   
    if($x % $i == 0) {
        if(is_even($i)) {
            $sk = $i; $x = $x / $i;
        }
    }
    $i++;   
}
echo $sk;

回答1:


The largest non-overflowing integer in PHP is stored in the constant PHP_INT_MAX.

You won't be able to work with integers larger than this value in PHP.

To see all of PHP's predefined constants, just use:

<?php
echo '<pre>';
print_r(get_defined_constants());
echo '</pre>';
?>

PHP_INT_MAX probably has a value of 2,147,483,647.

To handle numbers of arbitrary precision in PHP, see either the GMP or BC Math PHP extensions.




回答2:


You should read about Prime testing and Sieving.

In particular, you don't need to test whether each of your divisors is prime.

Something like the following would be faster.

while($i <= $x) 
{
    while ($x % $i == 0)
    {
        $sk = $i;
        $x = $x / $i;
    }
    $i++;
}

You can also stop your outer loop when $i reaches sqrt($x), and if you haven't found a divisor yet then you know $x is prime.




回答3:


Well, every language has it's own (while usually same) limitations, so if you exceed this php's limit, you can't get any higher. Max Integer is 9E18.



来源:https://stackoverflow.com/questions/2868251/the-largest-prime-factor-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!