To get all the primes within the natural number n, it must be less than The multiples of all primes are removed, and the remainder is the prime number. Give the range N of the value to be sifted to find the prime number within. 1 is neither prime nor composite, remove, first with 2 to sift, that is, 2 left, 2 multiples of the elimination, and then the next prime, that is, 3 sieve, 3 left, the multiples of 3 were removed; then the next prime number 5 sieve, 5 left, the multiples of 5 are removed; Mainly used in the Bitset type
1#include <iostream>2#include <string>3#include <bitset>4#include <cmath>5 6 using namespacestd;7 intMain ()8 {9 int ConstMax_number ( +);Ten int ConstMax_test ((int) sqrt (Double) (Max_number)) ; OneBitset<max_number +1>Number ; ANumber.Set(); -number[1] =0; - for(intI1); I!=max_test; ++i) the { - if(Number[i]) { - //Sieve off Multiples - for(intJ (I*i); J <max_number +1; J + =i) + { -NUMBER[J] =0; + } A } at } -cout <<"The number of the primes less than"<< Max_number +1 -<<" is"<< Number.count () <<Endl; - for(intI1); I! = Max_number +1; ++i) - { - if(Number[i]) cout << i <<","; in } -cout <<Endl; toSystem"Pause"); +}
Eratosthenes--Sieve method C + + for prime, with Bitset type