Find all prime numbers smaller than N

Source: Internet
Author: User

In the written test questions, the probability of finding a prime number is relatively high. I did it yesterday. It is not very difficult, but I can examine the programmer's mathematical and coding skills.

It is ideal to use nested loops. How can we reduce the number of loops? How can we find all prime numbers smaller than N?

It is impossible to divide a number with all numbers smaller than it. Just check the square root of N. However, there is still a precision issue when the root number is used directly. This may cause errors.

Simply write the judgment condition as I * I <= N. The truth is that I is more than the square root of N, before checking the first I divisor N, You can first check whether N can be divisible if it is smaller than the second I.

The following calculate the prime number:

[] FindPrime ([] prime = [max + 1 = (j = 2; j * j <= max; j ++ (k = 2 * j; k <= max; k ++ (k % j = 0 prime [k] = 1 (I = 2; I <max; I ++ (prime [I] = 0 [] p = (I = 0; I <list. size (); I ++ = [] prime = Prime. findPrime (1000 (I = 0; I <prime. length; I ++ ""

 

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.