简体   繁体   English

在 java 中查找素数的循环中的问题

[英]issue in loop of finding prime number in java

I know the mistake here is in the for loop as it should be i=2 but if i put it as i=1 then why is it not entering in the loop.could someone dry run this code and tell me how exactly is this an issue我知道这里的错误是在 for 循环中,因为它应该是 i=2 但是如果我把它设置为 i=1 那么为什么它没有进入循环。有人可以干运行这段代码并告诉我这到底是怎么回事问题

       if(n==2)
        { return true;} 

      for(int i=1;i<=Math.sqrt(n);i++){
        if(n % i == 0){
            return false;
        }
    }
    return true;

First you need to understand the mathematics behind it.首先,您需要了解其背后的数学原理。 Any number (that is a whole positive number) will give the reminder 0 when divided by one:任何数字(即整数正数)除以 1 时都会给出提示 0:

n % 1 == 0

This condition will therefore always be true.因此,此条件将始终为真。 If your case, once you are at n = 1, you return false.如果你的情况,一旦你在 n = 1,你返回 false。 I suggest you print out the output at every line of your program, and you will see the behavior.我建议你在程序的每一行都打印出 output,你会看到行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM