題目:判斷101-200之間有多少個素數,並輸出所有素數。
程序分析:判斷素數的方法:用一個數分別去除2到sqrt(這個數),
如果能被整除, 則表明此數不是素數,反之是素數。
public class 第二題判斷素數 { public static void main(String[] args) { //統計個數
int count = 0; //判斷101道200之間的素數
for(int i=101; i<201; i++) { if(isPrime(i)) { count++; System.out.println(i); } } System.out.println("總數:" + count); } //判斷一個數是否為素數
public static boolean isPrime(int n) { for(int i=1; i<=Math.sqrt(n); i++) { //不是素數
if(n % 2 == 0) { return false; } } return true; } }