Python prime numbers

Wiktor look at signature.invalid
Sat Feb 1 18:34:02 EST 2014


On Sat, 1 Feb 2014 07:33:47 -0800 (PST), Panagiotis Anastasiou wrote:

> Hi i'm new in programming and in python and i have an assignment that
> i cant complete. I have to Write a Python program to compute and print the 
> first 200 prime numbers. The output must be formatted with a title and the 
> prime numbers must be printed in 5 properly aligned columns . I have used this 
> code so far :

  Hi,
  try out this code:

for i in range(200):
   print '{0:>5}'.format(i),
   if (i-4) % 5 == 0:
       print

  Or maybe, if it's still unclear, try execute these lines:

print 'Hello {0}'.format('world')
print '|{0:>30}|'.format('right')
print '|{0:<30}|'.format('left')
print '|{0:^30}|'.format('center')
print '|{0:>16}|'.format('right'),
print '|{0:<16}|'.format('left'),
print '|{0:^16}|'.format('center')

  But still, it might be hard to implement this printing for..in loop while
you're verifying primes (in another loop), so maybe think about getting first
200 primes in while loop like you do (and only storing them in a list), and
then printing them out from this list in external for..in loop.



  Now, to your primetest() function. It may be good for small primes, but try
to verify with it, if 832475734579 is a prime. :)

> def primetest(potentialprime):
>     divisor = 2
>     while divisor <= potentialprime:

  First of all, see that you rarely use this loop - you check this condition at
most two times. You end up for good in the second while loop.

>         if potentialprime == 2:
>             return True
>         elif potentialprime % divisor == 0:
>             return False
>             break

  'break' after return is redundant - never executes

>         while potentialprime % divisor != 0:
>             if potentialprime - divisor > 1:
>                 divisor += 1
>             else:
>                 return True

  So, this is your main loop. Very inefficient. Think about that:
a) do you really have to check divisors up to the potentialprime? 
   Maybe there is a point, where you may say, that you've checked all 
   possibilities? Remember that a * b = b * a 
b) do you really have to check every divisor? I mean, increasing 
   it by 1 in every step?

-- 
Best regards,     Wiktor Matuszewski
'py{}@wu{}em.pl'.format('wkm', 'ka')



More information about the Python-list mailing list