Checking if a number is prime - python

I'm trying to write a program in python that checks if a number is prime.
def isPrime(x):
for i in range(2, int(x/2)+1):
if (x%i) == 0:
return False
break
else:
return True
if x == 2:
return True
x = int(input("Enter an number: "))
prime = isPrime(x)
if prime:
print(f"{x} is a prime number.")
else:
print(f"{x} is not a prime number.")
The program works for most numbers. However it also recognises 27 as a prime number (which isn't true: 3x9=27).

The issue is with the lines
else:
return True
It only checks if the given number is divisible by 2, if it is not, it immediately declares the number as a prime number. Removing those lines and rearranging a little should do the trick. You also have to add a return True at the end (Thanks Andrew).
def isPrime(x):
for i in range(2, int(x/2)+1):
if (x%i) == 0:
return False
break
if x == 2:
return True
return True
x = int(input("Enter an number: "))
prime = isPrime(x)
if prime:
print(f"{x} is a prime number.")
else:
print(f"{x} is not a prime number.")

Close; here is the fixed code. (There are better ways to do this, but this way works):
def isPrime(x):
if x < 2:
return False
for i in range(2, x):
#print("testing %d against %d..." % (x, i))
if (x%i) == 0:
return False
return True
x = int(input("Enter an number: "))
if isPrime(x):
print("%d is a prime number." % x)
else:
print("%d is not a prime number." % x)

Related

opposite return of the function

I am doing some Python exercisses and for some reason my fucntion is returning to me opposite bool value. If statement under the function need to has "not" to work properly - can anyone explain me what am I doing wrong?
number = int(input("Enter numbers you want to check: "))
def dividers(number):
temp_tab = range(2, number)
divider = 0
for x in temp_tab:
while number % x == 0:
divider += 1
if divider > 1:
return False
else:
return True
if not dividers(number):
print("It is a prime number")
else:
print("It is not a prime number")
It seems like you want a function to check if a number is prime:
def is_prime(number):
if number <= 1: return False
for x in range(2, number):
if number % x == 0:
return False
return True
number = int(input("Enter numbers you want to check: "))
if is_prime(number):
print("It is a prime number")
else:
print("It is not a prime number")

Prime number in Python

#Write your code below this line ๐Ÿ‘‡
def prime_checker(number):
for num in range (2, number):
if num % number == 0:
print("It is not a prime number")
else:
print("It is a prime number")
#Write your code above this line ๐Ÿ‘†
#Do NOT change any of the code below๐Ÿ‘‡
n = int(input("Check this number: "))
prime_checker(number=n)
How can I print a text that number is prime or not only once?
Fix
number % num == 0 and not num % number == 0
A number isn't prime the moment you find a number that doesn't divide it, but only when you have tested all and none divides it
Use for/else construction, it goes into else if no break has been used
def prime_checker(number):
for num in range(2, number):
if number % num == 0:
print("It is not a prime number")
break
else:
print("It is a prime number")
Note that this only fixes your way to do, but that isn't the optimal way to check if a numbre is a prime one, at least, ending range at square root of number, and directly verifying division by small numbers like 2,3,5,7
There are few mistakes in your code. I have modified them.
def prime_checker(number):
for num in range(2, number):
if number % num == 0:
print('Not prime')
return
print('Prime number')
# Write your code above this line ๐Ÿ‘†
# Do NOT change any of the code below๐Ÿ‘‡
n = int(input("Check this number: "))
prime_checker(number=n)
For loop is to check if any of the number starting from 2 is a factor of number or not.
First, a slightly more efficient prime check by
going until the sqrt of the number only
going in steps of 2
import math
def is_prime(n: int) -> bool:
if n in (2, 3, 5):
return True
if n < 2 or n % 2 == 0:
return False
for i in range(3, math.ceil(math.sqrt(n)), 2):
if n % i == 0:
return False
return True
Now you can wrap that function in yours
def prime_checker(n: int):
msg = "%d is prime" if is_prime(n) else "%d is not prime"
print(msg % n)
prime_checker(11)
# 11 is prime
I think it's good to check a number is prime or not
def is_prime(n):
st = "prime" # being prime status
for i in range(2,n):
if n % i == 0: # if number is prime
st = "not prime"
break;
return st
n = int(input("enter n: "))
print (is_prime(n))
You only need to change the end of your code
your function is true except for these lines:
if num % number == 0:
print("It is not a prime number")
else:
print("It is a prime number")
you should change these to:
st = "Prime"
if number % num == 0:
st = "not prime"
return st

I am getting incorrect output from prime number script

Getting wrong output from this script.
#!/usr/bin/python
numbers = [1,3,5,7,8,25]
def primes():
for i in numbers:
if i > 1:
if (i % 2) == 0:
print "not prime"
else :
print "prime"
print primes()
its saying 25 is prime, any idea why ?
Your program is checking if numbers are odd, not if they're prime.
This is the validation you want (from this page)
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
import math
numbers = [1,3,5,7,8,25]
def primes(n):
if n == 2:
return True
if n%2 == 0 or n <= 1:
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2):
if n%divisor == 0:
return False
return True
for i in numbers:
print i, '\t', primes(i)
Your code will just check for odd or even number. Not for prime number.

