所以我遇到了这个问题:
从1到1000有多少个数字不能被数字2,3和5整除?
起初看起来很简单,所以我写了一个快速的python程序来解决它:
count = 0
for number in range(1,1000):
if number % 2 != 0 and number % 3 != 0 and number % 5 != 0:
count += 1
print(count)
Run Code Online (Sandbox Code Playgroud)
我得到了正确的答案(266),但我认为如果我想检查的不仅仅是3个值,那么这样做是很多打字.我也想做一个数学解决方案所以我遇到了这个:
1000 - ((1000/2 +1000/3 +1000/5) -(1000/2x3 +1000/2x5 + 1000/3x5)+ (1000/2x3x5)) = 1000-((500+333+200) - (166 +100 + 66) + 33) = 1000- 734 = 266
我认为这是一个很好的方法,所以我在代码中实现它:
def foo(ln = 1000), numbers = [2,3,5]:
div = 0
muldiv = 0
totdiv = 1
for n in numbers:
div += …Run Code Online (Sandbox Code Playgroud)