Does this code make sense? Prime numbers in Python - python

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)

Related

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

Python - Prime check and increment

My objective of the below code is
check if entered number is a prime
if not print the next biggest prime
def primetest (num):
for c in range (2, num):
if num % c == 0:
repeattest (num) #not prime? increment number
else :
print (num,"is a prime number")
break
def repeattest (num): # check prime if not increment number by 1
for z in range (2, num):
num = num+1
primetest (num)
if num % z == 0:
num = num+1
else:
print ("Next Prime:", num+1)
break
num = int (input ("enter a number:")) # main code:
for y in range (2, num):
if num % y == 0:
repeattest (num)
else:
print (num,"is a prime number")
break
I think the logic is fine, but not sure why im not getting any output.
Time comlexity of your code is O(N) when it find a number which is prime or not.
There is no pointing on dividing from 2 to len(num)-1. It is enough to loop from 2 to sqrt of the given number. Therefore time complexity reduce to O(n) to O(log(n)).
import math
num = int (input ("enter a number:"))
def primeTest(num):
isPrime = 0
for i in range(2,int(math.sqrt(num)+1)):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print(num, "is a prime number")
else:
num = num + 1
repeatTest(num)
def repeatTest (num):
isPrime = 0
for i in range(2,int(math.sqrt(num))):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print("Next Prime: ", num)
else:
num = num + 1
repeatTest(num)
primeTest(num)
The logic which you are using to find if a number if prime seems wrong .
Taking a integer like 9 prints "9 is a prime number" .
And also you are checking for next prime numbers from 2 to Num .
Num being the input , you cant get a number greater than that .
It exits from the loop without even getting in , therefore not printing anything when you are searching for next prime .
You need to change the logic .
write a separate function for checking prime and end the loop when you find the next prime number instead of stopping at num .

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