【程序1】題目:古典問題:有一對兔子,從出生後第3個月起每個月都生一對兔子,小兔子長到第四個月後每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數爲多少?
//1.程序分析: 兔子的規律爲數列1,1,2,3,5,8,13,21....
import java.util.Scanner;
public class Demo1 {
public static int fun(int i){
if(i==1||i==2)
return 1;
else{
return fun(i-1)+fun(i-2);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for(int i=1;i<=n;i++){
System.out.println("第"+i+"個月"+fun(i));
}
}
}
【運行結果】
20
第1個月1
第2個月1
第3個月2
第4個月3
第5個月5
第6個月8
第7個月13
第8個月21
第9個月34
第10個月55
第11個月89
第12個月144
第13個月233
第14個月377
第15個月610
第16個月987
第17個月1597
第18個月2584
第19個月4181
第20個月6765
【程序2】題目:判斷101-200之間有多少個素數,並輸出所有素數。
public class Demo1 {
public static boolean fun(int n){
boolean result = true;
for(int i=2;i<n/2;i++){
if(n%i==0){
result =!result;
break;
}
}
return result;
}
public static void main(String[] args) {
for(int i=101,count=0;i<=200;i++){
if(fun(i)){
System.out.print(i+" ");
count++;
if(count%5==0)
System.out.println();
}
}
}
}
【運行結果】
101 103 107 109 113
127 131 137 139 149
151 157 163 167 173
179 181 191 193 197
199
【程序3】題目:打印出所有的’水仙花數’,所謂’水仙花數’是指一個三位數,其各位數字立方和等於該數本身。例如:153是一個’水仙花數’,因爲153=1的三次方+5的三次方+3的三次方
public class Demo1 {
public static boolean fun(int n){
int n1=n/100;
int n2=(n/10)%10;
int n3=n%10;
int sum=n1*n1*n1+n2*n2*n2+n3*n3*n3;
if(sum==n)
return true;
return false;
}
public static void main(String[] args) {
for(int i=100,count=0;i<=999;i++){
if(fun(i)){
System.out.print(i+" ");
count++;
if(count%5==0)
System.out.println();
}
}
}
}
【運行結果】
153 370 371 407