How to make this Block of python code short and efficient

后端 未结 11 2510
天命终不由人
天命终不由人 2020-12-15 16:48

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\\         


        
11条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-15 17:34

    Many of the above code examples are shorter, but (probably) not efficient enough:

    n%2 == 0 =>
        n%4 6 8... ==0
    n%3 == 0 =>
        n%3 6 9... ==0
    

    We can use only primes to check within the range:

    if all(n % i == 0 for i in [2,3,5,7,11,13,17,19])
    

    Furthermore, if n divides all from 2 to 20, it divides the LCM of 2 to 20.

提交回复
热议问题