Finding the nth prime number using Python

前端 未结 4 1779
礼貌的吻别
礼貌的吻别 2020-12-16 08:21

When I run this code, even for just counting to the 10th prime number (instead of 1000) I get a skewed/jacked output--all \"not prime\" titles for my is_composite variable,

4条回答
  •  情书的邮戳
    2020-12-16 09:04

    First of all, from the vague description of your prime checking algorithm, it appears that you are checking every number up to the number that you are testing for primality. However, in reality you are only required to test up to the square root of that number. A further optimization would be to remove all even numbers apart from two (you can do this by incrementing by twos from one and testing 2 separately), you end up with:

    def isprime(test):
        if test == 2: return True
        if test < 2 or test % 2 == 0: return False
        return not any(test % i == 0 for i in range(3, int(sqrt(test)) + 1, 2))
    

    Then all you have to do is iterate through the numbers from 2 upwards checking if they are prime and adding one to your counter if they are. When you reach 1000 stop and output the number being passed to the isprime function.

    Of course there are other more efficient methods, I personally prefer the Sieve of Atkin. But it would be up to you to implement that, my algorithm will serve your purposes.

    Edit: I noticed your comment that 'nothing is returning/happening' that would be due to the inefficiency of your algorithm, if you wait long enough you will get an answer. However, I do notice that you have no print statement in the code you provided, I'm hoping the code which your running has one.

    from math import sqrt
    
    def isprime(test):
        if test == 2: return True
        if test < 2 or test % 2 == 0: return False
        return not any(test % i == 0 for i in range(3, int(sqrt(test)) + 1, 2))
    
    test_num = 2
    prime_count = 1
    
    while (prime_count< 1000): 
    
     test_num = test_num + 1  
    
     if (isprime(test_num)):
         prime_count += 1
    
    print test_num
    

提交回复
热议问题