A formula to find prime numbers in a loop

烂漫一生 提交于 2019-11-26 02:38:15

问题


I need to find prime numbers with for loop or while loop

I wrote this but this is wrong

<?php
$i = 1;
while($i<5)
{
    for($j=1; $j<=$i; $j++)
    {
        if ($j != 1 && $j != $i)
        {
            echo $i . \"/\" . $j . \"=\" . $i%$j . \"<br />\";
            if ($i%$j != 0)
            {
                echo $i . \"<br />\";
            }
        }
    }
    echo \"<br />\";
    $i += 1;
}
?>

Is there a way to divide a number with an array to find the remaining?


回答1:


Here's a little function that I found: (http://icdif.com/computing/2011/09/15/check-number-prime-number/) Seemed to work for me!

function isPrime($num) {
    //1 is not prime. See: http://en.wikipedia.org/wiki/Prime_number#Primality_of_one
    if($num == 1)
        return false;

    //2 is prime (the only even number that is prime)
    if($num == 2)
        return true;

    /**
     * if the number is divisible by two, then it's not prime and it's no longer
     * needed to check other even numbers
     */
    if($num % 2 == 0) {
        return false;
    }

    /**
     * Checks the odd numbers. If any of them is a factor, then it returns false.
     * The sqrt can be an aproximation, hence just for the sake of
     * security, one rounds it to the next highest integer value.
     */
    $ceil = ceil(sqrt($num));
    for($i = 3; $i <= $ceil; $i = $i + 2) {
        if($num % $i == 0)
            return false;
    }

    return true;
}



回答2:


You can use this PHP function gmp_nextprime()




回答3:


This a basic implementation :

function prima($n){

  for($i=1;$i<=$n;$i++){  //numbers to be checked as prime

          $counter = 0; 
          for($j=1;$j<=$i;$j++){ //all divisible factors


                if($i % $j==0){ 

                      $counter++;
                }
          }

        //prime requires 2 rules ( divisible by 1 and divisible by itself)
        if($counter==2){

               print $i." is Prime <br/>";
        }
    }
} 

prima(20);  //find prime numbers from 1-20

This will output

 2 is Prime 
 3 is Prime 
 5 is Prime 
 7 is Prime 
 11 is Prime 
 13 is Prime 
 17 is Prime 
 19 is Prime 

Complete Logic step-by-step and visual analogy here : Here




回答4:


Here is a one-liner I found a while back to check for primes. It uses tally marks (unary math) to determine:

function is_prime_via_preg_expanded($number) {
    return !preg_match('/^1?$|^(11+?)\1+$/x', str_repeat('1', $number));
}

Check all numbers sequentially for primes:

$i=2; // start here (2 is the first prime)
while (1) { // neverending loop
    if (is_prime_via_preg_expanded($i)) echo $i." <br />\n";
    $i++;
}

To check only a range of numbers for primes like in the provided example:

$start = 2; // start here (2 is the first prime)
$end = 100;

$i=$start;
while ($i<=$end) {
    if (is_prime_via_preg_expanded($i)) echo $i." <br />\n";
    $i++;
}



回答5:


Without math function:

function isPrimeNumber($i) {
    $n = 2;
    while ($n < $i) {
        if ($i % $n) {
            $n++;
            continue;
        }

        return false;
    }

    return true;
}



回答6:


I know it is too late, but I found that this solution is more elegant.

function isPrime($num)
{
    if ($num < 2) {
        return false;
    }
    for ($i = 2; $i <= $num / 2; $i++) {
        if ($num % $i == 0) {
            return false;
        }
    }

    return true;
}



回答7:


Anything who's sqrt() is false or any float value is prime number




回答8:


This, I believe, is a quite efficient routine, which lists all the primes up to 1000.

It tests each number ($x) in order to see if it has any factors (other than itself and 1, of course).

Mathematically it is not necessary to test all lower numbers as possible factors, only lower primes up to the square root of $x. This is enabled by storing primes as they are found in an array (which I think is the strategy the OP was referring to).

As soon as the first prime factor is found, we know that $x is not prime, and so no further testing of that value of $x is needed and we can break out of the foreach loop.

