算法思想
1.窮舉算法
雞兔同籠:
上有三十五頭,下有九十四足,問雞兔幾何?
//窮舉算法
public static int qiongJu(int head ,int foot){
int temp ,i ,j ;
temp = 0 ;
for(i = 0 ;i <= head ;i++){
j = head - i ;
if(i*2 + j*4 == foot){
temp = 1 ;
chicken = i ;
rabbit = j ;
}
}
return temp ;
}
public static void main(String[] args){
int temp ,head ,foot ;
Scanner input = new Scanner(System.in) ;
System.out.println("窮舉法求解雞兔同籠問題:");
System.out.println("請輸入頭數:");
head = input.nextInt() ;
System.out.println("請輸入腳數:");
foot = input.nextInt() ;
temp = qiongJu(head,foot) ;
if(temp == 1){
System.out.println("雞有" + chicken + "只,兔有" + rabbit + "只。") ;
}else{
System.out.println("無法求解!");
}
}
2.遞推算法
斐波那契數列:兔子產仔
`public class Fibonacci {`
public static int raw(int n){
int t1 ,t2 ;
if(n == 1 || n == 2){
return 1 ;
}else{
t1 = raw(n-1) ;
t2 = raw(n-2) ;
return t1 + t2 ;
}
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("遞推算法求解兔子產仔問題!");
System.out.println("請先輸入時間:");
int n = scan.nextInt() ;
int num = raw(n) ;
System.out.println("經過" + n + "月的時間,共能繁殖"+ num + "對兔子!");
}
`}`
閱讀更多 給我一杯溫開水 的文章