栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JavaDay04.练习2.递归算法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaDay04.练习2.递归算法

走台阶问题:每次可以走一级或者两级,请问N个台阶一共有多少种走法?

import java.util.Scanner;
public class Homework {
    public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
        System.out.println("请您输入台阶数: ");
        int step = scanner.nextInt();
        int n = t1(step);
        System.out.println(n);
    }
    public static int t1(int step) {
        if (step < 0) {
            return -1;
        }
        if (step <= 2) {
            return step;
        }
        return t1(step - 1) + t1(step - 2);
    }
}

杨辉三角形,打印杨辉三角形,如下
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

public class Homework {
    public static void main(String[] args) {
     printYangHui();
    }
    
    private static int yangHui(int x, int y) {
        if (x == 1 || y == 1 || x == y) {
            return 1;
        }
        return yangHui(x - 1, y - 1) + yangHui(x - 1, y);
    }

    public static void printYangHui() {
        for (int i = 0; i < 10; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(yangHui(i, j) + "t");
            }
            System.out.println();
        }
    }
}

汉诺塔问题,三根柱子ABC,A柱子上有N个碟子,从上到下依次变大,现要求从A柱子把碟子移动到另一根柱子上,
移动过程中要求大盘子不能在下盘子之上,请使用Java程序来还原这个移动过程,计算当N个碟子的时候的移动

public class Tower {
    public static void main(String[] args) {
        hannuota(3, "A", "B", "C");
    }

    public static void move(int n, String i, String j) {
        System.out.println("第" + n + "个盘子,从" + i + "移动到" + j);
    }

    public static void hannuota(int n, String a, String b, String c) {
        if (n == 1) {
            move(n, a, c);
        } else {
            hannuota(n - 1, a, c, b);
            move(n, a, c);
            hannuota(n - 1, b, a, c);
        }
    }
}

求两个正整数的最大公约数和最小公倍数
x * y = 最大公约数 * 最小公倍数
f(m,n) = f(n,m%n)

import java.util.Scanner;
public class DivisorMultiple {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请您输入第一个数字: ");
        int num1 = scanner.nextInt();
        System.out.println("请您输入第二个数字: ");
        int num2 = scanner.nextInt();
        int gcd = gcd(num1, num2);
        System.out.println("最大公约数: " + gcd);

        int gbc = gbc(num1, num2);
        System.out.println("最小公倍数: " + gbc);
    }

    
    public static int gcd(int m, int n) {
        if (n == 0) {
            return m;
        }
        return gcd(n, m % n);
    }

    
    public static int gbc(int m, int n) {
        return m * n / gcd(m, n);
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/298862.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号