$primes = array();
for ($x = 2; $x <= 1000; $x++) {
    $xIsPrime = TRUE;
    $sqrtX = sqrt($x);
    foreach ($primes as $prime) if ($prime > $sqrtX || ((!($x % $prime)) && (!$xIsPrime = FALSE))) break;
    if ($xIsPrime) echo ($primes[] = $x)  . "<br>";
}



回答9:


Sieve_of_Eratosthenes is simple and faster algorithm to find prime numbers.

function getPrimes($finish)
    {
        $number = 2;
        $range = range($number,$finish);
        $primes = array_combine($range,$range);
        while($number*$number < $finish){
            for($i=$number; $i<=$finish; $i+=$number){
                if($i==$number){
                    continue;
                }
                unset($primes[$i]);
            }
            $number = next($primes);
        }
        return $primes;
    }



回答10:


<?php

    $n = 11;
    $o = $_POST["maxprime"];
    echo 'The script calculated the next primenumbers:</br>';
    echo '2, 3, 5, 7, ';
    while (true) { 
        $t = 6;
        while (true) { 
            if ($n % ($t - 1) == 0) {
                break;
            } 
            if ($n % ($t + 1) == 0) {
                break;
            }
            if ($t > sqrt($n)) {
                echo("$n,  "); 
                break;
            } 
            $t += 6; 
        }
        if (($n + 1) % 6 == 0) {
            $n += 2;
        } else {
            $n += 4;
        } 
        if ($n > $o) {
            break;
        }
    }

?>

http://www.primenumbergenerator.com/




回答11:


Below programs is simple with two for loops and ignores 1 and self values in iteration. It will print the prime numbers,

function get_primenumbers($length) {
    //Ignore 1
    for($i = 2; $i <= $length; $i++){
        $prime = true;
        for($j = 2; $j <= $i; $j++){
            //Ignore same number
            if(($i != $j) && ($i % $j == 0)){
                $prime = false;
                break;
            }
        }

        if(!$prime){
            echo "$i is not prime <br />";
        }else{
            echo "$i is prime <br />";
        }
    }
}



回答12:


i know this is coming kind of late, but hope it helps someone.

    function prime_number_finder($range)
    {
        $total_count=0;//intitialize the range keeper

        $i=1;//initialize the numbers to check

        while ($total_count<=$range)
        {
           $count=0;//initialize prime number inner count
           $k=$i;
           while ($k!=0)
           {

             if(($i%$k)==0)
             {
              $count++;
             }
              $k--;
           }
           //condition to check if a number is prime 
          if($count==2 || $count==1)
           {
            echo $i."</br>";//output the prime number;
            $total_count++;
            $i++;

           }
           //number is not prime
           if($count>2)
           {
             //$total_count++;
            $i++;
           }

        }
    }

//example prime_number_finder(200);




回答13:


$n = 7;

if ($n == 1) {
    echo 'Not a Prime or Composite No.';
}

$set = 0;
for ($index = 2; $index <= $n/2; $index++) {

    if ($n % $index === 0) {
        $set = 1;
        break;
    }
}

if ($set) {
    echo 'Composite';
} else {
    echo 'Prime';
}



回答14:


Find prime numbers between 1 and 10000, using a closure in array_filter():

$start = 2;
$step = 10000;

$stop = $start + $step;
$candidates = range($start, $stop);    
for($num = 2; $num <= sqrt($stop); ++$num){                        
    $candidates = array_filter($candidates,
        function ($v) use (&$num){
             return ($v % $num) != 0 || $v == $num ;
        }
    );
}
print_r($candidates);

Edit: 1 is not a prime number




回答15:


The best way to check if a number is prime is to see if it is divisible by any prime number before it. Pi(x) is the one I keep seeing everywhere... You can see a bit more information on Prime Counting on wikipedia.

So the most efficient way I can think of at the moment is as follow:

