[英]Calculating the 10001 prime number, no output is printed
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; 你的问题是你在for
循环之前没有将flag
重置为true; so once it is false
, it remains false
, so counter
is never incremented, meaning the while
loop guard never becomes false
. 所以一旦它是false
,它仍然是false
,所以counter
永远不会递增,这意味着while
循环保护永远不会变false
。
This is an example of why you should declare variables in the tightest possible scope (ie inside the while loop). 这是为什么你应该在最严格的范围内声明变量的例子(即在while循环内)。
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. 如果您调试了代码(或者甚至只是添加了几个System.out.println
),您可能已经发现它实际上并没有做正确的事情。
As mentioned by @AndyTurner you should declare flag = true;
正如@AndyTurner所提到的,你应该声明flag = true;
in while
loop and also there is a slight error in your logic for finding the prime number. 在while
循环中,你的逻辑中有一个轻微的错误,用于查找素数。
You are incrementing the num
after it is checked for prime
. 在检查prime
后,您正在递增num
。 So, if your 3rd prime is 5
, then it will print 6
as the answer. 所以,如果你的第3个素数是5
,那么它将打印6
作为答案。 lly, if your 10001th prime is X
, then it will print X + 1
as the answer. 如果你的第10001个素数是X
,那么它将打印X + 1
作为答案。
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 希望它有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.