[Tutor] Finding prime numbers script runs much faster when run via bash shell than idle

Karim karim.liateni at free.fr
Sat Apr 2 08:50:30 CEST 2011


On 04/02/2011 07:10 AM, Jaime Gago wrote:
> Hello there,
> Totally new to python with some *nix scripting knowledge.
>
> I wrote a simple piece of code as an exercise to an online -free- class that finds prime numbers. When I run it via IDLE it's taking way more time than if I run it via a (bash) shell (on Os X 10.6) while doing $>python -d mypp.py
>
> I'm really curious from a performance perspective as to what could cause such a noticeable difference.
>
> Thank you very much!
>
> Here is the code
>
> -------
> #Finding the 1000th Prime number
> #
> #
> ### STATE VARIABLES INITIALIZATION ###
>
> tested_number = 3
> testing_against = 3
> prime_counter = 1
>
> ### Starting the loop ##
>
> ### Number of prime numbers we want to find ##
> while(prime_counter<  1000):
> ### Testing if there is remainder of the division by the testing_against var
>      while ((tested_number%testing_against != 0) and (testing_against<  tested_number)):
>          testing_against=testing_against + 1
>      if (tested_number != testing_against):
>          x = 1
>      else:
>          prime_counter = prime_counter + 1
>          print prime_counter, 'found so far'
> ## Incrementing the tested number by 2 so we only test odd numbers
>      tested_number = tested_number + 2
> ## Reinitialization of the testing_against var to reenter the second loop in the required var state
>      testing_against = 3
> ## Printing the prime number
> print (tested_number - 2), 'is the 1000th prime number'
> ------
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Just a advice for readibility:

testing_against += 1
prime_counter = prime_counter + 1

instead of:

testing_against=testing_against + 1
prime_counter += 1


And IDLE add a layer due to the interactive feature to display result.
It is python interpreter plus Tk layer. Just a thought nothing truly
precise.

Regards
Karim








More information about the Tutor mailing list