1

as the title states, I want to find if integer i is divisible by all elements in a list.

I have this:

db = [3, 4, 5, 6, 7, 8]
i = 1
if all(i % d != 0 for d in db):
  i += 1

I tried using an if loop with all(), but it just skipped over that section even though the condition is met (I think). It should just add to the integer i until it is divisible by 3, 4, 5, 6, 7,and 8.

Any tips or anything I'm doing wrong?

Thanks, Ben

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Julia Fasick
  • 121
  • 7
  • 5
    What output are you expecting? It's a bit vague. – Austin Jan 02 '20 at 16:51
  • 1
    Does this answer your question? [built-in module to calculate least common multiple](https://stackoverflow.com/questions/51716916/built-in-module-to-calculate-least-common-multiple) – Rodrigo Rodrigues Jan 02 '20 at 16:56

2 Answers2

6

You checked the opposite:

If it's true for every element of db does not divide i.

You need to switch the branches of your if logic:

if all(i % d == 0 for d in db):
    print(i, "is divisible by all elements of the list")
else:
    i += 1

Alternately:

if any(i % d != 0 for d in db):
    i += 1
else:
    print(...)

Note that this appears to look for the lowest integer divisible by every integer in db. You can do this a lot faster by more directly finding the LCM (least common multiple) of the list. Put that into your browser's search bar.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • Nice edit, I was just about to suggest utilizing LCM as a tool instead, because it would provide a much faster solution. – Sunny Patel Jan 02 '20 at 16:54
  • 1
    @SunnyPatel yeah I agree lcm is the best way to go about it. I actually already wrote it that way, I wanted to try to approach it from this angle and I ran across this so I thought I'd just use this as an opportunity to learn something new. – Julia Fasick Jan 02 '20 at 16:57
1

if is not a loop. It looks like you meant to use while.

As well, you have the logic reversed. Use any instead of all.

db = [3, 4, 5, 6, 7, 8]
i = 1
while any(i % d != 0 for d in db):
  i += 1

print(i)  # -> 840

(I left out some info that Prune already covered in their answer.)

wjandrea
  • 28,235
  • 9
  • 60
  • 81