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

后端 未结 30 3532
遇见更好的自我
遇见更好的自我 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:59

    When I have to do a fast verification, I write this simple code based on the basic division between numbers lower than square root of input.

    def isprime(n):
        if n%2==0:
            return n==2
        else:
            cota = int(n**0.5)+1
            for ind in range(3,2,cota):
                if n%ind==0:
                    print(ind)
                    return False
        is_one = n==1
        return True != is_one
    
    isprime(22783)
    
    • The last True != n==1 is to avoid the case n=1.

提交回复
热议问题