So I’m trying out Problem 7 of Project Euler.
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int a){
if (a==2||a==3){
return true;
}
if (a%2==0){
return false;
}
bool prime=true;
for (int b=2;b<sqrt(a);b++){
if (a%b==0)
prime=false;
}
if (prime==true)
return true;
else
return false;
}
int main(){
int infinite=0;
long long int primecounter=0;
for (int c=2;infinite==0;c++){
if (isPrime(c)==true){
primecounter++;
//cout<<c<<endl;
if (primecounter==10001)
{cout<<c;
break;}
}
}
return 0;}
This is what I’ve come up with so far. It works for the few numbers that I tested, like the 6th prime number etc. However, when I run it for the 10001st prime, it gives me 104021, and the answer is wrong. Can someone tell me what is wrong with my code?
Where you get it wrong is
b < sqrt(a). Think of a=25, what happens in this case?rest of answer already pointed by comments.