The %
is the modulo operator. If you want to check if it's a prime or not you should test if it's only dividable by itself and 1 to get a integer (not a floating point number).
So what you want to do is to loop though a list of integers. In your script you can provide the limit of this list (as I assume). Then for each number in the list you want to check if there's a number other than 1 or itself that can be used to divide the number into integers.
The easiest way to check if a the result of a division is a floating point number or an integer is to convert the result to an integer and check if the number is still the same.
By default if you do math in Python, it only works with integers. Example:
>>> 5 / 2
2
To do a calculation with floating point precision, you need to define at least one of the numbers as a floating point number. You can do this by writing it as a floating point number like this:
>>> 5.0 / 2
2.5
You can also convert integers to floating point numbers using the float
method:
>>> float(5)
5.0
>>> float(5) / 2
2.5
You can also convert floats to integers using the int
method:
>>> int(2.5)
2
>>> int(float(5))
5
Now if you do a comparison with floats and ints in Python, it doesn't matter if it's a float or int, but what matters is the actual value it represends:
>>> 5 == 5
True
>>> 5.0 == 5
True
>>> 2.5 == 2.5
True
>>> int(2.5) == int(2.5)
True
>>> int(2.5) == 2.5
False
Note the last comparison. We convert the float 2.5
to an int, so that becomes 2
, which isn't equal to the float 2.5
. We can use this trick to check if the result of a division is a float or an int:
>>> result = 6.0 / 2
>>> result == int(result)
True
>>> result = 5.0 / 2
>>> result == int(result)
False
Great! Let's use that in our loop! We assume the number is a prime until we have proven it's dividable by a number other than 1 or itself.
number = 5.0
# assume the number is a prime
prime = True
# try divisions from 2 through the number - 1
# which are all the numbers between 1 and the number itself
for divisor in range(2, number - 1):
# do the division
result = number / divisor
# check if the result is an integer number
if result == int(result):
# if so, the number is not a prime
prime = False
# since we found it is not a prime,
# we can break out of the for loop
break
The complete script could look something like this:
limit = int(raw_input("Enter a number: "))
number = 0
while number <= limit:
prime = True
for divisor in range(2, number - 1):
result = float(number) / divisor
if result == int(result):
prime = False
break
if prime:
print int(number)
number += 1