The below code keeps displaying "is not prime" for a prime number and "is prime" for a number that is not prime. What am I doing wrong?
quuN = int(input("ENTER NUMBER : "))
quuM = 2
if (quuN <= 0) :
print("ENTER NON-NEGATIVE NUMBER PLEASE")
elif (quuN % quuM == 0) :
print(" IS PRIME " )
else :
print("IS NOT PRIME ")
The logic is incorrect
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number.
Simple python code below
def is_prime(n):
for i in range(3, n):
if n % i == 0:
return False
return True
The above code is checking if a number is even or odd. If you enter a prime number, for example 17, the code checks if 17 is less than or equal to 0. Then it checks 17%2 which evalutes to 1, and is not 0. Hence the else block is executed which prints IS NOT PRIME.
If you enter an even number, it prints IS PRIME.
This code checks for Prime numbers.
def is_prime(n):
import math
for i in range(2, int(math.sqrt(n))+1):
if n % i == 0:
return False
return True
I assume you're a beginner with python so let me point out the logic to check primality of numbers in your code is not correct, you should read first carefully the definition of primes numbers, when you do so, try to understand this little example which shows you how to check prime numbers:
import math
def is_prime_naive(number):
if number == 2:
return True
if number % 2 == 0:
return False
i = 3
sqrt_number = math.sqrt(number)
while i <= sqrt_number:
if number % i == 0:
return False
i = i+2
return True
for i in range(2,101):
print "{0} {1} prime".format(i,"is" if is_prime_naive(i) else "is not")
Now, be aware the above code is one of the simplest but also slowest way to check whether a number is prime or not. When you become familiar enough with the concept of primes then you should check for fastest way to check primality, some examples could be the Fermat and Miller Rabin primality tests. So, good luck with primes, you'll sure have fun with them ;-)
Here's the answer without using any libraries
Note: it's only needed to check until sqrt(n), explanation here
def isPrime(n):
if (n<=1): return False
for i in range(2, int(n**(.5))+1):
if (n%i==0):return False
return True
Related
Trying to write a program that checks if a number is prime.
Wrote the below code, but do not understand why do I have an output of 2 lines:
num = int(input("Provide number to check if prime: "))
if num <=1:
print("Invalid choice, try again")
num = int(input("Provide number to check if prime: "))
for i in range(2,num):
if num% i ==0:
print("Number is not prime")
break
if num %i !=0:
print("Number is prime")
My output is :
Provide number to check if prime: 15
Number is prime
Number is not prime
The sympy.isprime() is a built-in function under the SymPy module and can be utilized for checking of possible prime numbers. It is a direct function and returns True if the number to be checked is prime and False if the number is not prime.
>>> import simpy
>>> sympy.isprime(8)
False
>>> sympy.isprime(11)
True
or else define a function like this
>>> def isPrime(k):
# 1 is not prime number
if k==1:
return False
# 2, 3 are prime
if k==2 or k==3:
return True
# even numbers are not prime
if k%2==0:
return False
# check all numbers till square root of the number ,
# if the division results in remainder 0
# (skip 2 since we dont want to divide by even numbers)
for i in range(3, int(k**0.5)+1, 2):
if k%i==0:
return False
return True
>>> print(isPrime(13))
True
>>> print(isPrime(18))
False
As the first thing, you should remember that 1 isn't a prime number by definition, even if it can't be divided by any other number:
if (num == 1):
print("The number is NOT prime")
else:
for i in range(2, num):
if (num%i == 0): # If the number has a divisor
print("The number is NOT prime")
break
else: # If the for loop ends without reaching any break
print("The number IS prime")
The else branch of a for loop is reached when the loop ends without reaching any break AND the loop executes at least one time.
To better understand my answer, I would suggest to read this.
The error with your solution is caused by the loop printing that the number is prime for each time num%i == 0, so taking num = 6:
6%4 != 0 # The number is prime
6%5 != 0 # The number is prime
As Rajarshi Ghosh suggested, you should know that while programming it's a good idea to use imported functions to do this simple operations, in order to avoid long operations for such a simple job.
If you don't want to use an imported function, I would suggest you to read this article where they explained 6 ways of finding if a number is prime without using functions made by others.
You have issues in output, not only for the case of 15, but also for cases smaller than 1. The following code should work. It has two improvements.
It prints the correct output for 15. The key is to move the else block to align with the for loop.
It prints the correct output for any number smaller than 1, which is not prime. The key is to use the while-break method to get user enter right number until it is bigger than 1.
num = int(input("Provide number to check if prime: "))
while num <=1: #you need to use while loop
print("Invalid choice, try again")
num = int(input("Provide number to check if prime: "))
if num > 1: #only evaluate number is prime or not if it is greater than 1
for i in range(2,num):
if num% i ==0:
print("Number is not prime")
break
else: #to move the `else` block to align with the `for` loop.
print("Number is prime")
break #add a break here
Output:
What is a while loop?
A while loop tests the input condition. Every time the loop finishes, the condition is reevaluated (only evaluate number is prime or not if it is greater than 1). As long as the the number entered is <=1, the loop keeps executing (keep asking users for input).
If you want to just check whether a number is prime or not just do the following:
num = int(input("Provide number to check if prime: "))
flagNotPrime = False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flagNotPrime = True
break
if flagNotPrime:
print("Number is not prime")
else:
print("Number is prime")
Firstly, numbers that are <= 1 are not prime numbers. Therefore, the above code only proceeds if the num is greater than 1.
Secondly, the code checks if num is exactly divisible by any number from 2 to num - 1. If there is a factor in that range, the number is not prime, so the flag is set to True and the loop is broken using break.
Lastly, outside the loop, if the flag is True then num is not prime.
A prime number is a number that is only evenly divisible by itself and 1.
For example, the number 5 is prime because it can only be evenly divided by 1
and 5. The number 6, however, is not prime because it can be divided evenly
by 2 and 3.
Write a Boolean function named is_prime which takes an integer as an argument
and returns true if the argument is a prime number, or false otherwise. Use
the function in a program that prompts the user to enter a number and then
prints whether the number is prime.
This is the PYTHON code I have put in, but it tells me that it is wrong. I've tried but can't get it.
if num > 1:
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")
else:
print(num,"is not a prime number")
You almost got it. break in wrong place and can't have (and don't want/need) two else clauses:
if num > 1:
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")
You need to sort out the two else statements, and also change the algorithm so that it only prints num is a prime number if all the iterations of the for loop fail
if num < 2: # catch 1 and anything less than zero
print(num, "is not a prime number")
else:
prime = True
for i in range(2, num):
if num%i == 0:
print(num, "is not a prime number")
print(i,"times",num//i,"is",num)
prime = False
break
if prime:
print(num,"is a prime number")
I would put this in an isPrime function. You only need to check factors up to the square root of the number.
Edit: I see in your question you mentioned this, you just need to modify this code to return True or False
def isPrime(num):
if num < 2:
return False
for i in range(2,num):
if num%i==0:
return False
return True
Output
0 is not a prime number
1 is not a prime number
2 is a prime number
3 is a prime number
4 is not a prime number
2 times 2 is 4
5 is a prime number
6 is not a prime number
2 times 3 is 6
7 is a prime number
8 is not a prime number
2 times 4 is 8
9 is not a prime number
3 times 3 is 9
I took some time to develop a quick but accurate is_prime function in Python. Here it is:
from math import sqrt # you can just import math, but I only use sqrt
def is_prime(n):
if n<0:
n*=-1
if n<2:
return False
for i in range(2,int(sqrt(n))+1): # remember to fix sqrt to math.sqrt if you changed the
if n%i==0: # import to import math instead of from math import sqrt
return False
return True
Explanation:
If x is prime then -x is prime. So I just make the number positive with
if n<0:
n*=-1
0 is composite (it has the factors 1, 2, 3, 4, 5, ...) and 1 is neither, and neither of those are prime, and since n>-1 (because it was absolute valued) the condition n<2 will suffice.
if n<2:
return False
After that, I loop from 2 to int(math.sqrt(n))+1. That's just convert math.sqrt(n) into an int, and then add 1. The reason for math.sqrt is that n can only have factors until its square root (and also itself). The +1 is for keeping the range in bounds if the int() made it less than it was before.
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
return False
In the loop, I check if i (the loop counter) is divisible into n. If it is, that means n has a factor that isn't 1 (it started from 2) or itself (it ends at the square root of itself, and 1 is not an exception because that was fixed with the if n<2 condition). At that point, it returns False.
If n gets through all of those checks, it is prime.
This is my code:
a=int(input("Enter a number: "))
i=2
p=[]
while i<=a-1:
p.append(a%i)
i=i+1
if 0 not in list(p):
print(a, "is a prime")
else:
print(a, "is not a prime")
i mathematically find it difficult to compose a code to fill the line 4 in the below code
is_prime = True
for i in range(2,n):
if n%i == 0:
print("impossible")
print(is_prime)
i have been typing print(string) i.e
print("this is not possible")
in the blank and it output
true
what is the correct code to write. i want to believe it is a mathematics expression thing.i don't know the code to write after if.
If n is a prime number, then n%i == 0 will always be false in your loop. That's why the print in the 4th line is never called (you said it yourself, it's impossible). The true you are getting is from the print on the last line: you never update the value of is_prime, so it will always print True.
On the other hand, if what you want to know is if n is a prime number, you can do this:
is_prime = True
for i in range(2,n):
if n%i == 0:
is_prime = False
break
print(is_prime)
here i wrote it down for you, getting to mathematics what we know is any number is prime number if it can give a integer when it is divided by one or itself so now we can check if the number is divisible by any number in between
for example if your number is equal to 5 then we check if 5 gives an integer and leaves no remainder when divided by 2,3 and 4, you can program this algorithm as follows
x=8 #any number to check for
answer= "prime"
for i in range(1,x-1):
if(x%(i+1) == 0 ):
answer="non-prime"
print(answer)
The problem is that you are not reassigning is_prime to False when your if condition is passed. After print("impossible) you can simply add is_prime = False and follow that with a break statement to exit the for loop.
print(is_prime) will now return False.
You can also modify range(2, n) to range(2, n//2) (the // operator performs integer divison and leaves no remainder). This is because for any given number, you will only need to check half of numbers from 1 to n, as eventually you will start to encounter repeated numbers.
is_prime = True
for i in range(2, n //2):
if n % i == 0:
print("impossible")
is_prime = False
break
print(is_prime)
Edit print("impossible") to any of the following two approaches:
is_prime = False
or
not any([n%i==0 for i in range(2,n)])
from your code, the print statement is on the outer scope from the if condition. You woud try adding an else block. I have have included an example using your code. Hope it helps.
is_prime = True
n =10
for i in range(2,n):
print(i)
if n%i == 0:
print("impossible")
else:
print(is_prime)
Where can I put a print statement to print the final list but still retain the return, and are there any ways you can think of to improve this function. I wrote the function but am unsure as to its relative quality
def buildPrimeList ():
primeList = [1, 2]
possiblePrime = 3
print "To display all prime values less than or equal a number..."
x = raw_input("Enter a number higher then 3 ")
while (possiblePrime <= x):
divisor = 2
isPrime = True
while (divisor < possiblePrime and isPrime):
if (possiblePrime % divisor == 0):
isPrime = False
divisor = divisor + 1
if (isPrime):
primeList.append(possiblePrime)
possiblePrime = possiblePrime + 2
return primeList
buildPrimeList()
It's quite straight-forward to print result of a function:
print buildPrimeList()
Also I've noticed that you do not convert raw_input's result (which is string) to int:
x = int(raw_input("Enter a number higher then 3 "))
Another way to do the same thing in python might look like:
from itertools import count
def is_prime(n):
"""Checks if given number
n is prime or not."""
for i in xrange(2, n/2):
if n % i == 0:
return False
else:
return True
def prime_numbers():
"""Generator function which lazily
yields prime numbers one by one."""
for i in count(1):
if is_prime(i):
yield i
if __name__ == '__main__':
maxprime = int(raw_input("Enter a number:"))
for prime in prime_numbers():
if prime < maxprime:
print prime
else:
break
A number of python idioms and language features were used:
generator functions and iterators [1];
snake_case_method_naming [2];
docstrings [3];
if __name__ == '__main__': ... [4].
[1] http://www.ibm.com/developerworks/library/l-pycon/index.html
[2] PEP 8: Style Guide for Python Code
[3] http://www.learningpython.com/2010/01/08/introducing-docstrings/
[4] What does if __name__ == "__main__": do?
p.s. As jellybean and rpInt noted in their answers and comments there are a number of ways to speed things up. But most likely you shouldn't do that (unless you absolutely have to) as "Simple is better than complex" [5].
[5] PEP 20: The Zen of Python
You can print the list immediately before returning it.
As for the efficency of the algorithm, consider the sieve of erathostenes.
You can improve the function greatly by just taking every 2nd number and dividing by it.
First, 1 isn't a prime, you shouldn't use it in that way. The reason for this is the prime factorization, that is unique for every number, like 9 = 3*3. If you would add 1 to your prime pool, 9 = 3*3, 9 = 3*3*1, 9=3*3*1*1, every one is a valid prime factorization, but it isn't unique anymore for every number.
Second, you don't have to check the number with every natural number. If you think about the natural numbers, every second of them is even and divisable by 2. So, if a number is divisable by 4, it is per definition divisable by 2. You can reduce the amount of calculations you have to do by a factor of 2 if you use this property. Also, you seem to use a technique called "The Sieve of Erastothenes" http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes which just adds prime numbers to the pool, and checks if the next natural number is divisable by any of them. You can exploit that easily.
def buildPrimeList ():
#One is not really a prime, so we cut it out.
primeList = [2]
possiblePrime = 3
print "To display all prime values less than or equal a number..."
upperlimit = raw_input("Enter a number higher then 3 ")
try:
upperlimit = int(upperlimit)
except:
print "Sorry. You didn't enter a number."
return
while (possiblePrime <= upperlimit):
#lets check if the possible prime is divisable by any prime we already know.
isPrime = True
for prime in primeList:
if(possiblePrime % prime == 0):
#we can abort the check here, since we know already that this number can't be a prime
isPrime = False
break
if (isPrime):
primeList.append(possiblePrime)
possiblePrime = possiblePrime + 2
return primeList
print buildPrimeList()
This should work as expected.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Simple Prime Generator in Python
First I will prompt user to input any number. Then my code will check whether does the number input by the user is a Prime number not.
Here is my codes:
num = int(raw_input("Input any of the number you like:"))
for x in range(2, int(num**0.5)+1):
if num % x == 0:
print "It is not a prime number"
else:
print "It is a prime number"
But question is I cant seem to get the output for 2 and 3. And when I randomly input any numbers like 134245, the system will output alot of sentences. And I do not know why?
Appreciate any kind souls to help me up :)
import urllib
tmpl = 'http://www.wolframalpha.com/input/?i=is+%d+a+prime+number'
def is_prime(n):
return ('is a prime number' in urllib.urlopen(tmpl % (n,)).read())
you should stop once num % x == 0 is true (no need for further testing) and print 'it is a prime number' only if the loop completed without anything printed before.
A number is prime if it only divides by 1 and itself. A pseudocode follows:
boolean prime = true;
for (int i = 2; i * i <= num; i++)
if (num % i == 0) {
prime = false;
break;
}
if (prime)
println("It is prime!");
else
println("It is not prime!");
Look at your code like this:
num = ...
for x in range(2, int(num**0.5)+1):
print something
The body of the loop is executed at every iteration. That means you're printing something at every iteration, i.e. for each x that you check to see if it's a factor of num, you print. That's not what you should be doing; in order to determine whether a number is prime, you check all possible factors first, then print your result. So you shouldn't be printing anything until after the loop.
But question is I cant seem to get the output for 2 and 3.
You're looping from 2 to ceil(sqrt(n)). For 2 and 3, this is an empty range, hence no iteration happens. Either special-case it or rewrite the code such that it assumes that n is prime and tries to disprove it in the loop.
the system will output alot of sentences.
You're printing on every iteration. Instead, use a boolean flag (or a premature return, if you factor it out into a function) to determine prime-ness and print once, after the loop, based on that prime.
Your code is not structured well-- the algorithm continues to loop all the way up to the top of your range, even if you already know that the number is composite, and it also prints some result on each iteration when it should not.
You could put the logic into a function and return True or False for prime-ness. Then you could just check the result of the function in your if statement.
def is_prime(num):
for x in range(2, int(num**0.5)+1):
if num % x == 0:
return False
return True
num = int(raw_input("Input any of the number you like:"))
if not is_prime(num):
print "It is not a prime number"
else:
print "It is a prime number"
Here are two Python routines for calculating primes. (Hint: Google for Sieve of Eratosthenese):
def pythonicSieve(maxValue):
"""
A Pythonic Sieve of Eratosthenes - this one seems to run slower than the other.
see http://love-python.blogspot.com/2008/02/find-prime-number-upto-100-nums-range2.html
"""
return [x for x in range(2,maxValue) if not [t for t in range(2,x) if not x%t]]
def sieveOfEratosthenes(maxValue):
"""
see http://hobershort.wordpress.com/2008/04/15/sieve-of-eratosthenes-in-python/
"""
primes = range(2, maxValue+1)
for n in primes:
p = 2
while n*p <= primes[-1]:
if n*p in primes:
primes.remove(n*p)
p += 1
return primes