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

一、兔子问题

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值