题目:给定2个容量分别为x升和y升的杯子,水无限,只允许进行如下操作:1、将一个杯子的水盛满;2、将一个杯子的水清空;3、一个杯子向另一个杯子倒水,直到一个杯子装满水,或者另外一个杯子的水为空。判断能否准确量出z升水(即其中一只杯子的水为z升或者两只杯子的水总共为z升)。
思路:归纳法 ,x=4,y=7时,能量出5升水,3*4-7=5,实际上能量出1~11之间的任意水量,2*4-7=1,4*4-2*7=2,7-4=3,4,3*4-7=5,7-(4-(7-4))=6,7,7+(2*4-7)=8,4*4-7=9,2*7-4=10,4+7=11
求x和y的最大公约数,使用辗转相除法(反复使用除数除以余数直至余数为0,最后一次除数即为最大公约数)
public boolean canMeasureWater(int x, int y, int z) {
if(z > x+y) return false;
if(x == 0){
if(z == 0 || y == z )
return true;
else
return false;
}
if(y == 0){
if(x == z || z == 0)
return true;
else
return false;
}
int bc = x, ch = y;
int rem = x % y;
while(rem != 0){ //
bc = ch;
ch = rem;
rem = bc % ch;
}
//if(ch == 1) return true;
if(z % ch != 0) return false;
else return true;
}