Write a function that returns True if a positive integer n is a prime number and False otherwise. Hint: use the % operator: x % y returns the remainder of x when divided by y.
A prime number: if it has two factors: 1 and the number itself
1-- no 2-- yes 3--yes 4--no 7-- yes
A prime number should not have any factors other than these two. -- when you go from 2 to n-1, should not find any non-trival factors that divides n without a remainder.
you can loop through all numbers from 2 to n-1 using the range() object in python.
range(start, stop, step) returns a range object. you can iterate over the range object to get a sequence from start to stop-1, in step of step.
so 2 to n-1 : for i in range(2, n)
1, if you find a number that divides n evenly without a remainder, you can conclude that the number is not prime.
2, if you've looped through the entire range of numbers from 2 to n-1 without finding a nuber that divides n evenly, then the number is prime.
def is_prime(n):
for i in range(2, n):
if n % i == 0;
return False
return True
Optimize
4-1,2,4 5-1,5 6-1,2,3,6 9-1,3,9 10-1,2,5,10 18-1,2,3,6,9,18
the only factor of n that is greater than n/2 is n itself
we can instead run the loop only up to n/2
def is_prime(n):
for i in range(2, int(n/2)):
if n % i == 0:
return False
return True