Home  >  Article  >  Backend Development  >  How does php determine whether it is a prime number? Three ways to determine prime numbers (code examples)

How does php determine whether it is a prime number? Three ways to determine prime numbers (code examples)

青灯夜游
青灯夜游forward
2018-11-22 14:56:199956browse

The content of this article is to introduce how PHP determines whether it is a prime number? Three ways to determine prime numbers (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What are prime numbers?

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.)

Now we will introduceWhat are the three methods of judging 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:

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 a 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;
    }
}

Summary: The above is the entire content of this article. You can try it yourself to deepen your understanding. I hope it will be helpful to everyone’s learning. More related video tutorials are recommended: PHP中文网!

The above is the detailed content of How does php determine whether it is a prime number? Three ways to determine prime numbers (code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete