输出100以内的质数 发表于 2020-05-27 | 分类于 程序设计 | 字数统计: 432 | 阅读时长 ≈ 2 使用Java输出100以内的质数代码如下 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798package Homework;public class Prime { public static void main(String[] args) { boolean isFlag = true; for(int i = 2; i <= 100; i++){ for(int j = 2; j < i; j++){ if(i % j == 0) isFlag = false; } if(isFlag == true) System.out.println(i); isFlag = true;//重置isFlag } }} ``` ### 对算法进行优化 - 优化之前 ```javapackage Homework;public class Prime { public static void main(String[] args) { long begin = System.currentTimeMillis(); int count = 0; boolean isFlag = true; for(int i = 2; i <= 100000; i++){ for(int j = 2; j < i; j++){ if(i % j == 0) isFlag = false; } if(isFlag == true) count ++; isFlag = true;//重置isFlag } long end = System.currentTimeMillis(); System.out.println("质数的个数为:"+ count); System.out.println("花费时间为:" + (end - begin)); }}``` 运行结果 ![](优化前.png) - 优化一:只对本身是非质数的自然数是有效的 ```java package Homework;public class Prime { public static void main(String[] args) { long begin = System.currentTimeMillis(); int count = 0; boolean isFlag = true; for(int i = 2; i <= 100000; i++){ for(int j = 2; j < i; j++){ if(i % j == 0) { isFlag = false; break;//优化一 } } if(isFlag == true) count ++; isFlag = true;//重置isFlag } long end = System.currentTimeMillis(); System.out.println("质数的个数为:"+ count); System.out.println("花费时间为:" + (end - begin)); }}``` 运行结果: ![](优化一.png) - 优化二:对于内层循环次数进行优化 ```java package Homework;public class Prime { public static void main(String[] args) { long begin = System.currentTimeMillis(); int count = 0; boolean isFlag = true; for(int i = 2; i <= 100000; i++){ //将内层循环的次数从i变为根号i for(int j = 2; j < Math.sqrt(i); j++){ if(i % j == 0) { isFlag = false; break;//优化一 } } if(isFlag == true) count ++; isFlag = true;//重置isFlag } long end = System.currentTimeMillis(); System.out.println("质数的个数为:"+ count); System.out.println("花费时间为:" + (end - begin)); }} 运行结果: 可见,学好数据结构与算法的重要性