background image

【程序

1】  

 

题目:古典问题:有一对兔子,从出生后第

3 个月起每个月都生一对兔子,小兔子长到第三个月后每个月

又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

   

//这是一个菲波拉契数列问题

public class lianxi01 {
public static void main(String[] args) {
System.out.println("第 1 个月的兔子对数:    1");
System.out.println("第 2 个月的兔子对数:    1");
int f1 = 1, f2 = 1, f, M=24;
     for(int i=3; i<=M; i++) {
      f = f2;
      f2 = f1 + f2;
      f1 = f;
      System.out.println("第" + i +"个月的兔子对数: "+f2);
         }
}
}
【程序

2】   

题目:判断

101-200 之间有多少个素数,并输出所有素数。 

程序分析:判断素数的方法:用一个数分别去除

2 到 sqrt(这个数),如果能被整除, 则表

明此数不是素数,反之是素数。

   

public class lianxi02 {
public static void main(String[] args) {
    int count = 0;
    for(int i=101; i<200; i+=2) {
     boolean b = false;
     for(int j=2; j<=Math.sqrt(i); j++) 
     {
        if(i % j == 0) { b = false; break; } 
         else           { b = true; }
     }
        if(b == true) {count ++;System.out.println(i );}
                                  }
    System.out.println( "素数个数是: " + count);
}
}
【程序

3】   

题目:打印出所有的

 "水仙花数 ",所谓 "水仙花数 "是指一个三位数,其各位数字立方和

等于该数本身。例如:

153 是一个 "水仙花数 ",因为 153=1 的三次方+5 的三次方+3

的三次方。
public class lianxi03 {
public static void main(String[] args) {
     int b1, b2, b3;