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
1.0k views
in Technique[技术] by (71.8m points)

performance - How to make this Block of python code short and efficient

I am total newbie to programming and python. I was solving a problem. I found the solution but it seems like too slow.

    if n % 2 == 0 and n % 3 == 0 and
       n % 4 == 0 and n % 5 == 0 and
       n % 6 == 0 and n % 7 == 0 and
       n % 8 == 0 and n % 9 == 0 and
       n % 10 == 0 and n % 11 == 0 and
       n % 12 == 0 and n % 13 == 0 and
       n % 14 == 0 and n % 15 == 0 and
       n % 16 == 0 and n % 17 == 0 and
       n % 18 == 0 and n % 19 == 0 and
       n % 20 == 0:

This is the piece the code to check whether n is divisible by all numbers from 2 to 20 or not.

How I can make it short and efficient.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There's a trade-off between short and efficient.

The Short way is if all(n % i == 0 for i in range(2, 21)):

The Efficient way is to notice that things like n % 20 == 0 also mean that n % f == 0 where f is any factor of 20. For example, you can drop n % 2 == 0. So you'll end up with fewer comparisons which will run faster. In doing this you'll notice a pattern and you'll notice that the entire statement reduces to if n % 232792560 == 0! But that has now deeply embedded the 20 within it so will be difficult to unpick if you need a different upper limit.

So you see that the efficient way is not so easy to read and maintain. So pick the one best suited to your requirements.


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

...