简体   繁体   English

While 循环 1 - 100 之间的质数

[英]While Loop Prime Numbers between 1 - 100

I'm pretty new to programming, and I'm trying to get my head around loops.我对编程还很陌生,我正在努力解决循环问题。 I managed to get a piece of code working, but I'm still not fully understanding how it works.我设法让一段代码工作,但我仍然不完全理解它是如何工作的。 I found code for a similar program online which was written using a for loop and I managed to get it to work as a while loop (took me a few days..!).我在网上找到了一个类似程序的代码,它是使用 for 循环编写的,我设法让它像 while 循环一样工作(花了我几天时间……!)。 I'm trying to understand what the inner loop is doing.我试图了解内部循环在做什么。

I know the outer loop is checking that x is less than 100 for each iteration of the loop.我知道外循环正在检查循环的每次迭代中的x是否小于 100。 Why the need to nest the y variable in the loop, why is it set to 2 and why does it need to increment by one each time?为什么要在循环中嵌套y变量,为什么设置为2,为什么每次都需要加1? Also, is there a way to get out of the loop without using the break;另外,有没有办法在不使用break的情况下跳出循环? ?

I've seen a few other examples of this type of program here, but I am hoping someone can shed some light on how this one is working specifically.我在这里看到了此类程序的其他一些示例,但我希望有人可以阐明该程序的具体工作原理。

Thanks in advance!!!提前致谢!!!

class PrimeNumbers {
  public static void main(String args[]) {
    int x = 2;
    while (x <= 100) {
      int y = 2;
      while (y <= x) {
        if (x == y) {
          System.out.println(x);
        }
        if (x % y == 0) {
          break;
        }
        y++;
      }
      x++;
    }
  }
}

Comments are your friend:评论是你的朋友:

class PrimeNumbers {
    public static void main(String args[]) {
        // No point checking below 2 since the definition of a prime is "A prime number (or a prime) is a natural number greater than 1 ..."
        int x = 2;
        // Looking for primes up-to and including 100
        while (x <= 100) {
            // Same argument as above - start checking at 2 and work upwards.
            int y = 2;
            // stop when y > x as obviously y will not divide x
            while (y <= x) {
                // if y reaches x then we have not found any divisors
                if (x == y) {
                    // success! This x is prime.
                    System.out.println(x);
                }
                // if y divides x leaving no remainder then not prime - give up this y loop and select our next x
                if (x % y == 0) {
                    break;
                }
                // Try next y divisor.
                y++;
            }
            // Try next x candidate.
            x++;
        }
    }
}

and naming your variables more helpfully it gets even easier并更有帮助地命名您的变量,它变得更加容易

class PrimeNumbers {
    public static void main(String args[]) {
        // No point checking below 2 since the definition of a prime is "A prime number (or a prime) is a natural number greater than 1 ..."
        int candidate = 2;
        // Looking for primes up-to and including 100
        while (candidate <= 100) {
            // Same argument as above - start checking at 2 and work upwards.
            int divisor = 2;
            // stop when divisor > candidate as obviously divisor will not divide candidate
            while (divisor <= candidate) {
                // if divisor reaches candidate then we have not found any divisors (because of the `break` below).
                if (candidate == divisor) {
                    // success! This candidate is prime.
                    System.out.println(candidate);
                }
                // if divisor divides candidate leaving no remainder then not prime - give up this divisor loop and select our next candidate
                if (candidate % divisor == 0) {
                    break;
                }
                // Try next divisor.
                divisor++;
            }
            // Try next candidate.
            candidate++;
        }
    }
}

The variable x iterate all the number from 2 to 100. Inside this loop you will process some stuff to determine if x is a prime number or not.变量x迭代从 2 到 100 的所有数字。在这个循环中,您将处理一些东西以确定 x 是否是素数。 This stuff your code do is to iterate through all the number from 2 to x and try for each one if it divides x.你的代码所做的事情是遍历从 2 到 x 的所有数字,如果它除以 x,则尝试每个数字。 The variable y is this second number.变量y是第二个数字。

