Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

>Solution :

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading