Testing divisibility by multiple numbers

后端 未结 5 1620
灰色年华
灰色年华 2021-01-13 03:46

In Python, is there a way to test if a number is divisible by multiple numbers without writing out the modulo operation for each factor?

More specifically, is there

相关标签:
5条回答
  • 2021-01-13 03:49
    if all(i % n == 0 for n in reversed(xrange(11, 101))):
        print(i)
    

    Only a slightly modified version of the duplicate answers already given: xrange returns an object that generates the numbers in the range on demand (slightly faster than range and more memory efficient). If performance is important here, which it often is for mathematical code snippets like this bit, the reverse iterator will check the bigger numbers first. This is more likely to kick you out of the all() function sooner.

    0 讨论(0)
  • 2021-01-13 03:58

    Useall()and a Generator Expression:

    if all(i % n == 0 for n in range(11, 101)):
        print(i)
    
    0 讨论(0)
  • 2021-01-13 04:00

    The above answer was:

    if all(i % n == 0 for n in range(11, 101)):
        print(i)
    

    which, it should be mentioned as clarification, only works with the built-in all function. I use Spyder, which by default uses the all from numpy.core.fromnumeric, and the above answer will not work in that case. Then use the following:

    import __builtin__
    
    if __builtin__.all(i % n == 0 for n in range(11, 101)):
        print(i)
    
    0 讨论(0)
  • 2021-01-13 04:09

    You could do something like this:

    if all(i % n == 0 for n in range(11, 101)):
        print(i)
    
    0 讨论(0)
  • 2021-01-13 04:10

    (Note: This is of mathematical interest but the previous answers are better in practice.)

    You could compute the least common multiple of all the divisors and see if the number is divisible by that. (Just taking the product doesn't work; consider N=16 with divisors 4 and 8.)

    0 讨论(0)
提交回复
热议问题