class prime
{
    public $primes = [ 2, 3, 5, 7 ];
    public $not_prime = [ 1, 4, 6, 8, 9 ];
    public function is_prime( int $n )
    {
        if ( $n <= 1 ) return false;
        if ( in_array( $n, $this->primes ) ) return true;
        if ( in_array( $n, $this->not_prime ) ) return false;
        for( $i = 0; $i < count( array_slice( $this->primes, 0, $this->prime_count( $n ) ) ) || $i == $n; $i++ )
        {
            if ( $n % $this->primes[ $i ] == 0 ) return false;
        }
        return true;
    }
    public function build_primes_to( int $n )
    {
        for ( $i = end( $this->primes ) + 1; $i <= $n; $i++ )
        {
            if ( $this->is_prime( $i ) )
            {
                $this->primes[] = $i;
            }
            else
            {
                $this->not_prime[] = $i;
            }
        }
    }
    public function prime_count( $n )
    {
        $ln = log( $n );
        if ( $ln == 0 ) return 1;
        return intval( ceil( $n / $ln ) );
    }
}

Which isn't actually very efficient, well, not when it comes to building the list of prime numbers... I've been working on a better way of building the list here, though it would be just as easy and far more efficient to find a list online and use that.

Usage of the above would be along the lines of:

$find_to = 1000;
$prime = new prime();
$prime->build_primes_to( $find_to );
print "<pre>";
for ( $i = 1; $i < $find_to; $i++ )
{
    print "$i is " . ( !$prime->is_prime( $i ) ? "not " : "" ) . "prime\n";
}



回答16:


I know this is coming a bit late, but here's a simple program to help you do just what you're asking for...

<?php 
 //Prime Function
 function fn_prime($number) {
    $i = 2; $result = TRUE;
    while($i < $number) {
        if(!($number%$i)) {
            $result = FALSE;
        }
        $i++;
    }
    return $result;
 }

//Declare integer variable...
$k = 0;

//Start Loop up to any number of your choice for e.g. 200
while($k < 200) {
    if(fn_prime($k)) {
        echo "$k is a prime number<br/>";
    } else {
        echo "$k is not a prime number!<br/>";
    }
    $k++;
}

?>



回答17:


<?php
function prime_number($num){
    for( $j = 2; $j <= $num; $j++ )
    {
        for( $k = 2; $k < $j; $k++ )
        {
            if( $j % $k == 0 )
            {
                break;
            }
        }
        if( $k == $j )
            echo "Prime Number : ".$j."<br>";
    }
}
prime_number(23);
?>



回答18:


Enchanced version of @Farkie answer made especially for checking primes in loops.

function isPrime_v2($num) {
    static $knownPrimes=[3]; // array to save known primes

    if($num == 1)
        return false;

    if($num == 2 || $num == 3) //added '3'
        return true;

    if($num % 2 == 0)
        return false;

    $ceil = ceil(sqrt($num)); //same purpose, good point from Farkie

    // Check against known primes to shorten operations
    // There is no sense to check agains numbers in between
    foreach($knownPrimesas $prime){
        if ($prime>$ceil)
            break;
        if($num===$prime)
            return true;
        if($num % $prime == 0)
            return false;
    }


    /**
     * end($knownPrimes) % 2 !==0 - mathematically guaranteed
     * start with latest known prime
     */
    for($i = end($knownPrimes)+2; $i <= $ceil; $i = $i + 2) {
        if($num % $i == 0)
            return false;
    }
    $knownPrimes[]=$num;
    return true;
}

Benchmark with phpfiddle.org. V1 - Farkie answer, V2 - Enchanced version

V1 (1 to 5,000,000): divisions=330 929 171; primes=348 513; time=21.243s
V2 (1 to 5,000,000): divisions=114 291 299; primes=348 513; time=10.357s

NOTE! isPrime_v2 function is applicable ONLY in case of looping from 3. Otherwise saved $knownPrimes array will have insufficient history.




回答19:


Here's another very simple but quiet effective approach:

function primes($n){

    $prime = range(2 , $n);

    foreach ($prime as $key => $value) {

        for ($i=2; $i < $value ; $i++) { 

            if (is_int($value / $i)) {

                unset($prime[$key]);
                break;
            }
        }
    }

    foreach ($prime as $value) {
        echo $value.'<br>';
    }
}

primes(1000);



回答20:


<?php 
$limit=100;

$i=1;


outer:while($i<=$limit){
    $j=2;
    while($j<$i){
        if($i%$j==0){
            $i++;
            goto outer;
        }
        $j++;
    }
    echo $i;
    echo "<br/>";
    $i++;
}


?>


来源:https://stackoverflow.com/questions/16763322/a-formula-to-find-prime-numbers-in-a-loop

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