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

青灯夜游
Release: 2023-04-04 13:06:02
forward
9962 people have browsed it

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 不是素数";
}
Copy after login

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 不是素数";
}
Copy after login

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;
    }
}
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template