【问题标题】:Check if an int is prime Java检查一个 int 是否是素数 Java
【发布时间】:2018-01-13 19:35:20
【问题描述】:

对于“修复我的代码”帖子感到抱歉

编辑:与for 循环的语法有关,而不是质数,现在也解决了。

我的任务是从控制台获取一个 int 并(在单独的行上)打印出从 1 到 n 的所有素数。 我的方法从 n 开始,检查它是否为素数,然后将 n 递减 1 并循环直到 n=2。 为了检查一个数字是否是素数,我运行一个循环,检查数字除以 x 的余数是否等于 0,x 从 2 开始,在 root(n) 处停止。 现在这一切在理论上都是可行的,阅读我的代码我看不出哪里出了问题。

public class Prime {
public static boolean isPrime(int n) {
    boolean result = true;
    for (int x = 2; x>=sqrt(n); x++) {
        if ((n % x) == 0) {
            result = false;
            break;
        } else {
            x++;
        }
    }
    return result;
}

public static void main(String[] args) {
    Scanner intIn = new Scanner(System.in);
    int i = intIn.nextInt();
    while (i>=2) {
        if (isPrime(i)) {
            System.out.println(i);
            i--;
        } else {
            i--;
        }
    }
  }
}

例如,输入 10 将返回 10(以及 9、8、7、6、5、3),即使 isPrime() 检查 10 % 2 == 0,然后将 result 设置为 false。 我在这里错过了什么??

再次为这个烦人(略有重复)的问题道歉。

【问题讨论】:

标签: java loops for-loop primes


【解决方案1】:

这样试试,更清晰简洁。

public static boolean isPrime(int candidate) {
        int candidateRoot = (int) Math.sqrt((double) candidate);
        return IntStream.rangeClosed(2, candidateRoot)
                .noneMatch(i -> candidate % i == 0); // return true if the candidate
                                                     // isn't divisible for any of the
                                                     // numbers in the stream
    }

    public static void main(String[] args) {
        Scanner intIn = new Scanner(System.in);
        int i = intIn.nextInt();

        List<Integer> primeList = IntStream.rangeClosed(2, i)
                .filter(candidate -> isPrime(candidate))
                .boxed()
                .collect(toList());
        System.out.println(primeList);

        // Another way
        Map<Boolean, List<Integer>> primeAndNotPrimeMap = IntStream.rangeClosed(2, i)
                .boxed()
                .collect(partitioningBy(candidate -> isPrime(candidate)));
        System.out.println(primeAndNotPrimeMap);


    }

【讨论】:

    【解决方案2】:

    在循环中 x 必须小于或等于 因此,将 (int x = 2; x>=sqrt(n); x++) 的表达式更改为 for (int x = 2; x

    【讨论】:

      【解决方案3】:

      for 循环中的条件是继续循环的条件,而不是停止循环的条件。您需要将&gt;= 替换为&lt;=

      for (int x = 2; x<=sqrt(n); x++) {
          // Here -----^
      

      【讨论】:

      • 我通过切换到while 循环并像以前一样手动增加 x 来解决我的问题。这些方法之间的区别纯粹是样式/偏好吗?
      【解决方案4】:

      您将 x 增加两次,循环的条件应该是 x&lt;=sqrt(n)

      for (int x = 2; x>=sqrt(n); x++) { // here
          if ((n % x) == 0) {
              result = false;
              break;
          } else {
              x++; // and here
          }
      }
      

      正确的逻辑应该是:

      public static boolean isPrime(int n) {
          for (int x = 2; x<=sqrt(n); x++) {
              if ((n % x) == 0) {
                  return false;
              }
          }
          return true;
      }
      

      【讨论】:

      • 我的印象是 if 语句必须有一个伴随的 else 语句?
      • @420fedoras 不,不需要。
      猜你喜欢
      • 2011-02-16
      • 2015-09-15
      • 2018-10-10
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2016-08-21
      相关资源
      最近更新 更多