Check prime number - python

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

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

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

how to find a prime number function in python

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

python check prime, stuck at one point

This was the question our teacher gave us:
"One way to determine whether or not a number is a prime number is as follows:
if the number < 2, then return False
if the number is 2, then return True
for each value of i, where i >=2 and i < number:
if i divides the number evenly, then return False
return True"
I've managed to work through most of it, but was stuck when it said 'for each value of i, where i >=2 and i < number:'
how do I write this in code?
if number < 2:
return False
if number == 2:
return True
?????????
if i%2 == 0:
return False
return True
Yo need a loop to check all numbers from 2 to one less than the number being checked. There are better ways to do it (such as only checking up to the square root of the number) but a simplistic algorithm would be:
def isPrime (n):
if n < 2:
return False
for x in range (2, n):
if n % x == 0:
return False
return True
So, in terms of what you need to add to your code:
a loop iterating some variable from two up to one less than the number.
checking modulo with that variable rather than the hard-coded 2.
You will need to start a loop from 2 to the number
for i in range(2,number)
if number%i == 0:
return false
def isprime(num):
#this is the part you are missing
for divider in range(2,num):
if num%divider == 0:
return False
#end of missing part
return not num%2 == 0 or num==2 or num==0
for i in range(0,200):
if isprime(i): print i, isprime(i)

Function that checks primality correction?

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

Categories

Resources