蓝桥杯备考随手记: practise03

文章讲述了如何使用递归和辗转相除法解决小明切割矩形材料得到正方形的问题,具体分析了算法逻辑,并给出了Java代码实例,用于计算2019x324矩形材料能切割出的正方形总数。
摘要由CSDN通过智能技术生成

问题描述:

小明有一些矩形的材料,他要从这些矩形材料中切割出一些正方形。 当他面对一块矩形材料时,他总是从中间切割一刀,切出一块最大的正方形,剩下一块矩形,然后再 切割剩下的矩形材料,直到全部切为正方形为止。

例如,对于一块两边分别为5和3的材料(记为5×3),小明会依次切出3×3、2×2、1×1、1 ×1 共4个正方形。

现在小明有一块矩形的材料,两边长分别是2019和324。请问小明最终会切出多少个正方形?

思路分析:

对于一块矩形材料,如果其中一边的长度比另一边长,小明会切出一个边长等于较短边的正方形,并剩下一个边长为较长边减去较短边的矩形,直至两个边长相等。这个过程可以使用递归来解决,也可以看作是一个求最大公约数的问题,可以使用辗转相除法来实现。

代码实现:

递归:

public class Main {
    public static int countSquares(int length, int width) {
        if (length == width) {
            return 1; // 如果是正方形,返回1
        } else {
            int minSide = Math.min(length, width);
            int maxSide = Math.max(length, width);
            return 1 + countSquares(minSide, maxSide - minSide);
        }
    }

    public static void main(String[] args) {
        int length = 2019;
        int width = 324;
        int totalSquares = countSquares(length, width);
        System.out.println("小明最终会切割出 " + totalSquares + " 个正方形");
    }
}

辗转相除法:

public class Main {
    public static int countSquares(int length, int width) {
        int count = 0;
        while (length > 0 && width > 0) {
            count += length / width;
            int temp = width;
            width = length % width;
            length = temp;
        }
        return count;
    }

    public static void main(String[] args) {
        int length = 2019;
        int width = 324;
        int totalSquares = countSquares(length, width);
        System.out.println("小明最终会切割出 " + totalSquares + " 个正方形");
    }
}
  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值