[Tutor] Help
Dave Angel
davea at ieee.org
Tue Jul 13 13:28:27 CEST 2010
Dipo Elegbede 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'
>
>
>
Break the problem down. Instead of solving the "print all the primes
from 1 to 20", first solve the "Is a given number prime".
then once you have a solution to that one, write a loop that calls it 20
times, printing its conclusions.
So suppose you have the number 12. How would you manually decide if
it's prime? You'd find the remainder for all the numbers between 2 and
11, inclusive, and if *any* of those came out zero, you'd say it's not
prime.
Write a function isprime() that expresses exactly that, returning False
if any of the modulos came out zero, and True if they're all okay. The
function will have a loop, and inside the loop have a single if statement.
Test the function by calling it explicitly with various values. Then
when you're comfortable with that, solve the bigger problem as stated.
DaveA
More information about the Tutor
mailing list