[Tutor] Help

Shashwat Anand anand.shashwat at gmail.com
Wed Jul 14 04:38:54 CEST 2010


On Tue, Jul 13, 2010 at 3:20 PM, Dipo Elegbede <delegbede at dudupay.com>wrote:

> I was trying to write a code that prints prime numbers between 1 and 20.
>
> I have by myself seen that something is wrong with my code and also my
> brain.
>
> Could anyone be kind enough to tell me what to do....
>
> Where I am confused is how to test for other numbers without one and the
> number itself. It turns out that all numbers pass the condition I set so
> that would presuppose that all numbers are prime which is not.
>
> How exactly can I get it to run checks with other numbers such that it
> doesn't include the number itself and 1.
>
> The code is as follows:
>
> for i in range(1,20):
>
>     if float(i) % 1 == 0 and float(i) % i == 0:
>         print i, 'is a prime number'
>

Do you realize that all the numbers are divisible by 1. Hence float(i) % 1
_will be always zero_.
Now again, Do you realize that every number is divisible by itself. So
float(i) % i will also always be zero.
Also are you using float when dealing with integers.
Steps:
* You should probably check whether a number is prime.
* Then you should add extra loop to check whether in a given range of
numbers how many are prime.
* Now you optimize the code for lesse number of calculations, say for n
check for divisibility only until sqrt(n)
* Now you read wiki, read about sieve and apply sieve of erastothenes, to
make the code fast.
* Again memoize your code, so that it becomes more fast.
With all this done, you have a pretty handy code with yourself, coded by
you.
* Now solve this problem - https://www.spoj.pl/problems/PRIME1/ , which
can't be solved unless your code is highly optimized.
* If you have more curiosity, look for sieve of atkin.

Finish these and you are well off with primes :)

~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/97c7eccc/attachment.html>


More information about the Tutor mailing list