So, I came across this question:
How many numbers exist from 1 to 1000, which are not divisible by the numbers 2, 3 and 5?
It seems pretty easy at first, so I wrote a quick python program to solve it:
count = 0
for number in range(1,1000):
if number % 2 != 0 and number % 3 != 0 and number % 5 != 0:
count += 1
print(count)
I got the correct answer (266), but I thought that it was a lot to do if I wanted to check more than just 3 values. I also wanted to make a mathematical decision, so I came across this:
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
I thought this was a good approach, so I implemented it in code:
def foo(ln = 1000), numbers = [2,3,5]:
div = 0
muldiv = 0
totdiv = 1
for n in numbers:
div += ln/n
for i in numbers:
for n in range(numbers.index(i)+1, len(numbers)):
muldiv += ln/(i * numbers[n])
for n in numbers:
totdiv *= n
answer = ln - (div - muldiv + ln/totdiv)
print("answer is ", math.floor(answer))
Now I'm sure I mixed up somewhere in my second function, because it doesn't seem to work for more numbers. For example, if I tried to find
How many numbers exist from 1 to 1000, which are not divisible by the numbers 2, 3, 5 and 7?
228
foo(numbers = [2,3,5,7])
300
... , 228
, , , , ? ?