题目
质数:只能被1和它本身所整除的数。即:从2开始一直到这个数-1,都不能被这个数整除;最小的质数是2
知识点
1.System.currentTimeMillis():计算当前时间距离1970-1-1的毫秒数,返回long
2.Math.sqrt:开方,返回double
代码1
package lesson.l5_loop;//打印100以内所有质数
//质数:只能被1和它本身所整除的数。即:从2开始一直到这个数-1,都不能被这个数整除
//最小的质数是2
public class PrimeNumber1 {public static void main(String[] args) {for (int i = 2; i <= 100; i++) {boolean isPrime = true;for (int j = 2; j <= i - 1; j++) {if (i % j == 0 ) {isPrime = false;}}if (isPrime) {System.out.print(i + "\t");}}}
}
代码2
减少内层循环次数:i/2+1
package lesson.l5_loop;public class PrimeNumber2 {public static void main(String[] args) {for (int i = 2; i <=100 ; i++) {boolean isPrime=true;for (int j=2;j<=i/2+1;j++){if (i%j==0){isPrime=false;}}if (isPrime){System.out.print(i+"\t");}}}
}
代码3
使用break优化:当不是质数时,立即跳出当前循环
package lesson.l5_loop;public class PrimeNumber3 {public static void main(String[] args) {long start=System.currentTimeMillis();for (int i =2 ; i <=100 ; i++) {boolean isPrime=true;for (int j=2;j<=i/2+1;j++){if (i%j==0){isPrime=false;break;}}if (isPrime&&i!=1){System.out.print(i+"\t");}}long end=System.currentTimeMillis();System.out.println("\n"+(end-start));//52}}
代码4
使用开方i
Math.sqrt:开方
因为除以a==b,所以没必要去除以b
package lesson.l5_loop;public class PrimeNumber3 {public static void main(String[] args) {long start=System.currentTimeMillis();for (int i =2 ; i <=100 ; i++) {boolean isPrime=true;for (int j=2;j<=(int)Math.sqrt(i);j++){if (i%j==0){isPrime=false;break;}}if (isPrime){System.out.print(i+"\t");}}long end=System.currentTimeMillis();System.out.println("\n"+(end-start));//52 48}}
代码5
使用带标签的continue
package lesson.l5_loop;public class PrimeNumber4 {public static void main(String[] args) {long start = System.currentTimeMillis();label:for (int i = 2; i <= 100; i++) {for (int j = 2; j <= (int) Math.sqrt(i); j++) {if (i % j == 0) {continue label;}}System.out.print(i + "\t");}long end = System.currentTimeMillis();System.out.println("\n" + (end - start));}
}