算法應用之百錢買白雞
案列說明:主要內容是:公雞5元一隻,母雞3元一隻,小雞1元三隻,問100元怎樣可以買100雞?
思想:想要實現此算法,只要明白各種條件的關係即可,而且知道公雞最多買20只,母雞最多買33只,小雞最多買100只,這樣買各種雞的錢總爲100,元,雞的只數也是100;
publicclass BQMJ {
publicstaticvoid main(String[] args) {
intcock,hen,chicken=0;
for(cock=0;cock<=19;cock++){
for(hen=0;hen<=33;hen++){
chicken=100-cock-hen;
int p;
p=chicken%3;
if(((5*cock+3*hen+chicken/3)==100)&&(p==0)){
System.out.print(" 可以買公雞的只數:"+cock);
System.out.print(" 可以買母雞的只數:"+hen);
System.out.print(" 可以買小雞的只數:"+chicken);
System.out.println("\n");
}
}
}
}
}
算法應用之韓信點兵
案列說明:韓信帶兵不足百人,3人一行排列多一人,7人一行排列少兩人,5人一行正好,本例是計算韓信究竟點了多少兵?
想法:對於韓信點兵算法,只需將7人少2人轉換7人多5人,這樣解決問題的方法就很明顯了,再限定人數不多於100即可。
實現代碼:
publicclass Hxin {
publicstaticvoid main(String[] args){
inta=0,b=0,c=0,preson;//定義總人數和各種站法的剩餘人數 for(preson=0;preson<100;preson++){
a=preson%3;//每排三人剩餘人數
b=preson%7;//每排七人的剩餘人數c=preson%5;//每排五人的剩餘人數
if(a==1&&b==5&&c==0){//都符合條件時的人數
System.out.println("韓信帶的兵數是:"+preson);
}
}
}
}
算法應用之斐波那契數列
說明:斐波那契數列的定義:它的第一項和第二項均爲1,以後各項都爲前兩項之和
難點:如何設計好循環
public class Fbo {
private static void f (int x){
int f1=1,f2=1,i=3;
if (x==1) System.out.print (f1);
if(x==2)System.out.print(f1+" "+f2);
if(x>=3){//求位置大於三的數列System.out.print(f1+" "+f2);
while(x>=i){//求數列f1=f2+f1;//求兩項之和System.out.print(" "+f1);
i++;
f2 = f2 + f1;
System.out.print(" "+f2);
}
}
}
public static void main (String[] args) {
Scanner s = new Scanner (System.in);
System.out.println("請輸入你想查看的斐波那契數列個數:");
int num = s.nextInt ();
System.out.println("你想看的斐波那契數列:");
f (num/2+1);
}
}
算法應用之漢諾塔
案列說明:漢諾塔問題是一個古典的數學問題,內容是:漢諾塔(又稱河內塔)問題是源於印度一個古老傳說的益智玩具。大梵天創造世界的時候做了三根金剛石柱子,在一根柱子上從下往上按照大小順序摞着64片黃金圓盤。大梵天命令婆羅門把圓盤從下面開始按大小順序重新擺放在另一根柱子上。並且規定,在小圓盤上不能放大圓盤,在三根柱子之間一次只能移動一個圓盤。
難點:將n個盤子從一個座移到另一個座上,這是每個移動者要做的,除去第一個移動者外,其餘都要命令其他的移動者,就是第一個移動者開始,任務層層下放,最後將一個盤子從一個座移到另一個座上,這是第一個移動者自己做的工作,
public class Hanoi {
private static void move (charx,char y) {
System.out.printf ("%c-->%c",x,y);
System.out.print ("\n");
}
private static void hanoit (int n,char one,char two,char three){
//將n個盤子從第一座藉助第二座移到第三座
if (n==1){//如果只有一個盤子
move(one,three);
} else{
hanoit(n-1,one,three,two);//將一上的盤子藉助三移到二上 move(one,three);
hanoit(n-1,two,one,three);//將二上的盤子藉助一移到三上 }
}
public static void main(String[] args) {
int m;
System.out.println("請輸入你要移動的盤子數:");
Scanner s=new Scanner(System.in);
m=s.nextInt();
System.out.println("移動"+m+"個盤子的步驟如下");
hanoit(m,'A','B','C');
}
}