How can I write a program that finds prime numbers up to 1 million? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can I write a program that finds prime numbers up to 1 million?

prime numbers

29th Oct 2016, 11:31 AM
Kemal Derinsu
Kemal Derinsu - avatar
3 Answers
+ 2
You just need to divide every number with each number from 2 to its square root (after square root will be just multiples of already tried divisors). Here is the program: #include <iostream> #include <cmath> using namespace std; bool is_prime(int n); int main() { for(int i = 1; i <= 1000000; i++) if(is_prime(i)) cout << i << " "; return 0; } bool is_prime(int n) { int square_root = (int)sqrt(n); for(int i = 2; i <= square_root; i++) { if(n % i == 0) return false; } return true; }
29th Oct 2016, 12:00 PM
Daniel Oravec
Daniel Oravec - avatar
+ 2
Calculating primes one by one will be slow.The time complexity is O(n sqrt(n)). We can implement sieve of erastothenes with a boolean array to optimize the code. This reduces the time complexity to O(N) and all primes can be accessed after the calculation. #include<iostream> #include<cmath> #define MAXN 1000000 bool composite[MAXN]; int main() { int stop=sqrt(MAXN); for(int i=2;i<=stop;i++) { if(composite[i]) continue; for(int j=i*i;j<=MAXN;j+=i) composite[j]=true; } } Afterwards, members which is still false will be a prime number :) Of course, if you need to have the prime numbers only, you can store them into another dynamic array like vector instead of the original one.
29th Oct 2016, 1:02 PM
Hayden Lee
0
thank you for answers
31st Oct 2016, 5:08 PM
Kemal Derinsu
Kemal Derinsu - avatar