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

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

    I have got a prime function which works until (2^61)-1 Here:

    from math import sqrt
    def isprime(num): num > 1 and return all(num % x for x in range(2, int(sqrt(num)+1)))
    

    Explanation:

    The all() function can be redefined to this:

    def all(variables):
        for element in variables:
            if not element: return False
        return True
    

    The all() function just goes through a series of bools / numbers and returns False if it sees 0 or False.

    The sqrt() function is just doing the square root of a number.

    For example:

    >>> from math import sqrt
    >>> sqrt(9)
    >>> 3
    >>> sqrt(100)
    >>> 10
    

    The num % x part returns the remainder of num / x.

    Finally, range(2, int(sqrt(num))) means that it will create a list that starts at 2 and ends at int(sqrt(num)+1)

    For more information about range, have a look at this website!

    The num > 1 part is just checking if the variable num is larger than 1, becuase 1 and 0 are not considered prime numbers.

    I hope this helped :)

提交回复
热议问题