How to create the most compact mapping n → isprime(n) up to a limit N?

后端 未结 30 3460
遇见更好的自我
遇见更好的自我 2020-11-22 02:11

Naturally, for bool isprime(number) there would be a data structure I could query.
I define the best algorithm, to be the algorithm that pr

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 02:52

    In Python:

    def is_prime(n):
        return not any(n % p == 0 for p in range(2, int(math.sqrt(n)) + 1))
    

    A more direct conversion from mathematical formalism to Python would use all(n % p != 0... ), but that requires strict evaluation of all values of p. The not any version can terminate early if a True value is found.

提交回复
热议问题