Inverse thinking to find primes

Source: Internet
Author: User

1#include <stdio.h>2 3 intMainvoid)4 {5     Const intLen = -;6     intPrime[len];7      for(intI=0; i<len; i++)8Prime[i] =1;//1 Mark this ordinal number is a prime, 0 is marked as non-prime9      for(intx=2; x<len; X + +)Ten     { One          for(intj=2; x*j<len; J + +) Aprime[x*j]=0; -     } -      for(intk=2; k<len; k++) the     { -         if(prime[k]==1) -printf"%d", k); -     } +printf"\ n"); -     return 0; +}

I can't read the code, look here:

Assuming a number from 2 to n, I ask for the prime numbers, known as 2 primes. I can assume that all are primes. Using an array prime, such as an element with an ordinal number of 4, it is not a prime, that prime[4]=0.

OK, now create the prime, let all values be initialized to 1, and then let 2 gradually increase the multiples (from twice times to M times, this m*2<=n), these 2 multiples are obviously not prime, you need to change the value of the corresponding angle of the element to 0.

Then 2 increases by 1, repeating the process until N. The remaining angular mark corresponds to an element value of 1, and the value of those angular marks is a prime number. You can print it in turn.

Inverse thinking to find primes

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.