判斷輸入的某數是不是質數
並列出1-100之間的質數
=========================
=========================
import java.util.Scanner;
public class JudgeMethod {//輸入整數判斷是否為質數
static Boolean WhetherPrime=true;
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int JudgeValue;
System.out.println("Please enter integer:");//請使用者輸入一整數
while(scan.hasNextInt()){//如果是整數就進入while
JudgeValue=scan.nextInt(); //把使用者輸入的值指派給JudgeValue
JudgePrime(JudgeValue);//呼叫JudgePrime函式去算JudgeValue是不是質數
if(WhetherPrime){//如果WhetherPrime傳回false不是質數
System.out.println("非質數");
break;
}else{//如果WhetherPrime傳回true是質數
System.out.println("質數");
break;
}
}
System.out.println("1-100的質數有:");//印出1-100的質數
for(int i=2;i<100;i++){
WhetherPrime=true;
JudgePrime(i);
if(WhetherPrime==true){
System.out.print(i+",");
}
}
}
public static Boolean JudgePrime(int JudgeValue){
if(JudgeValue%2==0&&JudgeValue!=2){//如果JudgeValue不是2又能被2整除,則不是質數傳回false
WhetherPrime=false;
return WhetherPrime;
}else if(JudgeValue%3==0&&JudgeValue!=3){//如果JudgeValue不是3又能被3整除,則不是質數傳回false
WhetherPrime=false;
return WhetherPrime;
}else if(JudgeValue%5==0&&JudgeValue!=5){//如果JudgeValue不是5又能被5整除,則不是質數傳回false
WhetherPrime=false;
return WhetherPrime;
}else if(JudgeValue%7==0&&JudgeValue!=7){//如果JudgeValue不是7又能被7整除,則不是質數傳回false
WhetherPrime=false;
return WhetherPrime;
}else{//不是以上情況從11到JudgeValue開根號 去除JudgeValue 可整除便不是質數
for(int i=11;i<=(int)Math.ceil(Math.sqrt(JudgeValue));i+=2){
if(JudgeValue%i==0){
WhetherPrime=false;
return WhetherPrime;
}
}
}
return WhetherPrime;//以上情況都不能整除則是質數 傳回預設值true
}
}
留言列表