public class Prime
{
public static void main(String [] args)
{
int num = 3;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
num++;
}
System.out.println(num);
}
}
Whenever I run this code, no result is printed out. I'm assuming its because the code is inefficient, but I don't know what is wrong with this code.
Your problem is that you don't reset flag
to true before the for
loop; so once it is false
, it remains false
, so counter
is never incremented, meaning the while
loop guard never becomes false
.
This is an example of why you should declare variables in the tightest possible scope (ie inside the while loop).
while(counter < 10001)
{
int flag = true;
for (...) {...}
if (flag) { counter++; }
// ...
}
It's also an example of why you should make sure your code is correct before you think about whether it is efficient . Had you debugged the code (or even just added in a few System.out.println
s), you could have found that it wasn't actually doing the right thing.
As mentioned by @AndyTurner you should declare flag = true;
in while
loop and also there is a slight error in your logic for finding the prime number.
You are incrementing the num
after it is checked for prime
. So, if your 3rd prime is 5
, then it will print 6
as the answer. lly, if your 10001th prime is X
, then it will print X + 1
as the answer.
I have posted the correct logic for your problem below. I hope it helps you.
public class Main
{
public static void main(String [] args)
{
int num = 2;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
flag = true;
num++;
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
}
System.out.println(num);
}
}
Its not printing cause its going in infinite loop as counter is not incremented once flag become false
public static void main(String [] args)
{
int num = 3;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
flag = true;
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
num++;
}
System.out.println(num);
}
Try this. hope it helped
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.