Home > Enterprise >  How would I use a modulus operator on a range of numbers? (Python)
How would I use a modulus operator on a range of numbers? (Python)

Time:08-02

I want to have a number incrementing indefinitely and check if the number is divisible by all numbers from 1 to 20. Here's my example code attempting to prove a concept

        ans = 0
        for num in range(1, 100000000):
            print(num)
            for factor in range(1,21):
                #This is where you guys come in
                if num % range(1,21) == 0:
                     ans = num
                     break

I am assuming there is an easier way to increment indefinitely. I am also assuming there is an easier way to use the modulus operator on a range of numbers.

TLDR: Instead of having to go like this:

#Unwanted product
if num % 1 or num % 2 or num % 3... or num % 20

I would much prefer a simpler option such as:

#Proof of concept
if num % range(1,21)

For further context, this is regarding question #5 on Project Euler.

CodePudding user response:

To check if num is "divisible by all numbers from 1 to 20":

if not num % 232792560:
    print('divisible by all')

(The number 232792560 is the least common multiple of the numbers 1 to 20.)

  • Related