经典算法示例

程序员交流社区

添加小编微信:372787553,备注 进群

源代码地址:https://github.com/yanghaiji/Advanced-books/tree/master/source-code/src/main/java/com/javayh/advanced/java/algorithm/example

1. 有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第3个月后每个月又生一对兔子, 假如兔子都不死,问每个月的兔子总数为多少?

    /**
     *
     *  分析
     *		1	2	3	4	5	6	7
     * 种兔	1	1	1	1	2	3	5
     * 小兔	0	0	1	2	3	5	8
     * 总数	1	1	2	3	5	8	13
     *      当月的总数 = 前两个月的和
     */
    public static void main(String[] args) {
        for (int i = 0; i < 12; i++) {
            System.out.println(sum(i));
        }
    }

    /**
     * 求和
     * @param mo
     * @return
     */
    static int sum(int mo){
        //前两个月没有幼兔产生
        if(1 == mo || 2 == mo){
            return 1;
        }
        return sum(mo - 1) + sum(mo -2);
    }

2. 打印出所有的 "水仙花数 ",所谓 "水仙花数 "是指一个三位数,其各位数字立方和等于该数本身。

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

    public static void main(String[] args) {
        System.out.println(narcissus(153, 3));
        System.out.println(narcissus(100, 3));
    }

    /**
     *
     * @param num 原数据
     * @param pow 次方数
     * @return
     */
    static boolean narcissus(Integer num, Integer pow){
        int x , y , z = 0;
        //计算出十位与各位的数
        int ten = num % 100;
        //计算出百位
        x = num / 100;
        //计算出十位
        y = ten/10;
        //计算出各位
        z = ten % 10;
        int sum = (int) (Math.pow(x,pow) +  Math.pow(y,pow) +  Math.pow(z,pow));
        System.out.println("计算水仙花数的和为:"+sum);
        return sum == num;
    }

3. 判断1-20之间有多少个素数,并输出所有素数

public static void main(String[] args) {
    // 判断1-20之间有多少个素数,并输出所有素数
    // 不能被2整除的数
    System.out.println("个数:"+mouldTaking(20));

}
static int mouldTaking(Integer num){
    AtomicInteger sum = new AtomicInteger(0);
    for (int i = 1; i < num; i++) {
        if(i % 2 !=0){
            System.out.println("素数:"+i);
            sum.incrementAndGet();
        }
    }
    return sum.get();
}

4.二分查找

public static void main(String[] args) {
    int array[] = {3,5,11,17,21,23,28,30,32,50,64,78,81,95,101};
    System.out.println(binSerch(array,5,array.length-1,81));
}

/**
 *  递归实现
 * @param art 数组
 * @param start 开始下标
 * @param end   结束下标
 * @param key 需要查找的数值
 * @return
 */
public static int binSerch(int art[],int start,int end ,int key){
    int mid = (end + start)/2;
    if (art[mid] == key){
        return mid;
    }
    if (start >= end){
        return -1;
    }else if(key > art[mid]){
        return binSerch(art,mid+1,end,key);
    }else if(key < art[mid]){
        return binSerch(art,start,mid-1,key);
    }
    return -1;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小杨同学~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值