prime number python for loops - python

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

Related

Why does using for loop for finding prime number runs only runs once?

I want to find the prime numbers up to the given number but my loop only runs once and my output is only 2 and 3, where did I went wrong?
def primer_check(n):
prime_state = True
for i in range(2,n+1):
if i == 2:
print(2)
continue
for j in range(2,i):
if i % j == 0:
prime_state = False
break
if prime_state: print(i)
n = int(input("Enter a number to see the prime numbers up to that number : "))
primer_check(n)
you have to set prime_state to True everytime when you start a new loop.here is the code.you are almost correct .Hope it helps :)
def primer_check(n):
for i in range(2,n+1):
prime_state = True
if i == 2:
print(2)
continue
for j in range(2,i):
if i % j == 0:
prime_state = False
break
if prime_state: print(i)
n = int(input("Enter a number to see the prime numbers up to that number : "))
primer_check(n)

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

Checking if a number is prime

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)

Prime number check acts strange [duplicate]

This question already has answers here:
How to create the most compact mapping n โ†’ isprime(n) up to a limit N?
(29 answers)
Closed 7 years ago.
I have been trying to write a program that will take an imputed number, and check and see if it is a prime number. The code that I have made so far works perfectly if the number is in fact a prime number. If the number is not a prime number it acts strange. I was wondering if anyone could tell me what the issue is with the code.
a=2
num=13
while num > a :
if num%a==0 & a!=num:
print('not prime')
a=a+1
else:
print('prime')
a=(num)+1
The result given when 24 is imputed is:
not prime
not prime
not prime
prime
How would I fix the error with the reporting prime on every odd and not prime for every even?
You need to stop iterating once you know a number isn't prime. Add a break once you find prime to exit the while loop.
Making only minimal changes to your code to make it work:
a=2
num=13
while num > a :
if num%a==0 & a!=num:
print('not prime')
break
i += 1
else: # loop not exited via break
print('prime')
Your algorithm is equivalent to:
for a in range(a, num):
if a % num == 0:
print('not prime')
break
else: # loop not exited via break
print('prime')
If you throw it into a function you can dispense with break and for-else:
def is_prime(n):
for i in range(3, n):
if n % i == 0:
return False
return True
Even if you are going to brute-force for prime like this you only need to iterate up to the square root of n. Also, you can skip testing the even numbers after two.
With these suggestions:
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
Note that this code does not properly handle 0, 1, and negative numbers.
We make this simpler by using all with a generator expression to replace the for-loop.
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up
# the square root of n for all odd numbers
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return False
return True
Taken from:
http://www.daniweb.com/software-development/python/code/216880/check-if-a-number-is-a-prime-number-python
def is_prime(n):
return all(n%j for j in xrange(2, int(n**0.5)+1)) and n>1
The two main problems with your code are:
After designating a number not prime, you continue to check the rest of the divisors even though you already know it is not prime, which can lead to it printing "prime" after printing "not prime". Hint: use the `break' statement.
You designate a number prime before you have checked all the divisors you need to check, because you are printing "prime" inside the loop. So you get "prime" multiple times, once for each divisor that doesn't go evenly into the number being tested. Hint: use an else clause with the loop to print "prime" only if the loop exits without breaking.
A couple pretty significant inefficiencies:
You should keep track of the numbers you have already found that are prime and only divide by those. Why divide by 4 when you have already divided by 2? If a number is divisible by 4 it is also divisible by 2, so you would have already caught it and there is no need to divide by 4.
You need only to test up to the square root of the number being tested because any factor larger than that would need to be multiplied with a number smaller than that, and that would already have been tested by the time you get to the larger one.
This example is use reduce(), but slow it:
def makepnl(pnl, n):
for p in pnl:
if n % p == 0:
return pnl
pnl.append(n)
return pnl
def isprime(n):
return True if n == reduce(makepnl, range(3, n + 1, 2), [2])[-1] else False
for i in range(20):
print i, isprime(i)
It use Sieve Of Atkin, faster than above:
def atkin(limit):
if limit > 2:
yield 2
if limit > 3:
yield 3
import math
is_prime = [False] * (limit + 1)
for x in range(1,int(math.sqrt(limit))+1):
for y in range(1,int(math.sqrt(limit))+1):
n = 4*x**2 + y**2
if n<=limit and (n%12==1 or n%12==5):
# print "1st if"
is_prime[n] = not is_prime[n]
n = 3*x**2+y**2
if n<= limit and n%12==7:
# print "Second if"
is_prime[n] = not is_prime[n]
n = 3*x**2 - y**2
if x>y and n<=limit and n%12==11:
# print "third if"
is_prime[n] = not is_prime[n]
for n in range(5,int(math.sqrt(limit))):
if is_prime[n]:
for k in range(n**2,limit+1,n**2):
is_prime[k] = False
for n in range(5,limit):
if is_prime[n]: yield n
def isprime(n):
r = list(atkin(n+1))
if not r: return False
return True if n == r[-1] else False
for i in range(20):
print i, isprime(i)
Your problem is that the loop continues to run even thought you've "made up your mind" already. You should add the line break after a=a+1
After you determine that a number is composite (not prime), your work is done. You can exit the loop with break.
while num > a :
if num%a==0 & a!=num:
print('not prime')
break # not going to update a, going to quit instead
else:
print('prime')
a=(num)+1
Also, you might try and become more familiar with some constructs in Python. Your loop can be shortened to a one-liner that still reads well in my opinion.
any(num % a == 0 for a in range(2, num))
Begginer here, so please let me know if I am way of, but I'd do it like this:
def prime(n):
count = 0
for i in range(1, (n+1)):
if n % i == 0:
count += 1
if count > 2:
print "Not a prime"
else:
print "A prime"
This would do the job:
number=int(raw_input("Enter a number to see if its prime:"))
if number <= 1:
print "number is not prime"
else:
a=2
check = True
while a != number:
if number%a == 0:
print "Number is not prime"
check = False
break
a+=1
if check == True:
print "Number is prime"
a=input("Enter number:")
def isprime():
total=0
factors=(1,a)# The only factors of a number
pfactors=range(1,a+1) #considering all possible factors
if a==1 or a==0:# One and Zero are not prime numbers
print "%d is NOT prime"%a
elif a==2: # Two is the only even prime number
print "%d is prime"%a
elif a%2==0:#Any even number is not prime except two
print "%d is NOT prime"%a
else:#a number is prime if its multiples are 1 and itself
#The sum of the number that return zero moduli should be equal to the "only" factors
for number in pfactors:
if (a%number)==0:
total+=number
if total!=sum(factors):
print "%d is NOT prime"%a
else:
print "%d is prime"%a
isprime()
This is a slight variation in that it keeps track of the factors.
def prime(a):
list=[]
x=2
b=True
while x<a:
if a%x==0:
b=False
list.append(x)
x+=1
if b==False:
print "Not Prime"
print list
else:
print "Prime"
max=int(input("Find primes upto what numbers?"))
primeList=[]
for x in range(2,max+1):
isPrime=True
for y in range(2,int(x**0.5)+1) :
if x%y==0:
isPrime=False
break
if isPrime:
primeList.append(x)
print(primeList)
Prime number check.
def is_prime(x):
if x < 2:
return False
else:
if x == 2:
return True
else:
for i in range(2, x):
if x % i == 0:
return False
return True
x = int(raw_input("enter a prime number"))
print is_prime(x)
# is digit prime? we will see (Coder: Chikak)
def is_prime(x):
flag = False
if x < 2:
return False
else:
for count in range(2, x):
if x % count == 0:
flag = True
break
if flag == True:
return False
return True

Categories