程序应该打印出前100个素数,但实际上只打印出了0和1。

huangapple go评论61阅读模式
英文:

Program that should print the first 100 prime numbers, only prints 0 and 1 instead

问题

public class Programma {
    public static void main(String args[]) {
        int flag = 0;
        for (int i = 0; i < 100; ++i) {
            for (int j = 1; j < i; ++j) {
                if ((i % j) == 0)
                    flag = 1;
                    break;
            }
            if (flag == 0)
                System.out.print(i + " ");
            flag = 0;
        }
    }
}

输出:

$ java Programma
0 1

我真的不明白为什么... 我已经多次检查了代码,但找不到错误。

英文:
public class Programma{
    public static void main(String args[]){
        int flag=0;
        for(int i=0;i&lt;100;++i){
            for(int j=1;j&lt;i;++j){
                if((i%j)==0)
                    flag=1;
                    break;
            }
            if (flag==0)
                System.out.print(i + &quot; &quot;);
            flag = 0;
        }
    }
}

Output:

$ java Programma 
0 1 

I really don't understand why.. I've checked the code multiple times and can't find the bug.

答案1

得分: 4

你忘记在if语句中添加花括号:

if((i%j)==0) {
    flag=1;
    break;
}

所以只有第一行是在条件下,break语句每次都会执行。

然后你有一个逻辑错误,将第二个循环的起始值改为2:

