简体   繁体   English

我如何让这个 for 循环只打印素数?

[英]How would I get this for loop to print prime numbers only?

What I need it to do is print all of the prime numbers starting at 1 and ending at the input, if the input is also a prime number.我需要它做的是打印所有从 1 开始到输入结束的素数,如果输入也是素数。 Here's my code now:这是我现在的代码:

static void primeNumbers(int n) {

boolean isPrime;

System.out.println("All the prime numbers up to " + n + " are -->");
for (int prime = 2; prime < n; prime = prime++) {
  if (n % prime == 0) {
    isPrime = false;
  }
  if(isPrime == true){
    System.out.println(prime);
  }
}
}

My teacher said that I need to make a nested for loop, but I just don't know what to put in it.我的老师说我需要做一个嵌套的 for 循环,但我就是不知道该放什么。 I'm also getting an error saying that my last use of isPrime hasn't been initialized.我还收到一条错误消息,指出我上次使用 isPrime 尚未初始化。

You need to actually check for primality, and not just see if the number is a factor of n:您需要实际检查素数,而不仅仅是查看数字是否是 n 的因数:

static boolean isPrime(int n) {
    if (n < 2) {
        return false;
    }
    if (n % 2 == 0) {
        return n == 2;
    }
    for (int k = 3; k * k <= n; k += 2) {
        if (n % k == 0) {
            return false;
        }
    }
    return true;
}

static void primeNumber(int n) {
    System.out.println("All the prime numbers up to " + n + " are -->");
    for (int num = 2; num < n; num ++) {
        if (isPrime(num)) {
            System.out.println(num);
        }
    }
}

You will need to do something like this for your program to work.你需要做这样的事情才能让你的程序工作。

static void primeNumbers(int n) {

    boolean isPrime = true;

    System.out.println("All the prime numbers up to " + n + " are -->");
    for (int prime = 2; prime < n; prime++) {
        if (n % prime == 0) {
            isPrime = false;
        }else{
            isPrime = true;
        }
        if(isPrime){
            System.out.println(prime);
        }
    }
}

It is necessary to initialize isPrime.有必要初始化isPrime。

And, Eratosthenes' s sieve is famous algorithm for get prime numbers.并且,埃拉托色尼筛法是著名的求素数的算法。

I think the URL below will help you.我认为下面的网址会对您有所帮助。

https://www.geeksforgeeks.org/java-program-for-sieve-of-eratosthenes/ https://www.geeksforgeeks.org/java-program-for-sieve-of-eratosthenes/

here is one of the solutions这是解决方案之一

 public static void main(String[] args) {
        int n = 23;
        boolean[] isPrime = new boolean[n + 1];

        for (int i = 1; i <= n; i++) {
            isPrime[i] = true;
        }

        for (int i = 2; i <= n / i; i++) {
            if (isPrime[i]) {
                for (int j = i; j <= n / i; j++) {
                    isPrime[i * j] = false;
                }
            }
        }

        for (int i = 1; i <= n; i++) {
            if (isPrime[i]) {
                System.out.println(i);
            }
        }
    }

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

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