For example when you're at the iteration where x = 4 .例如,当您处于x = 4的迭代中时。 y will first be equal to 2. Then you check if x%y==0 , this means you check if x is divisible by y. y 首先等于 2。然后检查是否x%y==0 ,这意味着您检查 x 是否可以被 y 整除。 In this case it's true.在这种情况下,这是真的。 so x is not a prime number so you exit the inner loop ( break; statement).所以 x 不是素数,所以你退出内部循环( break;语句)。 Then x=5 , you have y=2 .然后x=5 ,你有y=2 this does not divide x.这不会划分 x。 you increment y ( y=3 ).你增加 y ( y=3 )。 This does not divide x either.这也不会划分 x。 You increment y ( y=4 ).您增加 y ( y=4 )。 This does not divide x.这不会划分 x。 you increment y ( y=5 ).你增加 y ( y=5 )。 The if y==x return true.如果y==x返回 true。 It means you've iterate through all value of y.这意味着您已经遍历了 y 的所有值。 So x is a prime number.所以 x 是一个质数。 So you print x.所以你打印x。 You exit your inner loop.你退出你的内循环。 you increment x ( x=6 ).你增加 x ( x=6 )。 And so on...等等...

Why the need to nest the y variable in the loop, why is it set to 2 and why does it need to increment by one each time?为什么需要在循环中嵌套 y 变量,为什么将其设置为 2,为什么每次都需要递增 1?

We need to reset the variable within the loop because the test needs to be applied for each value of x.我们需要在循环内重置变量,因为需要对 x 的每个值应用测试。 The values of x are the potential candidates for prime numbers. x 的值是素数的潜在候选者。 Why is it set to 2 is because every number is divisible by 1.为什么设置为 2 是因为每个数字都可以被 1 整除。

Also, is there a way to get out of the loop without using the break;另外,有没有办法在不使用中断的情况下退出循环? ? ?

You can add another condition to the second while loop.您可以向第二个 while 循环添加另一个条件。 This flag could then be set once you exit condition has been satisfied.一旦满足退出条件,就可以设置此标志。

As you can see your first loop is checking whether or not x is smaller than 100. Then your next while dividing all numbers that is smaller than x, and if there is some number that is smaller than x and have 0 mod it is not prime.正如你所看到的,你的第一个循环是检查 x 是否小于 100。然后你的下一个同时将所有小于 x 的数字除以,如果有一些小于 x 并且具有 0 mod 的数字不是素数. For example our x = 5 in first iteration y = 2, 5 % 2 = 1 as you can it is not possible to divide because mod is not zero, then y increments by one, 5 % 3 = 2 mod is 2 again not dividable, and so on in the you would that y increments till the 5 this means there is no smaller integer that you could divide to x from that our x=5 is prime number.例如我们的 x = 5 在第一次迭代中 y = 2, 5 % 2 = 1 因为你不能除以因为 mod 不为零,然后 y 递增 1,5 % 3 = 2 mod 又是 2 不可除,依此类推,你会认为 y 递增到 5 这意味着没有更小的整数可以除以 x,因为我们的 x=5 是素数。 When you don't understand what is going on, try to print all things.当您不明白发生了什么时,请尝试打印所有内容。

To know if a number is prime, the rest will only be zero when the number(x) is divided between himself or 1.要知道一个数是否是素数,只有当数 (x) 除以他自己或 1 时,其余的才会为零。

So in this code you divide each number(x) by all the numbers(y) between 1 and the number itself.因此,在此代码中,您将每个数字 (x) 除以 1 和数字本身之间的所有数字 (y)。

That's the reason when这就是原因当

if (x % y == 0) { break; }

This means,if dividing y there is a rest = 0 between 1 and X you stop the loop cause it is not gonna be a prime.这意味着,如果除以y在 1 和 X 之间有一个rest = 0你停止循环因为它不会是一个素数。

You can remove the break using a variable flag but the loop would do many more iterations.您可以使用变量标志删除中断,但循环会进行更多迭代。

print('Prime numbers between 1 and 100 are:') print('1 到 100 之间的质数是:')

for num in range(2,101): if num > 1: for i in range(2,num): if (num % i) == 0: break else: print(num) for num in range(2,101): if num > 1: for i in range(2,num): if (num % i) == 0: break else: print(num)

class Example{
    public static void main(String[] args) {
        int i=2;
        int j;
        int count;

        while(i<100){
            j=1;
            count=0;
            while(j<=i){
                if (i%j==0){
                    count++;
                }
                j++;
            }
            if (count==2){
            System.out.println(i);
            }
            i++;
        }
    }
}

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

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