prime number python for loops

Question:
A program that take a positive integer n as input and returns True if n is a prime number, otherwise returns False.
My Answer:
n = int(input("Enter a number: "))
for i in range(2,n):
if n%i == 0:
print(False)
print(True)
when I enter a prime number it works but when I enter a non prime number it doesn't work.
Example:
>>>
Enter a number: 12
False
False
False
False
True
>>>
please help!
You can break and use else:
n = int(input("Enter a number: "))
for i in range(2, n):
if n % i == 0:
print(False)
break
else:
print(True)
True will only be printed if the loop completes fully i.e no n % i was equal to 0.
Your code always prints True at the end, and prints a number of Falses before that. Instead, you should have a variable (isPrime?) that gets initialized to True and gets set to False when you find it is divisible by something. Then print that variable at the end.
You're just printing each intermediate value, if you use return in a function it works fine
def prime(n):
for i in range(2, n):
if n%i == 0:
return False
return True
>>> prime(5)
True
>>> prime(12)
False
You could use the for-else clause here. Also, you don't need to go beyond the square root of n:
import math
for i in range(2, int(math.sqrt(n))):
if n % i == 0:
print "False"
break
else:
print "True"
There's a lot of different ways to fix your code, but all of them hinge on the fact that you should be breaking out of that loop if you find a divisor (ie if n%i == 0)
Usually, you'd have a boolean value storing whether or not you've found a divisor, but python lets you do the following
n = int(input("Enter a number: "))
for i in range(2,n):
if n%i == 0:
print(False)
break
else:
#else statement only happens if you don't break out of the loop
print(True)
Check out the algorithm here:
http://www.programiz.com/python-programming/examples/prime-number
# Python program to check if the input number is prime or not
# take input from the user
num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
If you encounter an i which gives modulo zero with n, then you have to print False and then do nothing. For this you can use a flag variable which takes care of this condition. If no such i is encountered, flag remains 1 and True is printed.
n = int(input("Enter a number: "))
flag = 1
for i in range(2,n):
if n%i == 0:
print(False)
flag = 0
break
if flag:
print(True)
check this one, it should make clear why the else statement is indented 'non conventionally':
num = int(input('Enter the maximum value: '))
for number in range(3, num+1):
#not_prime = False
for factor in range(2, number):
if number%factor == 0:
#not_prime = True
break
#if not_prime:
#continue
else:
print(number)
All of the above things are correct but I want to add thing that you should check for the condition of 1. if someone puts 1 as an integer you will have to return False. 1 is not prime
def prime_num(num):
if num <= 0:
return "the number is not primary"
for i in range(2, num - 1):
if num % i == 0:
return "The number is not primary, it can be divided: " + str(i)
return "The number: " + str(num) + " is primary"
This is one of the many ways to solve it:
def is_prime(num):
if (num == 2):
return True
elif any(x for x in range(2, num - 1) if (num % x == 0)):
return False
else:
return True

Python prime function problems

I am very new to python; I only started two days ago. After looking at some designs online, i tried to use this function to determine if a number is prime:
def isprime(n):
if n == 1:
print("1 is not a prime.")
if n == 2:
print("2 is a prime number.")
for x in range(2, int(n)):
if n%x == 0:
print(n, "is a composite number.")
break
else:
print(n, "is a prime number.")
break
isprime(int(input("Enter a number.")))
The isprime(int(input("Enter a number."))) is so I can run the file as an .py.
However, while it runs without any errors, it returns false positives. For example, it states that 45 is a prime number. What did i do wrong?
You're aborting iteration of your for x in range loop after the first iteration, because both branches of your if-statement contain a break.
Remove the else-branch and use a for...else construct:
def isprime(n):
if n == 1:
print("1 is not a prime.")
if n == 2:
print("2 is a prime number.")
for x in range(2, int(n)):
if n%x == 0:
print(n, "is a composite number.")
break
else:
print(n, "is a prime number.")
The problem is in the logic of your code. Indentation plays an important role in Python. The code works good if it is changed like this:
def isprime(n):
if n == 1:
print("1 is not a prime.")
if n == 2:
print("2 is a prime number.")
prime = True
for x in range(2, int(n)):
if n%x == 0:
print(n, "is a composite number.")
prime = False
break
if prime:
print(n, "is a prime number.")

Categories