patterncppMinor
Find the 10001st prime number (in C++)
Viewed 0 times
numberthe10001stfindprime
Problem
I wrote this solution for project Euler #7, to find the 10001th prime number using sieve of eratosthenes. It's really slow though. Any suggestions to improve performance (without using more complex sieves like sieve of atkin)?
#include
#include
#include
#define max 500000
using namespace std;
int main()
{
int ctr = 0;
int i=2,j,n=10001,p=2;
int arr[max];
memset(arr,0,sizeof(arr));
while(1)
{
p=2;
while(p*p<=i)
{
if(arr[p] == 0)
for(j=p*p;j<=i;j+=p)
arr[j] = 1;
p++;
}
if(arr[i]==0)
ctr++;
if(ctr==n)
break;
i++;
}
cout<<i;
}Solution
- Why is everybody using
#include? It is so hard to include `to getmemsetworking?
- Why do you need
?
- Don't use using namespace std;
. It's a bad practice.
- Static array of int
s with size500000is likely too big to fit into stack. Useint * arr = new int[max]anddelete [] arr;` instead.
- Using whole integers to store boolean value is just a waste of memory.
-
It takes 42 seconds to find result. My version (without sieve) takes about real: 0.015s, user: 0.013s.
#include
bool isPrime(int num) {
for (int i = 2; i*i 1;
}
int main() {
int i = 2;
for (int primes = 0; ; ++i) {
if (isPrime(i)) {
if (++primes == 10001) {
std::cout << i << "\n";
break;
}
}
}
}Code Snippets
#include <iostream>
bool isPrime(int num) {
for (int i = 2; i*i <= num; ++i) {
if ((num % i) == 0) return false;
}
return num > 1;
}
int main() {
int i = 2;
for (int primes = 0; ; ++i) {
if (isPrime(i)) {
if (++primes == 10001) {
std::cout << i << "\n";
break;
}
}
}
}Context
StackExchange Code Review Q#136328, answer score: 6
Revisions (0)
No revisions yet.