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

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

    Most of previous answers are correct but here is one more way to test to see a number is prime number. As refresher, prime numbers are whole number greater than 1 whose only factors are 1 and itself.(source)

    Solution:

    Typically you can build a loop and start testing your number to see if it's divisible by 1,2,3 ...up to the number you are testing ...etc but to reduce the time to check, you can divide your number by half of the value of your number because a number cannot be exactly divisible by anything above half of it's value. Example if you want to see 100 is a prime number you can loop through up to 50.

    Actual code:

    def find_prime(number):
        if(number ==1):
            return False
        # we are dividiing and rounding and then adding the remainder to increment !
        # to cover not fully divisible value to go up forexample 23 becomes 11
        stop=number//2+number%2
        #loop through up to the half of the values
        for item in range(2,stop):
            if number%item==0:
               return False
            print(number)
        return True
    
    
    if(find_prime(3)):
        print("it's a prime number !!")
    else:
        print("it's not a prime")  
    

提交回复
热议问题