Why does the following code return True when it should return False. Trying to test if number is prime.
The intent of the code is to loop the this range(2,n) and if any number i divides n (remainder is 0) return False. The code returns True (incorrect) for 25 but False (correct) for 20. When the loop reaches 5 then 25%5 is 0 so it should return False. Where did I go wrong. There are other ways to check if number is prime but I want to know why this way does not work for 25 but does for 20.
def isPrime(n):
"""
"""
for i in range(2,n):
if n%i == 0:
return False
else:
return True
def main():
print isPrime(25) #Should return False
if __name__ == '__main__':
main()
Here is another implementation without the return statements that get so the area of the code that I would like to better understand.
for i in range(2,n+1):
if n%i == 0:
print 'for i =',i,'n%i =',n%i,'Therefore',n,'is not a prime'
print 'Should break out of loop here and return False'
else:
print 'for i =',i,'n%i =',n%i
Here is sample output.
for i = 2 n%i = 0 Therefore 10 is not a prime
Should break out of loop here and return False
for i = 3 n%i = 1
for i = 4 n%i = 2
for i = 5 n%i = 0 Therefore 10 is not a prime
Should break out of loop here and return False
for i = 6 n%i = 4
for i = 7 n%i = 3
for i = 8 n%i = 2
for i = 9 n%i = 1
So, shouldn't have broken out where i is 2 or when i is 5 when n is 10? Why doesn't it?
In your code you are checking with each number in that range and at the same time you are returning true or false, that's a bad idea. you have to return false if all the numbers in that range not matching with your condition. Instead of that in your coding you are checking for each element.
def isPrime(n):
"""
"""
for i in range(2, n):
if n % i == 0:
return False
else:
return True
print isPrime(25)
So if you write the else with for loop it will first execute for all the elements in range if nothing is matching it will it will go to the else part rather than checking if:..Else:.. for each element in that range.
Related
I've worked a lot on this but I can't figure out the problem. Can you help me?
The code should print numbers from 0 to 100 and print next to the prime numbers "Prime". The first function works but if I try to print the numbers all togheter the "prime" tag gets misplaced.
def testPrime(numTest):
if numTest <= 1:
return False
if numTest == 2:
return True
for i in range(2, numTest):
if (numTest % i) == 0:
return False
else:
return True
def printPrimes (lenght):
i = 0
while i <= lenght:
if testPrime(i):
print(str(i) + "Prime")
else:
print(str(i))
i += 1
printPrimes(100)
The logic in testPrime() is flawed. There are faster techniques but here's a trivial approach that may help:
def testPrime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
Since a prime number is defined a number a natural number greater than 1 that is not a product of two smaller natural numbers
I think this is the only lines you need.
def testPrime(n):
for i in range(2,n):
if n%i == 0:
return False
return True
Function to identify is n prime or not.
def test_prime(n):
if n == 1:
return False
elif n==2:
return True
else:
for e in range(2,n): # iteration from 2 to n
if e % 2 == 0:
return False
return True
Why is 3 not prime number here?
print(test_prime(3))
That is because the logic you have implemented is wrong. As it is already pointed out, your code currently is checking whether or not your input number is even or odd. For checking if the number is prime, you can do as follows:
def test_prime(n):
if n == 1:
return False
elif n==2:
return True
else:
for e in range(2,n): # iteration from 2 to n
if n % e == 0:
return False
return True
The else condition will check whether the remainder after dividing the input number by each number in range is 0 or not. If it's 0 then it's not a prime number. Also, you could run the loop from 0 to half of n, which is more efficient as suggested.
Number 3 is not prime number because of the logic in the code which goes from range(2,n), what will return number 2 and 2%2 == 0 which is False.
This question already exists:
Checking if a number is prime in Python [duplicate]
Closed 2 years ago.
def is_prime(num):
lst = []
if num > 1:
pass
else:
return False
for number in range(0, 1000000+1):
if str(num) in str(number):
continue
elif str(1) in str(number):
continue
elif str(0) in str(number):
continue
lst.append(number)
for x in lst:
if num % num == 0 and num % 1 == 0 and not(num % x == 0):
return True
else:
return False
print(is_prime(9))
I do not know what is the problem with my code and I cannot find a solution the point of the program is to check whether the number is a prime number or not(prime number is only divisible by 1 and itself). The for loop just doesn't seem to work or something
def isprime(n):
return (all([False for i in range(2,n) if n % i == 0 ]) and not n < 2)
print (isprime(0))
print (isprime(1))
print (isprime(2))
print (isprime(3))
print (isprime(9))
print (isprime(10))
print (isprime(13))
Output:
False
False
True
True
False
False
True
Or:
def isprime(n):
if n < 2: return False
for i in range(2, n):
if n % i == 0:
return False
else:
return True
Line 16-19:
if num % num == 0 and num % 1 == 0 and not(num % x == 0):
return True
else:
return False
The first statement, num % num == 0 is finding the remainder when num is divided by num, which is always zero and therefore this statement is always true. num % 1 == 0 is also always true, so your code is equivalent to:
if not(num % x == 0):
return True
else:
return False
Which means, in the context of your program, "if the first value in lst is not a factor of num, then num is prime. Otherwise, num is not prime"
This only runs the loop one time and is backwards. Instead, you need to check if one of the numbers in lst is a factor to return False, and if all of the number is lst are not factors, then return True
for x in lst:
if num % x == 0:
return False
return True
for x in lst:
if num % num == 0 and num % 1 == 0 and not(num % x == 0):
return True
else:
return False
This loop can only ever run once, as it's guaranteed to return either true or false at the first iteration. If you find any factors, you want to return False. Otherwise, True.
for x in range(2, num):
if num % x == 0:
return False
return True
(Also, I'm not sure what was going on with the str shenanigans or the num % num / num % 1 conditions, both of which are always zero. But those should be unnecessary)
Except for 2 itself, you should only check divisibility by odd numbers up to the square root of the value.
Here's a short version:
def isPrime(N):
return all(N%p for p in range(3,int(N**0.5)+1,2)) if N>2 and N&1 else N==2
I'm trying to define prime numbers, but my algorithm doesn't recognize 2 as a prime number. Instead return None. I try it in Google Colab, Jupiter Notebook and PyCharm with same result.
My code:
# V1) Test all divisors from 2 through n-1. (skip 1 and n)
def is_prime_v1(n):
""" Return 'True' if 'n' is a prime number. False otherwise. """
if n == 1:
return False # 1 is not prime
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
# ===== Test Function =====
for n in range(1, 21):
print(n, is_prime_v1(n))
My output:
1 False
2 None
3 True
4 False
5 True
6 False
7 True
8 False
9 True
10 False
11 True
12 False
13 True
14 False
15 True
16 False
17 True
18 False
19 True
20 False
Additionally, the return has some erros, like 9 is not a prime number.
This code is from, starting in 0:46: Python and Prime Numbers || Python Tutorial || Learn Python Programming
Because Your program never enters the loop.
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
starts from 2, up until n-1.
Also, you should indent it differently. Only after your program exited the loop should you return True:
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
But if you want to optimize your function, it should be like this:
def is_prime_v1(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for d in range(3, round(n**0.5) + 1, 2):
if n % d == 0:
return False
return True
Since you dont need to check up to the number itself, only it's square root.
Also, no number that is even can ever be prime (except 2), since it would be divisible by two.
EDIT:
I'm happy my answer helped :)
You can explicitly define 2 as prime.
The return True is inside your for loop and so is returning true after just 1 iteration (which is why you have errors).
For primes, it suffices to check only up to the square root of the number you are testing, this should speed things up considerably for large n.
Try this
def is_prime_v1(n):
""" Return 'True' if 'n' is a prime number. False otherwise. """
if n == 1:
return False # 1 is not prime
elif n == 2:
return True
for d in range(2, int(n**0.5) + 1):
if n % d == 0:
return False # Is not prime
return True
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
Create a separate if for it like you did for 1.
if n == 2:
return True #2 is prime
I have a little problem when i need to determine if a number , x is a prime number or not.
x will be a randomly generated positive integer and i get the following message when i execute code:
Your function fails on is_prime(2). It returns None when it should return True.
My code:
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x):
while x % n == 0:
return False
break
else:
return True
i want the while loop to iterate through n == 2 up to n == (x-1) but it doesnt seem to do it!
what am i doing wrong?
You could write this function much more simplier:
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
So your call for is_prime(2) wouldn't pass the if test and wouldn't be used in the for run and would just return True.
All other prime numbers should be tested if they are greater than 3 and not even.