for(int i=1;i<100;++i){
    for(int j=2;j<i;++j){

现在你的代码可以工作了。为了理解原因,可以添加额外的println语句:

public class Programma{
    public static void main(String args[]){
        int flag=0;
        for(int i=1;i<100;++i){
            for(int j=2;j<i;++j){
                if((i%j)==0){
                    System.out.println("# " + i + "/" + j);
                    flag=1;
                    break;
                }
            }
            if (flag==0)
                System.out.println(i + " ");
            flag = 0;
        }
    }
}

并尝试使用/不使用更改后的for循环起始值。

英文:

You forgot to add the curly brackets to the if:

            if((i%j)==0) {
                flag=1;
                break;
            }

So only the first line was under the condition, the break was executed each time.

Then you have a logical error, start the second loop with 2:

   for(int i=1;i&lt;100;++i){
        for(int j=2;j&lt;i;++j){

Now your code works. To understand why, add an additionally println like

public class Programma{
    public static void main(String args[]){
        int flag=0;
        for(int i=1;i&lt;100;++i){
            for(int j=2;j&lt;i;++j){
                if((i%j)==0){
                    System.out.println(&quot;# &quot; + i + &quot;/&quot; + j);
                    flag=1;
                    break;
                }
            }
            if (flag==0)
                System.out.println(i + &quot; &quot;);
            flag = 0;
        }
    }
}

and try it with / without changed start values for the for loop.

答案2

得分: 1

以下是您要翻译的内容:

这将为您提供前100个素数。

public class Programma {

    public static void main(String[] args) {
        int flag=0,primeCounter=0,start=2;
        while(primeCounter<100){
            for(int j=2;j<=Math.sqrt(start);j++){
                if((start%j)==0){
                    flag=1;
                    break;
                }
            }
            if (flag==0) {
                System.out.print(start + " ");
                primeCounter++;
            }
            start++;
            flag = 0;
        }
    }
}
英文:

This will give you the first 100 prime numbers.

public class Programma {

	public static void main(String[] args) {
		int flag=0,primeCounter=0,start=2;
		while(primeCounter&lt;100){
			for(int j=2;j&lt;=Math.sqrt(start);j++){
				if((start%j)==0){
					flag=1;
					break;
				}
			}
			if (flag==0) {
				System.out.print(start + &quot; &quot;);
				primeCounter++;
			}
			start++;
			flag = 0;
		}
	}
}

答案3

得分: 1

在你的代码中,我怀疑这里的 if 有些问题。

if((i%j)==0) { // 忘记在 if 语句内部添加大括号 {}
    flag=1;
    break;  // 没有大括号的情况下,break 语句会立即执行。
}

通过对你的原始代码进行一些小的改进,下面是基于 for 循环的代码段,用于打印出小于等于 N 的所有素数。

public class Programma {
    // 打印出小于等于 N 的所有素数的函数。
    static void print_primes(int N) {
        int flag;
        // 遍历从 2 到 N 的每个数字。
        for (int i = 2; i <= N; i++) {
            flag = 1;
            for (int j = 2; j <= i / 2; ++j)  {
                if (i % j == 0) {
                    flag = 0;
                    break;
                }
            }
            if (flag == 1) // flag == 1 表示 i 是素数。
                System.out.print(i + " ");
        }
    }
    // 主函数打印出小于等于 n = 100 的所有素数。
    public static void main(String[] args) {
        print_primes(100);
    }
}

输出结果:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

你还可以用更少的代码行数来实现,而不是使用循环,如果你选择使用基于 Java 8stream 库来解决问题。

import java.util.stream.*;
import java.util.Arrays;

public class Programma {
    // 检查一个数是否是素数。
    static boolean isPrime(int n) {
        return IntStream.rangeClosed(2, n / 2).noneMatch(i -> n % i == 0);
    }
    // 生成小于等于 n 的所有素数,并将它们作为 int[] 数组返回。
    static int[] generatePrimes(int n) {
        return IntStream.rangeClosed(2, n).filter(Programma::isPrime).toArray();
    }
    // 主函数打印出小于等于 n = 100 的所有素数。
    public static void main(String[] args) {
        System.out.println(Arrays.toString(generatePrimes(100)));
    }
}

输出结果(打印出小于等于 n = 100 的所有素数):

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
英文:

In your code, I suspect that there is something wrong with the if here.

if((i%j)==0) { // By forgetting to add braces {} around the code inside the if 
    flag=1;
    break;  // the break statement executes instantly, without them.
}

By making some small improvements in your original code here is the for loop based code segment that prints all prime numbers up to N.

public class Programma {
    // Function to print all prime numbers up to N.
    static void print_primes(int N) {
        int flag;
        // Traverse each number from 2 to N.
        for (int i = 2; i &lt;= N; i++) {
            flag = 1;
            for (int j = 2; j &lt;= i / 2; ++j)  {
                if (i % j == 0) {
                    flag = 0;
                    break;
                }
            }
            if (flag == 1) // flag == 1 means i is prime.
                System.out.print(i + &quot; &quot;);
        }
    }
    // Main prints all prime numbers up to n = 100.
    public static void main(String[] args) {
        print_primes(100);
    }
}

Output:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

You could also write this in fewer lines of code, than using loops, should you go for a Java 8 stream library based solution.

import java.util.stream.*;
import java.util.Arrays;

public class Programma {
    // Check if a number is prime or not.
    static boolean isPrime(int n) {
        return IntStream.rangeClosed(2, n / 2).noneMatch(i -&gt; n % i == 0);
    }
    // Generate all prime numbers until n, and return them as an int[] array.
    static int[] generatePrimes(int n) {
        return IntStream.rangeClosed(2, n).filter(Programma::isPrime).toArray();
    }
    // Main prints all prime numbers up to n = 100.
    public static void main(String[] args) {
        System.out.println(Arrays.toString(generatePrimes(100)));
    }
}

Output (all prime numbers up to n = 100 are printed):

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

答案4

得分: -1

以下是翻译好的内容:

这里是答案:

public class Main{
    public static void main(String[] args) {

    int i;
    int num = 0;
    int maxCheck = 100; 
    boolean isPrime = true;
    String primeNumbersFound = "";
    for (i = 1; i <= maxCheck; i++) {
        isPrime = CheckPrime(i);
        if (isPrime) {
            primeNumbersFound = primeNumbersFound + i + " ";
        }
    }
    System.out.println("从1到" + maxCheck + "的素数为:");
    System.out.println(primeNumbersFound);
}
public static boolean CheckPrime(int numberToCheck) {
    int remainder;
    for (int i = 2; i <= numberToCheck / 2; i++) {
        remainder = numberToCheck % i;
        if (remainder == 0) {
            return false;
        }
    }
    return true;
}
}

在这里,你只是检查余数是否为0,如果是,那么numberToCheck就不是素数,所以你中断循环。否则,你就继续循环。希望这对你有所帮助。如果你需要更详细的解释,只需访问这个链接

英文:

Here is the answer:

public class Main{
    public static void main(String[] args) {

    int i;
    int num = 0;
    int maxCheck = 100; 
    boolean isPrime = true;
    String primeNumbersFound = &quot;&quot;; 
    for (i = 1; i &lt;= maxCheck; i++) {
        isPrime = CheckPrime(i);
        if (isPrime) {
            primeNumbersFound = primeNumbersFound + i + &quot; &quot;;
        }
    }
    System.out.println(&quot;Prime numbers from 1 to &quot; + maxCheck + &quot; are:&quot;);
    System.out.println(primeNumbersFound);
}
public static boolean CheckPrime(int numberToCheck) {
    int remainder;
    for (int i = 2; i &lt;= numberToCheck / 2; i++) {
        remainder = numberToCheck % i;
        if (remainder == 0) {
            return false;
        }
    }
    return true;

}

}

Here you just check if the remainder is 0, then numberToCheck is not prime and so you break the loop. Else you just continue the loop. Hope this helps. If you need a more detailed explanation just visit this link.

huangapple
  • 本文由 发表于 2020年10月14日 15:52:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64348885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定