过一遍经典算法题,写写代码顺便整理思路

一、兔子问题

package demo;

import java.util.Scanner;

publicclass Test01 {

   /*

    * 【程序1题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第四个月后每个月又生一对兔子,假如兔子都不死,

    * 问每个月的兔子总数为多少? 1.程序分析:兔子的规律为数列1,1,2,3,5,8,13,21….

第N个月

0

1

2

3

4

5

1月小兔子

1

0

1

1

2

3

2月小兔子

0

1

0

1

1

2

成兔

0

0

1

1

2

3

总数

1

1

2

3

5

8

 

    */

   publicstaticvoid main(String[] args) {

      Scanner sc = new Scanner(System.in);

      System.out.println(math.myMath(sc.nextInt()));

   }

}

 

class math {

   publicstaticint myMath(intx) {

      if (x == 1 || x == 2) {

        return 1;

      } else {

        return myMath(x – 2) + myMath(x – 1);

      }

   }

}

 

 

 二、判断素数

package demo;

 

publicclass Test02 {

/* 【程序2   题目:判断101-200之间有多少个素数,并输出所有素数。  

   1.程序分析:判断素数的方法:用一个数分别去除2sqrt(这个数),如果能被整除,  

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

*/

   publicstaticvoid main(String[] args) {

      StringBuilder sb=new StringBuilder();

      for(intx=100;x<200;x++){

        if(mathTool.ispn(x)){

        sb.append(x);

        sb.append(“,”);

        }

      }

      sb.delete(sb.length()-1, sb.length());

      System.out.println(“100-200间素数包括:+sb);

   }

 

}

class mathTool{

   publicstaticboolean ispn(intx) {

      booleanflag=true;

      for(inty=2;y<x;y++){

        if(x%y==0){

           flag=false;

        }

      }

      returnflag;

   }

}

 

 

 三、水仙花数

package demo;

 

publicclass Test03 {

/* 【程序3   题目:打印出所有的水仙花数,所谓水仙花数是指一个三位数,

 * 其各位数字立方和等于该数本身。例如:153是一个水仙花数,因为153=1的三次方+5的三次方+3的三次方。  

        1.程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。  

*/

   publicstaticvoid main(String[] args) {

      StringBuilder sb=new StringBuilder();

      for(intx=100;x<999;x++){

        if(Tool03.isFlower(x)){

           sb.append(x);

           sb.append(“,”);

        }

      }

      sb.delete(sb.length()-1, sb.length());

      System.out.println(“100-999包含水仙花数:”+sb);

   }

 

}

class Tool03{

   publicstaticboolean isFlower(intx){

      booleanflag=false;

      intbai=x/100;

      intshi=x%100/10;//%100取十位数和个位数

      intge=x%10;

      //结论:取上位用除,取下位用模

      if((int)Math.pow(bai, 3)+(int)Math.pow(shi, 3)+(int)Math.pow(ge, 3)==x){

        flag=true;

      }

      returnflag;

   }

}

 

————————————————————————————————————————————————————————————————

持续更新中  17-4-10  12:19

点赞