打印质数从1到100

这个程序应该输出1到100之间的素数。请问有谁解释下面的程序流程? 我在编写下面的程序时遇到了困难。 我确实在互联网上找到了它,但我仍然无法弄清楚它是如何工作的以及程序的流程如何?

public class GeneratePrimeNumbersExample { public static void main(String[] args) { //define limit int limit = 100; System.out.println("Prime numbers between 1 and " + limit); //loop through the numbers one by one for(int i=1; i < 100; i++){ boolean isPrime = true; //check to see if the number is prime for(int j=2; j < i ; j++){ if(i % j == 0){ isPrime = false; break; } } // print the number if(isPrime) System.out.print(i + " "); } } } 

素数的输出示例是1到100之间的素数

1 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

您如何找到普通香草解决方案的素数? 如果数字是素数。 除了它本身之外,它不会是任何数字的倍数。 所以假设数字是x。 从2到x-1开始,这个数字不能被任何数字整除。 为什么从2而不是1开始,因为每个数字都可以被1整除。上面的代码试图复制相同的行为。 要查找1到99之间的所有素数(根据循环):

  1. 从2到数字(外环 – 1)
  2. 尝试将数字除以检查它是否可分。 (余数应为零)。
  3. 如果真数不是素数。 其他数字是素数。

如果您使用适当的名称将各个部分拆分为自己的方法,则会更容易理解:

 for (int n = 1; n < 100; n++) if (isPrime(n)) System.out.println(n); private boolean isPrime(int n) { for (int f = 2; f < n; f++) { if (isFactor(f, n)) return false; } return true; } private boolean isFactor(int factor, int number) { return number % factor == 0; } 

这也是Java 8流可以使事情变得更清晰的一个领域:

 List primes = IntStream.range(1, 100) .filter(this::hasNoFactors) .collect(Collectors.toList()); private boolean hasNoFactors(int number) { return IntStream.range(2, number) .noneMatch(f -> number % f == 0); } 

另请注意,这是一种非常低效的算法。 您不需要检查从2到n的每个可能因子,只需要检查质数。 您还可以利用多处理器机器:

 List primes = new ArrayList<>(); IntStream.range(1, 100) .filter(n -> primes.parallelStream().nonMatch(p -> n % p == 0)) .forEach(primes::add); 
 public class Prime { public static void main(String arg[]) { int count=0; for(int i=2;i<100;i++) { for(int j=2;j 

只能被1和1整除的数字称为素数。 这是用于查找1到100之间的素数的最简单的代码版本。

 import java.io.*; import java.util.*; class solution { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int n = 100; /* A prime number is a whole number greater than 1, whose only two whole-number factors are 1 and itself. */ for(int i=2;i<=n;i++) // 1.So we are starting with initialization i = 2 { int flag = 1; for(int j=2;j<=i/2;j++) // 2.Try dividing the number by half check whether it divisible { if(i%j==0) // 3. If the number is divisible by other number ->Not a prime Number { flag = 0; break; } } if(flag==1) // 4. If the number is not divisible by any other numbers but only by itself and 1 -> prime no { System.out.print(i+" "); } } } } /* 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 */ 

public static ArrayList prime(int limit){

  ArrayList primes = new ArrayList<>(); for(int p = 2; p <= limit; p++) { int count = 0; for(int i=2; i < p; i++) { if (p%i == 0) { count++; } } if (count == 0) { primes.add(p); } } return primes; } 
 public class primenum { public static void main(String[] args) { for(int i=2;i<100;i++){ int count=1; for(int j=2;j