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

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

    In Python 3:

    def is_prime(a):
        if a < 2:
            return False
        elif a!=2 and a % 2 == 0:
            return False
        else:
            return all (a % i for i in range(3, int(a**0.5)+1))
    

    Explanation: A prime number is a number only divisible by itself and 1. Ex: 2,3,5,7...

    1) if a<2: if "a" is less than 2 it is not a prime.

    2) elif a!=2 and a % 2 == 0: if "a" is divisible by 2 then its definitely not a prime. But if a=2 we don't want to evaluate that as it is a prime number. Hence the condition a!=2

    3) return all (a % i for i in range(3, int(a0.5)+1) ):** First look at what all() command does in python. Starting from 3 we divide "a" till its square root (a**0.5). If "a" is divisible the output will be False. Why square root? Let's say a=16. The square root of 16 = 4. We don't need to evaluate till 15. We only need to check till 4 to say that it's not a prime.

    Extra: A loop for finding all the prime number within a range.

    for i in range(1,100):
        if is_prime(i):
            print("{} is a prime number".format(i))
    

提交回复
热议问题