Three methods for php to determine a number as a prime number, and three methods for php to determine a prime number

Source: Internet
Author: User

Three methods for php to determine a number as a prime number, and three methods for php to determine a prime number

What is a prime number?

Prime number. A natural number greater than 1, except 1 and itself, cannot be divisible by other natural numbers called prime numbers; otherwise, it is called a union number. (Note: 1 is not a prime number .)

Method 1:

The basic method is the count method.

$ Num = 7; $ n = 0; // used to record the number of divisible items -- count for ($ I = 1; $ I <= $ num; ++ $ I) {if ($ num % $ I = 0) {$ n ++ ;}} if ($ n = 2) {echo "$ num is a prime number ";} else {echo "$ num is not a prime number ";}

Method 2:

When a number is equal to the product of two numbers, one of them must be less than half of the number. Use break. Once one of them can be wiped out, the cycle ends immediately. This reduces the number of cycles 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 is a prime number ";} else {echo "$ num is not a prime number ";}

Method 3:

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

$ Num = 4; for ($ I = 2; $ I <$ num; ++ $ I) {if ($ num % $ I = 0) {echo "$ num is not a prime number"; break;} if ($ I >= sqrt ($ num) {echo "$ num is a prime number"; break ;}}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.