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.")
Related
#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'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)
Trying to write a function 'prime_check(number)' to test if an argument is a prime number
The number_of_factors for a given number should only be 1 (the given number itself) and '1', which is already excluded in the while statement
Having trouble adding a variable to the list "set_of_factors"
Tried to debug in Thonny, which says that set_of_factors = none
def prime_checker(number):
set_of_factors=[]
number_of_factors=len(set_of_factors)
f=2
while number > 1 and f<=number:
if number%f == 0:
set_of_factors.insert(0,1)
f+=1
else:
f+=1
if number_of_factors==1:
print("It is a prime number")
else:
print("It is not a prime number")
n = int(input("Check this number: "))
prime_checker(number=n)
Prime numbers have two factors, one and itself. Ex. 5's factors would be (1, 5)
Also istead if ".insert" use ".append"
def prime_checker(number):
set_of_factors=[]
number_of_factors=len(set_of_factors)
f=2
while number > 1 and f<=number:
if number%f == 0:
set_of_factors.insert(0)
f+=1
else:
f+=1
if number_of_factors==2:
print("It is a prime number")
else:
print("It is not a prime number")
Let's say we want to look at range(2,10).
I have written the following code:
for n in range(2,10):
for x in range(2,n):
if n%x == 0:
print(n,'equals',x,'*',n//x)
break
else:
print(n, "is a prime number")
The above way can do checking correctly but it also returns one factor.
But if I replace break to continue:
for n in range(2,10):
for x in range(2,n):
if n%x == 0:
print(n,'equals',x,'*',n//x)
continue
else:
print(n, "is a prime number")
It couldn't do the checking correctly anymore. So is there any better way to get both checking and all factors correctly?
Your answer will be of great help to me!!
Do not use either break or continue, but make and use a bool variable prime as follows.
for n in range(2,10):
prime = True
for x in range(2, n):
if n%x == 0:
print(n,'equals',x,'*',n//x)
prime = False
if prime:
print(n, "is a prime number")
def prime_checker(num):
if num <=1:
print('Not Prime')
elif num == 2:
print('Prime')
else:
for i in (2, (num ** (1/2))):
if num%i == 0:
print('Not Prime')
break
else:
print('Prime')
break
I am super new to coding, just learning the basics. I based it off of the primality test I found on Wikipedia.
I think it works. It might be cumbersome, but it seems to work.
The iterator for your for loop should be a range of integers, not just a tuple of 2 and the square root the number. When using range, be sure to convert the bounds to integers with int first. And it's only considered a prime number if the number cannot be divided by any of the numbers in the loop, so you should declare a prime number only after the loop finishes, or otherwise the loop should declare "not prime" and returns.
def prime_checker(num):
if num <=1:
print('Not Prime')
elif num == 2:
print('Prime')
else:
for i in range(2, int(num ** (1/2)) + 1):
if num%i == 0:
print('Not Prime')
return
print('Prime')
prime_checker(63)
prime_checker(31)
prime_checker(9)
This outputs:
Not Prime
Prime
Not Prime
Your logic is good, however you could have used sqrt for root square,
also the range function will raise a TypeError if you supply a float parameter (which is usually the case when working with root square).
A working implementation would be:
from math import sqrt
def prime_checker(num):
is_prime = True
if num <= 1 or not isinstance(num, int):
is_prime = False
elif num == 2:
pass
else:
for i in range(2, int(sqrt(num)) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print('Prime')
else:
print('Not Prime')
I think I got it to work not as a function.
from math import sqrt
print('This script will check if your input is a prime number.')
num = int(input('Number: '))
if num <=1:
print('Not Prime')
elif num == 2 or num ==3:
print('Prime')
else:
for i in range(2, int(sqrt(num)) + 1):
if num%i == 0:
a = 'Not Prime'
break
else:
a = 'Prime'
print(a)