应用
小明在玩一个数字加减游戏,输入4个正整数:s、t、a、b,其中s>=1,b<=105,a!=b。只使用加法或者减法,使得s=t。
每回合,小明用当前的数字,加上或减去一个数字;目前有2种数字可以用来加减:a、b,其中b没有使用次数限制。 请问小明至少使用多少次a,才能使s=t?
实现
strings = input("请依次输入4个以空格分隔的正整数,分别代表s、t、a、b,其中s>=1,b<=105,a!=b:").split()
numbers = [int(i) for i in strings]
s, t, a, b = numbersM = 0def dividing_judgement(x, y):r = x % yif r == 0:result = Trueelse:result = Falsereturn resultif s <= t:result = dividing_judgement(t-s, b)# s可以通过b的整数倍相加变成tif result:print("至少使用0次a")else:while not result:s = s + aM += 1result = dividing_judgement(t-s, b)print(f"至少使用{M}次a")
else:result = dividing_judgement(s-t, b)# s可以通过b的整数倍相减变成tif result:print("至少使用0次a")else:while not result:s = s - aM += 1result = dividing_judgement(s-t, b)print(f"至少使用{M}次a")
请依次输入4个以空格分隔的正整数,分别代表s、t、a、b,其中s>=1,b<=105,a!=b:1 10 5 2
至少使用1次a