Python - 如何编写程序在不使用 %、// 或任何乘法的情况下获取两个数的商的余数?
Python - How to write a program to get the remainder of the quotient of two numbers without using %, //, / or any multiplication?
我真的卡在这上面了。我可以用整数除法和乘法来完成,但我不知道如何在没有这些运算符的情况下找到余数。 (也不能导入任何东西。主要前提是使用while循环)。
>>> def solution(a, b):
... while a >= b:
... a -= b
... return a
...
>>> solution(11, 5) == (11 % 5)
True
>>> solution(763, 47) == (763 % 47)
True
只是一个高效的:
def mod(a, b):
if a >= b:
a = mod(a, b + b)
if a < b:
return a
return a - b
演示:
>>> a, b = 75349157395712349036170927572349157024, 543791534729045
>>> mod(a, b)
510757213184524
>>> a % b
510757213184524
我真的卡在这上面了。我可以用整数除法和乘法来完成,但我不知道如何在没有这些运算符的情况下找到余数。 (也不能导入任何东西。主要前提是使用while循环)。
>>> def solution(a, b):
... while a >= b:
... a -= b
... return a
...
>>> solution(11, 5) == (11 % 5)
True
>>> solution(763, 47) == (763 % 47)
True
只是一个高效的:
def mod(a, b):
if a >= b:
a = mod(a, b + b)
if a < b:
return a
return a - b
演示:
>>> a, b = 75349157395712349036170927572349157024, 543791534729045
>>> mod(a, b)
510757213184524
>>> a % b
510757213184524