Finding the nth prime number using Python -


when run code, counting 10th prime number (instead of 1000) skewed/jacked output--all "not prime" titles is_composite variable, test_num giving me prime , composite numbers, , prime_count off

some of answers developers have shared use functions , math import--that's haven't yet covered. not trying efficient answer; trying write workable python code understand basics of looping.


  # test prime diving number previous sequence of number(s) (% == 0).    # counting 1 way 1000.  test_num = 2 #these numbers being tested primality is_composite = 'not prime' # counted prime_count prime_count = 0 #count number of primes   while (prime_count<10): #counts number primes , make sures loop stops after 1000th prime (here: running tenth quick testing)    test_num = test_num + 1   # starts two, tested primality , counted if  x = test_num - 1  #denominator prime equation   while (x>2):      if test_num%(x) == 0:    is_composite = 'not prime'   else:     prime_count = prime_count + 1    x = x - 1      print is_composite   print test_num   print prime_count  

see hints given mit assignment. quote them below:

  1. initialize state variables

  2. generate (odd) integers > 1 candidates prime

  3. for each candidate integer, test whether prime

    3.1. 1 easy way test whether other integer > 1 evenly divides candidate 0 remainder. this, can use modular arithmetic, example, expression a%b returns remainder after dividing integer integer b.

    3.2. might think integers need check divisors – don’t need go beyond candidate checking, how sooner can stop checking?

  4. if candidate prime, print out information know in computation, , update state variables

  5. stop when reach appropriate end condition. in formulating condition, don’t forget program did not generate the first prime (2).

it this:

def primes(n):     # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188     """ returns  list of primes < n """     sieve = [true] * n     in xrange(3,int(n**0.5)+1,2):         if sieve[i]:             sieve[i*i::2*i]=[false]*((n-i*i-1)/(2*i)+1)     return [2] + [i in xrange(3,n,2) if sieve[i]] 

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -