2017-08-06 52 views
2

遗憾的“修复我的代码”后检查一个int是首要的Java

编辑:更多有关的for环比质数,现在也解决了语法。

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

我再次为烦人(轻微重复)的问题表示歉意。

+0

的可能的复制[如何在Java中工作这种素数测试?](https://stackoverflow.com/questions/19514680/how-does-this-prime-number-test-in-java-工作) – Ice

回答

3

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

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

我通过切换到while循环并像以前一样手动增加x来解决我的问题。这些方法纯粹是风格还是偏好? – 420fedoras

2

您递增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; 
} 
+0

我的印象是if语句必须有其他语句? – 420fedoras

+1

@ 420fedoras不,不是必需的。 – Eran

1

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

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


    }