May 23, 2010 at 11:44pm UTC
All right, I plan on turning this into a sieve, but for now, not even finding the Nth prime works. :(
Here's my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#include "iostream"
using namespace std;
int main()
{
int N;
int primecount=0;
cout << "I will find the <Nth> prime.\n\n :" ;
cin >> N;
int * primes = new int [N];
for (int loop = 2; loop <N; loop++)
{
for (int loop2 = 2; loop2<=loop/2; loop2++)
{
if (loop%loop2==0)
break ;
else if (loop2==loop/2)
{
primes[primecount]=loop;
primecount+=1;
}
else
continue ;
}
}
cout << primes[primecount];
cout << "\n\n\n" ;
system("pause" );
return 0;
}
I suspect that this:
int * primes = new int [N];
Is giving me problems...
Any suggestions?
Last edited on May 23, 2010 at 11:52pm UTC
May 23, 2010 at 11:50pm UTC
You're not finding the Nth prime, you're finding all primes lower than N (assuming the algorithm is correct).
You don't need an array to do this.
May 23, 2010 at 11:53pm UTC
Ah, I'm sorry. That bit of code was in there from when I was testing it. I removed it, please check the code now.
May 23, 2010 at 11:55pm UTC
1 2 3
primes[primecount]=loop;
primecount+=1;
cout << primes[primecount];
Here,
You're accessing wrong address. You shall first print number after you shall increment the values
Like;
1 2 3
primes[primecount]=loop;
cout << primes[primecount];
primecount+=1;
AFTER YOUR EDIT
cout << primes[primecount];
Instead of it , try
cout << primes[primecount-1];
Last edited on May 23, 2010 at 11:57pm UTC
May 24, 2010 at 12:08am UTC
Still finding all primes lower than N.
May 24, 2010 at 12:10am UTC
Thank you! Now it works, except instead of finding the Nth prime, it finds the prime closest to N. By the way, I found out that this code is extremely inefficient, and I have to overhaul the entire thing. >_> Thank you guys for the help.
Last edited on May 24, 2010 at 12:14am UTC