题目:编程输出2~100之间的质数
解答:Java编码实现
说明:2~100之间的质数(素数)有25个,分别为: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。 质数定义:只能被1和它本身整除的数(即约数只有1和其本身)
解法1(OO):
public class Prime { public static void main(String[] args) { for (int i = 2; i <= 100; i++) if (isPrime(i)) System.out.println(i); } private static boolean isPrime(int n) { for (int j = 2; j <= Math.sqrt(n); j++) if (n % j == 0) return false; return true; } }
解法2(过程):
public class Prime2 { public static void main(String[] args) { int i, j; for (i = 2; i <= 100; i++) { for (j = 2; j <= Math.sqrt(i); j++) { if (i % j == 0) break; } if (j > Math.sqrt(i)) System.out.println(i); } } }