Home  >  Article  >  Backend Development  >  How to determine whether a number is prime in php?

How to determine whether a number is prime in php?

青灯夜游
青灯夜游Original
2019-10-12 17:52:085615browse

Prime numbers are also called prime numbers. A natural number greater than 1 that cannot be divided by other natural numbers except 1 and itself is called a prime number; otherwise it is called a composite number. (Note: 1 is not a prime number.) So how does PHP determine whether a number is prime? The following article will introduce it to you.

How to determine whether a number is prime in php?

Let’s introduce what are the three ways to determine prime numbers in php?

Method 1:

Basic method, - counting method.

$num = 7;$n = 0; //用于记录能被整除的个数 -- 计数
for($i = 1;$i <= $num; ++$i){    
    if($num % $i == 0){        
       $n++;
    }
}
if($n == 2){    
   echo "$num 是素数";
}else{    
   echo "$num 不是素数";
}

Method 2:

That is, when a number is equal to the product of two numbers, one of the numbers must be less than half of the number. Use break; as long as one of the numbers can be divided, the loop will end immediately. This reduces the number of loops and speeds up the process.

$num = 5;$flag = true;
for($i = 2;$i <= $num/2;++$i)
{    if($num % $i == 0)
    {        $flag = false;        break;
    }
}if($flag)
{    echo "$num 是素数";
}else{    echo "$num 不是素数";
}

Method 3:

Same as above, when the product of two numbers is equal to one number, then one of the numbers must be less than the square root of the number.

$num = 4;for($i = 2;$i<$num;++$i){    
     if($num % $i == 0){        
         echo "$num 不是素数";        
         break;
    }    
    if($i >= sqrt($num)){        
       echo "$num 是素数";        
       break;
    }
}

For more PHP related knowledge, please visit: PHP Chinese website!

The above is the detailed content of How to determine whether a number is prime in php?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn