Typical C language example: Prime Number judgment

Source: Internet
Author: User

Prime number. In a natural number greater than 1, except for 1 and the integer itself, it cannot be divisible by other natural numbers.

Basic version _ bool isprimer (unsigned N) {If (n <= 1) return false; unsigned I, TEM = SQRT (n) + 1; for (I = 2; I <= TEM; I ++)/* 2 is also a prime number */If (N % I = 0) return false; return true;} upgraded version _ bool isprimer (unsigned N) {If (n = 2) return true; If (n <= 1 | n % 2 = 0) return false; even numbers other than/* 2 are not prime numbers */unsigned I, TEM = SQRT (n) + 1; for (I = 3; I <= TEM; I + = 2) /* I = 2 has been judged before. Here, it starts from 3 and returns false with an odd number */If (N % I = 0; /* and the N entered here is an odd number, and the odd number cannot be divisible by an even number. Therefore, I increase by 2 */return true ;}

Hope to have betterAlgorithm!

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.