user1906430 - 4 months ago 13

Python Question

I'm trying to brute-force a projecteuler questions before I improve my code. I can't get multiple condition and logical operator working in my loop. Here is the code, editor shows no errors but it simply don't increase condition value so obviously some of the conditions are wrong. Can some one show me the correct way to use multiple and logical operators?

`i = 20`

while (i % 2 != 0 and i % 3 != 0 and i % 4 != 0 and i % 5 != 0 and

i % 6 != 0 and i % 7 != 0 and i % 8 != 0 and i % 9 != 0 and

i % 10 != 0 and i % 11 != 0 and i % 12 != 0 and i % 13 != 0 and

i % 14 != 0 and i % 15 != 0 and i % 16 != 0 and i % 17 != 0 and

i % 18 != 0 and i % 19 != 0 and i % 20 != 0):

i = i + 20

else:

print(i)

Answer

It looks like you're trying to find the smallest number which is a multiple of all integers from 1 to 20 inclusive. You're starting with 20, and you want to keep going up by 20 until your condition is met.

It's easier to see the problem in a smaller case. Say we only cared about 2, 3, and 4.

We want to find a number i for which

```
i % 2 == 0 and i % 3 == 0 and i % 4 == 0
```

But the negation of this is either

```
not (i % 2 == 0 and i % 3 == 0 and i % 4 == 0)
```

or, distributing the `not`

,

```
i % 2 != 0 or i % 3 != 0 or i % 4 != 0
```

In other words, if *any* of the numbers fail to divide evenly, you want to increase by 20, not if *all* of them fail to.

20, for example, is divisible by 2, so `i % 2 != 0`

is False, so you have `False and i % 3 != 0 and.. etc`

, which will still be false. A working version of your code would look like

```
i = 20
while any(i % num != 0 for num in range(2,21)):
i += 20
```

where I've used a generator expression to avoid all the duplication. Note thought that this will be *very much* slower than using the math trick they want you to use, because the final answer has 9 digits..