So I'm relatively new to Python and trying to define a function which will check to see if a number is prime or not. The code is as follows:
def prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for i in range(3, int((x**0.5)+1)):
if x % i == 0:
return False
else:
return True
This seems to work for most values however it fails on certain values such as 25, can anyone help to explain to me why? Thanks!
return leaves your function once it is reached. Let's look at the case of 25.
Is x<2 no, so continue.
Is it x==2 no, so continue.
Is x divisible by i(=3)? No, so go to the else clause, return True leave the function.
See the issue?
To put it another way, for sufficiently large x, your function is equivalent to:
def prime_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
if x % 3 == 0:
return False
else:
return True
It's the
else:
clause, the first i it checks will make it return true.
Instead, write
else:
for i in range(3, int((x**0.5)+1)):
if x % i == 0:
return False
return True
EDIT:
And as #mata points out, you actually need to start at 2, so it should be for i in range(2, int((x**0.5)+1)):
Related
For context, I am trying to solve Project Euler problem 3 using Python:
What is the largest prime factor of the number 600851475143?
As a first step to this, I am trying to write a function that returns whether or not a number is prime as a Boolean. I made a first attempt, and checked out how this has been written previously. I have ended up with the following code:
def isprime(x):
limit = x**0.5
i = 2
if x < 2:
return False
elif x == 2:
return True
else:
while i <= limit:
if x%i == 0:
return False
i = i + 1
else:
return True
For some reason, the code above does not work perfectly. For example, isprime(99) would return True.
Please, can someone help me understand why this isn't working? I am trying to avoid just copying and pasting someone else's code, as I want to understand exactly what is going on here.
To me, it looks like the issue is with the final else statement. I say this because the logic reads "in the event that x%i == 0, this number is not prime" but it doesn't explicitly say what to do in the event that no x%i iterations == 0.
Any help on this would be appreciated! I'm not necessarily looking for the cleanest, neatest way of doing this, but more just trying to first make this code work.
Just to show an alternative, what you could do is checking from number 2 to your number if the operation (x % i) is equal to zero. If it never happend, it will be a prime.
def isprime(x):
# check for factors
for i in range(2,x):
if (x % i) == 0:
return False
else:
return True
print(isprime(99))
Try this :
def isprime(x):
limit = x**0.5
i = 2
if x <= 2:
return False
while i <= limit:
if x%i == 0:
return False
i = i + 1
return True
I've changed many things. have this point in your mind that there is no need to else clauses when you return at the end of if block.
you need to tell what happens when x%i==0 condition not met and the value of i remain constant and also need to see when all conditions not met, then it is a prime
# your code goes here
def isprime(x):
limit = x**0.5
i = 2
if x < 2:
return False
elif x == 2:
return True
else:
while i <= limit:
if x%i == 0:
return False
i+=1
return True
print(isprime(144)) # false
print(isprime(99)) # false
print(isprime(131)) # true
I am new to programming and I face an issue while trying to write a program in finding out prime number. Here is my code:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range (2,x-1):
if x % n == 0:
return False
else:
return True
I received an error stating "Your function fails on is_prime(3). It returns None when it should return True."
Can someone please explain the flaw in this code?
Thank you!
range() has an exclusive upper bound, so it's trying to get the range between 2 and 2 (3 - 1), which is no elements. Since you can't iterate over nothing, the for loop never runs, so None is returned (this is the default return type of a function if none is specified).
The solution to your immediate problem would be to use range(2, x) rather than range(2, x - 1). You'll find that you'll have problems at x > 3 though because as #khelwood said, you're returning True or False immediately after checking the first value. Instead, only return True after checking all values in the range.
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range (2,x): # range function will iterate till x-1
if x % n == 0:
return False
# return true only at the end after making sure it is not divisible by any number in the middle
return True
I've been plugging away on the Codecademy python course and I had a solution that worked. However, during the verification process, I added an extra bit of code that would print the current state the for loop is in. When I execute the code, however, it seems to go through one iteration before quitting, which I know is not the case. The following is my code:
def is_prime(x):
if x < 2:
return False
if x == 2:
return True
if x == 3:
return True
else:
for n in range(2,x-1):
if x % n == 0:
print "Current value is %d." %n
return False
return True
How can I make it print a value each "n" value when the number is going through the loop?
Your issue is that you are only printing when x % n == 0 , and then right away you are returning 'False' , hence its only printing once.
You need to move the print statement to just below for loop , something like -
def is_prime(x):
if x < 2:
return False
if x == 2:
return True
if x == 3:
return True
else:
for n in range(2,x-1):
print "Current value is %d." %n
if x % n == 0:
return False
return True
Try this one. I'm using Fermat's little theorem :
def is_prime(x):
if x > 1 and ((2)**x-(2))%x == 0:
return True
return False
def is_prime(x):
if x < 2:
return False
else:
for n in range(2,x - 1):
if x % n == 0:
return False
return True
I started getting back to python coding and realized I couldn't quite figure this out. I'm trying to code a prime number function. Could someone help with this?
Here is my code:
def is_prime(x):
a = True
for n in range(2, x-1):
while n < x:
n+=1
if x % n == 0:
a = False
elif n < 2:
a = False
else:
a = True
break
break
return a
If anyone has an idea on what I'm doing wrong, please let me know. A month ago I tried this and couldn't get the logic down. I think I was stumped and didn't ever ask for help... Also, how long do you think I should try to do this for before I ask for help on average?
As, it has been said, you can optimize the code by just checking the odd numbers and iterating upto the sqrt of the num
import math
def isPrime(num):
if(num==1):
return False
if(num==2):
return True
if(num%2==0):
return False
i = 3
while(i<math.sqrt(num)+1):
if num%i==0:
return False
i += 2
return True
#do the inputs and check if isPrime
#print(isPrime(2))
using your code, and focusing on code structure:
def is_prime(x):
# function contents must be indented
if x == 0:
return False
elif x == 1:
return False
# your base cases need to check X, not n, and move them out of the loop
elif x == 2:
return True
for n in range(3, x-1):
if x % n == 0:
return False
# only return true once you've checked ALL the numbers(for loop done)
return True
adding some optimizations:
def is_prime(x):
if x <= 1:
return False
if x == 2:
return True
for n in range(3, x**(0.5)+1, 2): # this skips even numbers and only checks up to sqrt(x)
if x % n == 0:
return False
return True
def prime(number):
for i in range(2,number,1):
if number % i == 0:
return False
return True
entry = int(input("Please enter the number: "))
while True:
if prime(entry):
print ("It's a prime number. ")
continue
else:
print ("It's not a prime number.. ")
continue
You will entry a number then this function will give you if its a prime or not. Check the function it will solve your problem.
ALSO You can upgrade the speed of your program. You know prime numbers can not be even, so you you dont have to check even numbers
like 4-6-8-26. So in the range function, which is (2,number) add "2"
end of it. like (3,number,2) then program will not check even numbers.
ALSO a factor can not be bigger than that numbers square root. So you dont have to check all of numbers till your main number, its
enough to check your numbers square root. like: (2,number**0.5) that
means from 2 to your number square root. So double up for program
speed.
So the function will be:
def prime(number):
for i in range(3,(number**0.5)+1),2):
if number % i == 0:
return False
return True
The first function enough for you actually. I am working with huge numbers, so I have to upgrade the speed of my program.
def is_prime(x):
for n in range(2, x-1):
if n == 0:
return False
elif n == 1:
return False
elif n == 2:
return True
elif x % n == 0:
return False
else:
return True
What you are doing wrong is , the first three if elif blocks are executed every time in the loop. So, they should be outside the for loop. Also.
if x%n==0:
return True
It is fine. But the later
else:
return True
is wrong because whenever the first n does not divide the x, it will return Composite. So,
return True
block must be outside the for loop.
Other optimizations can be done by yourself.
This is how I solved it
def is_prime(n):
if n==1:
print("It's not a Prime number")
for z in range(2,int(n/2)):
if n%z==0:
print("It's not a Prime number")
break
else:
print("It's a prime number")
or if you want to return a boolean value
def is_prime(n):
if n==1:
return False
for z in range(2,int(n/2)):
if n%z==0:
return False
break
else:
return True
Function that checks if input is prime.
I know it has been covered many times here, but my code for some reason gives me True for x=32 and I cant figure out why
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for i in range(3,x): #Ignore sqrt(x) improvement
if x%i == 0:
return False
else :
return True
for i in range(3,x):
This first goes with the number 3. As 32 % 3 != 0, it returns True. Then the function breaks because it has returned a value.
Consider putting return True after the for-loop:
for i in range(3,x): #Ignore sqrt(x) improvement
if x % i == 0:
return False
return True
Now if a number is divisible, it will immediately break and return False. But if no numbers go into 32, the for-loop will finish, and it will return True.
Also, if you are using python 2.x, it will be faster to use xrange(), as that returns a generator :).