Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Algo to find all the primes #21

Closed
wants to merge 3 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Algo to find all the primes
Adding Sieve of Eratosthenes.
  • Loading branch information
lavishsaluja committed Jun 13, 2018
commit 50243e732cd3f31a1ee094195e1b79f2ae932c24
33 changes: 33 additions & 0 deletions Algorithms/NumberTheory/FindingAllPrimes/SieveofEratosthenes.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Sieve Of Eratosthenes
// Time Complexity O(nlog(log(n))) whereas following brute force will end you up with O(n*sqrt(n))
#include <iostream>
#include<math.h>
using namespace std;

int main() {
int n;cin>>n;
int prime[n+1];//prime[i]=1 will imply that i is prime & prime[i]=0 will imply that i is not prime
for(int i=0;i<=n;i++)
prime[i]=1;//considering all as primes as of now.
prime[0]=0;
prime[1]=0;//since 0 & 1 are not prime ofcourse

/*
Here we will be running are first loop only till sqrt(n) instead of n because we know that
if a number is prime it does not have any factor till its square root so we
can use it for optimization.
*/
for(int i=2;i<=sqrt(n);i++){
if(prime[i]==1){//if i is prime
for(int j=2;j*i<=n;j++){
prime[i*j]=0;//setting the multiples of i to 0 because they can't be prime ofcourse
}
}
}
for(int i=0;i<=n;i++){
if(prime[i]!=0){
cout<<i<<endl;
}
}
return 0;
}