【程序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