public static long sum7()
{
int c = 1;
boolean isprime = true;
long prime = 0;
for (long i = 3; i <= Long.MAX_VALUE; i++)
{
for (long j = 2; j < i; j++)
{
if (i % j == 0)
{
isprime = false;
break;
}
}
if (isprime == true)
{
c++;
}
if (c == 10001)
{
prime = i;
break;
}
}
return prime;
}
static Scanner scanner1 = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println(sum7());
}
I was trying out the following code for a project euler question(Q7), i’m supposed to locate the 10001st prime number but it was just not working. The build is successful but it is not showing anything Please help. Thanks in advance….
It’s not clear exactly what you’re trying to do, so I have to guess based on the code. I’m assuming that you wish to find the 10001th prime number.
First off, you forgot to set
isprimeback to true at the end of the loop. As it is now, it will permanently be false after the first iteration, meaning that 3 is the only prime detected and you’ll loop all the way up to 2^63 (effectively infinite) after that and eventually return 0.You can solve the problem and also scope your variable better by moving
boolean isprime = true;to the start of the loop. You might as well moveprimeinto the loop while you’re at it and change theif c==10001bit to just return directly.Secondly,
c = c++;isn’t correct. You’re incrementing the variable and then resetting it to the old value. You should either doc++;orc = c + 1.