Python prime number check - python

guys!
I have a codecademy Python course excercise in which I have to check if parameter passed is prime. My code looks like this:
def is_prime(x):
for n in range(2, x-1):
if (x < 2):
return False
elif(x % n == 0):
return True
else:
return False
It seems to me that I have covered all possibilities, but it constatnly displays this error:
Your function fails on is_prime(0). It returns None when it should return False.
This falls in the first if-condition as far as I can see. Can someone explain how this is possible?

Hint, what numbers are inside range(2, x-1) when x is 0?

This version may works.
def is_prime(x):
if (x < 2):
return False
for n in range(2, x-1):
if(x % n == 0):
return False
return True

Related

Python RecursionError

(I'm a total beginner)
I want to write a recursive function which can tell me if a number is a prime number or not: but I keep getting the same recursion error :
here is my code :
from math import *
def has_a_divider(n,p):
if n%p==0:
return True
elif has_a_divider(n,(p-1))!= True:
return False
else:
return False
def is_prime(a):
if has_a_divider(a,sqrt(a))==False:
return True
else:
return False
Your problem is sqrt(a) which returns a float instead of the int your code requires.
You can replace it by ceil(sqrt(a)) to get an int from it.
Also, this code does not work for finding if the number is prime as all numbers will have at least 1 has a divider. A possible solution is to update has_a_divider to check for dividers bigger than 1.
A possible implementation:
from math import ceil, sqrt
def has_a_divider(n,p):
if p < 2:
return False
if n % p==0:
return True
return has_a_divider(n,(p-1))
def is_prime(a):
if a == 1:
return False
return not has_a_divider(a,ceil(sqrt(a)))
print(is_prime(3))
print(is_prime(5))
print(is_prime(4))

Upper bound equal to lower in Python range

Can someone please explain to me why this code works for 2 as well:
def is_prime_v1(n):
'''Return True if 'n' is prime. False otherwise.'''
if n == 1:
return False
for d in range(2,n):
if n % d == 0:
return False
return True
when the code gets to
for d in range(2,n):
if n % d == 0:
return False
return True
Would it not see this as start at 2 but go up to and do not include 2?
This does not make complete sense to me.
The formula works but if you try and create a list on that range like so:
x = list(range(2,2))
You get an empty list.
Please could anyone explain this to me? Does it work for two as well because it would not be able to do the below on range(2,2) and then moves down to return True?
if n % d == 0:
return False
return True
Thanks
because for loop is never executed , list(range(2,2)) == [], so the program didn't iterate over range and directly proced to return True statement
Your assumption is correct. The upper value of the range function is not put through the for loop. To overcome this, you could just add or n == 2 to the third line of your program.

Prime number calculator functions, why is one correct and the other incorrect?

I've seen some similar codes here on stack overflow but none had my same question.
basically, my question is why when I tried to check the inequality (!=) in the for loop it didn't work. But when I tried using the equality (==) it worked fine?
so this code returns True always:
def is_prime(x):
if x == 2:
return True
else:
for i in range(2, x):
if x > 2:
if x % i != 0:
return True
return False
while this code is works fine:
def is_prime(x):
if x < 2:
return False
if x == 2:
return True
else:
for i in range(2, x):
if x > 2:
if x % i == 0:
return False
return True
Your second function is correct because it returns False if in any loop x % i == 0. Otherwise, it returns True. This is the definition of a prime number.
Your first function is incorrect because it returns True if in any loop x % i != 0. Otherwise, it returns False. The problem with this is that for all integers k > 2 there exists an integer i in range [2, k) such that k % i does not equal 0. Trivially, you can set i = k - 1. So the function will always return True.

Largest prime factor-Python

I'm trying to find the largest prime factor of a given number (600851475143) using Python. I've made the following code, but I don't know what is wrong and whether I am using right code Please help find my mistake and improve it.
import math
def t(x):
l=[]
for i in range(1,int(math.sqrt(x))):
if x%i==0:
l.append(i)
return l
def check(y):
for i in range(2,1+y/2):
if y%i==0:
return 'this is not prime'
return 'ya'
print t(600851475143)
print check(486847)
You need to check that everything you're adding to the list is actually a prime
for i in range(1,int(math.sqrt(x))):
if (x % i) != 0:
continue
if check(i):
l.append(i)
Then, pop the last (largest) element of the list:
return l.pop()
You can also check up to the square root:
def check(y):
for i in range(2,int(math.sqrt(y))):
if (y % i) == 0:
return False
return True
Here's a slightly modified version that iterates backwards (as suggested by pzp), and returns as soon as a prime is found:
#!/usr/bin/env python
import math
def t(x):
for i in xrange(int(math.sqrt(x)), 1, -1):
if (x % i) != 0:
continue
if check(i):
return i
return None
def check(y):
for i in range(2, int(math.sqrt(y))):
if (y % i) == 0:
return False
return True
print t(600851475143)
print check(6857)
You're pretty close. Your check() is returning before you want it to. You want:
def check(y):
for i in range(2,1+y/2):
if y%i==0:
return 'this is not prime'
return 'ya'
This will wait until you've check all the numbers < y before returning false. Right now, it checks 2, then returns either true or false.
Also t() is returning all factors, rather than the greatest factor. For just the greatest factor (assuming there is one), you want return l[-1]
EDIT:
Ok, I think I get what you're going for. By using this t() and check(), you can get the largest prime by with:
def t(x):
l=[]
for i in range(1,int(math.sqrt(x))):
if x%i==0:
l.append(i)
return l
#Notice, return list of all factors
def check(y):
for i in range(2,1+y/2):
if y%i==0:
return False
return True
number_to_check = 92873465
prime_factors = []
for factor in t(number_to_check): # Iterate through factors returned from t()
if check(factor):
prime_factors.append(factor)
print "Largest Prime Factor: " + prime_factors[-1]

Trying to check a condition for every element in a list of integers

I'm trying to define a method to check whether or not every element of a list is a factor of the parameter.
Here's what I have:
def factorall(x):
if all(x % num for num in nums) == 0:
return True
else:
return False
(In this case nums is a list of the integers from 1 to 10)
However, this returns true for any number. I'm assuming this happens because it is only checking 1 and then returning True, but shouldn't all() be checking for every element of the list before returning True?
I'm a bit unfamiliar with all() so I probably implemented it incorrectly. Can someone point me in the right direction?
Thanks!
you should use not any instead of all
def factorall(x):
return not any(x%num for num in nums) #if any of these is a value other than 0
or if you want it like you currently have it
def factorall(x):
return all(x%num==0 for num in nums)
You should do the comparison inside the all function, or simply remove it, and use negation of the result x % num:
def factorall(x):
return all(not x % num for num in nums)
The return statement works same as:
return all(x % num == 0 for num in nums)
I agree that the 2nd one seems clearer.
def factorall(x):
if all(x % num == 0 for num in nums):
return True
else:
return False

Categories