Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

Python giving me an error for trying to mod two variables

I am trying to get the lowest number that is divisible by all the numbers from 1 to 20.

The problem is in i%j == 0. It's giving me this error:

ZeroDivisionError: integer division or modulo by zero

even though I tried the same thing with a variable and a constant and it passes:

i % 2 == 0

My code:

i = 20
while True:
    k = 0
    for j in range(21):
        if i % j == 0:
            k += 1
    if k == 21:
        break
    i+= 1

print(i)
question from:https://stackoverflow.com/questions/65864805/python-giving-me-an-error-for-trying-to-mod-two-variables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your current approach won't work for the time constraint - it'll just take too long to complete.

Try this code first and figure out what's the trick to save computing time.

primes = [2,3,5,7,11,13,17,19]
prod = 1

for p in primes:
    n = 2
    prod *= p
    while (p**n < 21):
        prod *= p
        n += 1
print(prod)   # 232_792_560

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...