Function that checks primality correction? - python

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 :).

Related

I've written a code to check if a number is prime, but doesnt work [duplicate]

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

Check prime number

def isPrime(n):
if n>1:
for i in range(2,n):
if (n % i==0):
return False
else:
return True
else:
return False
This code worked in most cases, but when input n=133, it returned True as output. Please show me the error.
Please note that your code could return True in the first iteration of the loop, you need to check for the other values.
Let's see how your loop works.
For value such as 3 your loop will have n%i check i.e. 3%2 which won't satisfy the condition. So it will return true.
But for value such as 9. Loop will check 9%2=0 which again doesn't satisfy the condition and returns True.
So use something like.
def isPrime(n):
if n>1:
for i in range(2,n):
if (n % i==0):
return False
else:
x=False
return x;
else:
return False
So I ran this and it seems this function will return True for any odd number because it returns false on the first iteration, which is checking if it's divisible by 2. Overall, your function is pretty much wrong, here is how I would approach it.
def isPrime(n):
div = True
for i in range(2,int(n**0.5)):
if n%i==0:
div = False
break
return div
Here what I did was I only checked prime factors upto the square root of the number (because if a number has a prime factor greater than its square root(but not the number itself), it must also have a prime factor less than its square root, so we do not need to check further), and I exited from the loop whenever even once it was divisible by something. I checked and it's working correctly.
The problem with your loop is that when you are iterating through the for loop, it always returning either True or False. To prevent that, what you should create a counter which changes its value accordingly.
def PrimeChecker(n):
if n < 1:
return f'{n} is less than 1. So, not prime' # You can add this if you
# want.
else:
for i in range(2, n): # The main loop
counter = True # The counter
if n % i == 0: # If it becomes divisible....
counter = False # Counter becomes false.
break # Break out of loop
return counter # Return False or True
Hope that helped :)
Most efficient Primechecker program :)
from math import sqrt
def checkprime(x):
if x > 2 and x % 2 == 0:
return False
elif x < 2:
return False
else:
for i in range(2, int(sqrt(x)) + 1):
if x % i == 0:
return False
return True
return False

Why is my prime number function not working?

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

Python prime checker faulty with 25?

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)):

Python function, odd, that takes in one number and returns True

Here is condition.
Write a Python function, odd, that takes in one number and returns True when the number is odd and False otherwise.
Condition is x: int or float.
and returns: True if x is odd, Falae otherwise
My code is
def odd(x):
while x % 2 != 0:
return (x % 2 == 1)
When if odd(62) above code is works, but odd(62) output is None. How can I correct False answer?
Please Help me.
Your function doesn't return anything if the number is not odd. You don't need a while loop at all:
>>> def odd(x):
... return x % 2 != 0
...
>>> odd(62)
False
>>> odd(63)
True
Also see other ways to check if the number is odd or not:
How to determine if an integer is even or odd
You don't want to use a while loop, a simple if will do it. The reason you get none is because the while loop doesn't run in the "even" condition so there is no return.
An even simpler way of writing it is to return the condition itself:
def odd(x):
return x % 2 == 1
The while loop is messing it up.
def odd(x):
return x % 2 == 1
return (x % 2 != 0)
This will return a boolean value; evaluates True if number is odd and False otherwise.
def odd(x):
'''
x: int
returns: True if x is odd, False otherwise
'''
while x%2 != 0:
return True
else:
return False

Categories

Resources