知識+看到拿來做做
質數的地方 因頭腦不好 還在想更好的演算法...
========================輸出
========================Main.java
Created with colorer-take5 library. Type 'java'
import java.util.Scanner;
public class Main {
public static void main(String[] args) {//主功能表
MathTool mt=new MathTool();
Scanner sc =new Scanner(System.in);
int SelectItem;
System.out.println("**************************");
System.out.println("*1.求質數 *");
System.out.println("*2.FibonacciSequence數列 *");
System.out.println("*3.算整數陣列第二大值 *");
System.out.println("**************************");
if(sc.hasNextInt()){
SelectItem=sc.nextInt();
switch(SelectItem){
case 1:
System.out.println("請輸入一整數:");
int case1=sc.nextInt();
if(mt.JudgePrime(case1)==true){
System.out.println(case1+"是質數");
}else{
System.out.println(case1+"不是質數");
}
break;
case 2:
System.out.println("請輸入要查詢的第幾項數:");
int case2=sc.nextInt();
System.out.println("FibonacciSequence數列第"+case2+"項為"+mt.FibonacciSequence(case2));
break;
case 3:
System.out.println("請輸入陣列大小:");
int item=sc.nextInt();
int [] iarray=new int [item];
System.out.println("請輸入"+item+"個整數:");
for(int i=0;i<item;i++)
iarray[i]=sc.nextInt();
System.out.println("陣列第二大元素為"+mt.ArraySecondMax(iarray));
break;
default:
System.out.println("請輸入功能表內有的編號");
}
}else{
System.out.println("請輸入數字");
}
}
}
========================MathTool.java
Created with colorer-take5 library. Type 'java'
import java.util.TreeSet;
public class MathTool {//MathTool類別
public Boolean JudgePrime(int JudgeValue){//判斷質數回傳true表示是質數,false表示不是
Boolean WhetherPrime=true;
if(JudgeValue==1){//1不是質數
WhetherPrime=false;return WhetherPrime;
}else
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
}
public int FibonacciSequence(int count){//1,1,2,3,5,8,13....費布納西數列
int Acount1=1;//是放an
int Acount2=1;//是放a(n+1)
int Acount3=1;//是放a(n+2)
int temp2;//放前一次的a(n+2)
int temp1;//放前一次的a(n+1)
for(int i=3;i<=count;i++){
temp2=Acount3;
temp1=Acount2;
Acount3=temp2+temp1;
Acount2=temp2;
Acount1=temp1;
}
return Acount3;
}
public int ArraySecondMax(int[] a){//算整數陣列第二大值
TreeSet ts=new TreeSet();//new一個TreeSet物件ts
for(int i=0;i<a.length;i++)//用迴圈把整數陣列a的每一個值加進ts裡
ts.add(a[i]);
ts.remove(ts.last());//移除掉ts最後一個數(最大數)//所以現在ts最後一個數就是陣列a的第二大數,把他指派給變數SecondMax
int SecondMax=Integer.parseInt(ts.last().toString());
return SecondMax;//回傳SecondMax
}
}