【程序 1】
题目:古典问题:有一对兔子,从出生后第 3 个月起每个月都生一对兔子,小兔子长到第
三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
1.程序分析: 兔子的规律为数列 1,1,2,3,5,8,13,21....
参考答案:
public class Rabbit {
private static int[] temp =new int[]{1,1};
public static void main(String[] args) {
getNumOfRabbit(12);
System.err.println("最终结果:"+temp[1]);
}
public static int getNumOfRabbit(int month) {
if(month==1||month==2){
}else{
System.err.println("1个月:"+temp[0]);
System.err.println("2个月:"+temp[1]);
for(int i=3;i<=month;i++){
int count=temp[0]+temp[1];
temp[0]=temp[1];
temp[1]=count;
System.err.println(i+"个月:"+temp[1]);
}
}
return temp[1];
}
}
【程序 2】
题目:判断 101-200 之间有多少个素数,并输出所有素数。
1.程序分析:判断素数的方法:用一个数分别去除 2 到 sqrt(这个数),如果能被整除,
则表明此数不是素数,反之是素数。
参考答案:
public class ShuShu {
public static void main(String[] args) {
int count=0;
for(int i=101;i<=200;i++){
int temp= i%2;
if(temp!=0){
boolean flag=true;
for(int j=2;j<i/2;j++){
if(i%j==0){
flag=false;
break;
}