要求:打印 2 - 100000 当中的素数与非素数。(素数定义:在大于1的自然数中,除了1和它本身以外不再有其他因数)
1. 常规方式——对正整数n,如果用2到 之间的所有整数去除,均无法整除,则n为质数:
// sqrt 法 public static void printPrime1(int num) { boolean[] isPrimes = new boolean[num + 1]; for (int i = 2; i < isPrimes.length; i++) { isPrimes[i] = true; } for (int i = 3; i <= num; i++) { for (int j = 2; j <= Math.sqrt(i); j++) { if (i % j == 0) { isPrimes[i] = false; break; } } } System.out.print("质数有: "); for (int i = 2; i < isPrimes.length; i++) { if (isPrimes[i]) { System.out.print(i + " "); } } System.out.println(""); System.out.print("非质数有: "); for (int i = 2; i < isPrimes.length; i++) { if (!isPrimes[i]) { System.out.print(i + " "); } } }
注意这里用一个布尔类型的数组用于素数的判断与最终结果的打印,避免了使用两个容器去分别存放各自需要打印的两块内容。
2. 埃氏筛选法
// 埃氏筛法 public static void printPrime2(int num) { boolean[] isPrimes = new boolean[num + 1]; for (int i = 2; i < isPrimes.length; i++) { isPrimes[i] = true; } for (int i = 2; i < num; i++) { if (isPrimes[i] == true) { for (int j = 2; i * j <= num; j++) { isPrimes[i * j] = false; } } } System.out.print("质数有: "); for (int i = 2; i < isPrimes.length; i++) { if (isPrimes[i]) { System.out.print(i + " "); } } System.out.println(""); System.out.print("非质数有: "); for (int i = 2; i < isPrimes.length; i++) { if (!isPrimes[i]) { System.out.print(i + " "); } } }
最后提供一个main方法,完成对两个方法的调用与性能比较:
public static void main(String[] args) { long timePoint1 = System.currentTimeMillis(); printPrime1(100000); long timePoint2 = System.currentTimeMillis(); System.out.println(); printPrime2(100000); long timePoint3 = System.currentTimeMillis(); System.out.println(); System.out.println("sqrt法耗时: " + String.valueOf(timePoint2 - timePoint1)); // 390 ms System.out.println("埃氏筛法耗时: " + String.valueOf(timePoint3 - timePoint2)); // 297 ms }
原文地址:https://www.cnblogs.com/binye-typing/p/9261118.html
时间: 2024-10-07 03:12:41