繁体   English   中英

检查int是否是主要的Java

[英]Check if an int is prime Java

对不起“修复我的代码”帖子

编辑:更多地涉及for循环的语法而不是素数,现在也解决了。

我的任务是从控制台获取一个int并打印(在单独的行上)从1到n的所有素数。 我的方法从n开始,检查它是否为素数,然后将n递减1并循环直到n = 2。 为了检查一个数字是否为素数,我运行一个循环,检查剩余的潜水数量x等于零,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。 我在这里失踪了什么?

我再次为烦人(略微重复)的问题道歉。

for循环中的条件是继续循环的条件,而不是停止循环的条件。 您需要更换>=<=

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

你正在递增x两次,循环的条件应该是x<=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;
}

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

试试这种方式,它更清晰简洁。

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);


    }

暂无
暂无

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

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