Sunday, 24 September 2017

Finding Array of Prime and Factors using Sieve of Eratosthenes Algorithm in C++

Theory: Using the sieve of Eratosthenes find an array of prime numbers.

Explanation:

1.Declare an int array sieve[]
2.Using the Sieve of Eratosthenes algorithm an array of prime can be obtained.Again factors of non prime can also be obtained;
3.sieve[i] == 0 : i is a prime number.
4. When not equal to zero the factor is displaced within the array element.

Code
#include <bits/stdc++.h>
using namespace std;
int sieve[100];
int main(){
int n;

cin>>n;
for(int x=2; x<=n; x++){
if(sieve[x]){
continue;
}
for(int i=2*x;i<=n;i+=x){
sieve[i]=x;
}
}

cout<<"Prime factors is those elements with 0 and other elements are factors";
for(int i=2;i<=n;i++){

    cout<<i<<" "<<sieve[i]<<endl;
}
return 0;}


No comments:

Post a Comment

Spoj Problem ACMCEG2C - Pick the candies (C++)

  The problem link may be found here.       Explanation: Use Deque to keep track of elements of the variety of candies. If i is gre...