欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Java-Kettle 问题(由裴树定理解决)

最编程 2024-07-18 22:19:28
...

水壶问题

有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断能否通过使用这两个水壶,从而可以得到恰好 z升 的水?如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水。

裴蜀定理(或贝祖定理):
若a,b是整数,且gcd(a,b)=d,那么对于任意的整数x,y,ax+by都一定是d的倍数,特别地,一定存在整数x,y,使ax+by=d成立。

边界问题的处理:
当x=0或者y=0时,判断y==z或x==y;
当z=0时,直接返回true;
当x+y<z的时候直接返回False。

测试示例:
示例1:
输入: x = 3, y = 5, z = 4
输出: True

示例2:
输入: x = 2, y = 6, z = 5
输出: False

import java.util.*;

public class Kettle {
    public static void main(String[] args) {
        System.out.println("请输入两个水壶的容量以及需要求的水的升数:");
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        System.out.println(canMeasureWater(a,b,c));;
    }
    //求最大公约数
    public static int euclid(int inte1, int inte2) {
        int surplus ;
        surplus  = inte1%inte2;
        while(surplus  != 0) {
            inte1 = inte2;
            inte2 = surplus ;
            surplus  = inte1%inte2;
        }
        return inte2;
    }
    public static boolean canMeasureWater(int x, int y, int z){
        // 首先判断约束条件
        if(x == 0)  return y == z;
        if(y == 0)  return x == z;
        if(z == 0)  return true;
        if(x+y < z) return false;
        int num = euclid(x,y);
        if((z%num)!=0)   return false;
        else    return true;
    }

}

初学者一枚,如有问题欢迎指正~

推荐阅读