Erato Sieve Method (Sieve of Eratosthenes) to calculate the prime number.

Source: Internet
Author: User

The Erato method (Sieve of Eratosthenes) is a method for finding all primes less than n.
Start by creating an integer 2~n table, looking for I? Integer, which is programmed to implement this algorithm, and discusses the computational time.

Since they are implemented by deletion, and 1 and 0 are not prime numbers, they are removed from 2,3,5 and their multiples.

Use data[] to store all the numbers, replacing the good number in the presence of data[]

Instead, just make the 2,3,5 and the number that divides the numbers to zero: if (data[j]% i = = 0) data[j]==0;

The code snippet implemented is:

for (i = 2; i < n; i++) for (j = i + 1; j < N; j + +) if (data[j]! = 0 && data[j]% i = = 0) Data[j] = 0;

So the final complete implementation process is:

#include <iostream> #include <math.h>using namespace std; #define MAX 50000int n;int data[max];class rox{ Public:void Show (), void creat (), void Run ();p rivate:int I, J;}; void Rox::creat () {for (i = 0; I <= N; i++) data[i] = i;} void Rox::run () {for (i = 2, i < n; i++) {for (j = i + 1; j < N; j + +) {if (data[j]! = 0 && data[j]% i = = 0) Dat A[J] = 0;}}} void  Rox::show () {for (i = 0; I <=n; i++) {if (Data[i]! = 0&&data[i]!=1) cout << "" <<data[i];}} void Main () {Rox t;cout << "Please enter the maximum value tested N:"; cin >> N; T.creat (); cout << "The table created is" << Endl; T.show (); T.run (); cout<<endl;cout << "Deleted tables are:" << Endl; T.show (); cout << Endl;}

  

Erato Sieve Method (Sieve of Eratosthenes) to calculate the prime number.

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.