This question already has answers here:
Fastest way to list all primes below N
(39 answers)
Closed 8 years ago.
I'm trying to get make a program that will print all the prime numbers within the argument I pass to it, so far I've made python respond with a True or False if it is prime or not.
prime = []
prime_list = []
def check_prime(user_input):
for x in range(2, user_input):
if float(user_input) % x > 0:
prime = True
else:
prime = False
break
print prime
check_prime(int(raw_input("get prime numbers up to: ")))
Here is the program where it successfully returns if the number is prime or not(I think)
What I am trying to do is get all the prime numbers and store them into a list, then print them all out when it's finished. I've been picking away at this program for at least a week and I just can't figure it out.
Please pointers only, no finished version.
You have made a function which prints out True or False depending on whether a number is prime.
The next step is to make it return True or false.
Here is an example of a different test which you can adapt for your own needs.
def is_even(number):
if number % 2 == 0:
return True
else:
return False
$ is_even(6)
True
$ answer = is_even(6)
$ print(answer)
True
The next step is to loop through all the numbers that you want to consider, and only store them if they are prime. (You could also just print them if that's all you need.)
Related
This question already has answers here:
Prime number check acts strange [duplicate]
(14 answers)
Closed 5 days ago.
I'm writing a program that tells if this is a prime number from the input.
I'm trying to understand the logic of this code:
def prime_checker(number):
for i in range(2, number):
if number % i == 0:
print("It's not a prime number.")
break
else:
print("It's a prime number")
break
n = int(input("Check this number: "))
prime_checker(number=n)
Previously, I did not put a break, which resulted with a lot of print statements being printer. So I googled, "how to end the loop in python".
Now, the code did not work as expected. For example, if I put 2, I get no results (nothing). If I put 87, it says it's a prime number (it's not).
Can someone explain what is wrong with the code?
I know that the right solution would be:
def prime_checker(number):
is_prime = True
for i in range(2, number):
if number % i == 0:
is_prime = False
if is_prime:
print("It's a prime number.")
else:
print("It's not a prime number.")
n = int(input("Check this number: "))
prime_checker(number=n)
However, I do want to truly understand the logic and differences between two. Any thoughts?
Many Thanks!
You cannot know whether number is a prime before having checked all potential divisors. So you cannot expect to know the number is a prime before the loop has made all* iterations. You really need to be sure there is no integer divisor.
The opposite is true: you can know whether the number is not a prime before having tested all potential divisors, because you only need to find one divisor. As soon as you found it you know it is not a prime and don't need to continue looping. The second code could therefore be optimised by a break just following is_prime = False
* Well, you could know once i > sqrt(number). Fact is that the loop doesn't have to continue beyond that limit.
This question already has answers here:
To find first N prime numbers in python
(30 answers)
Closed 5 years ago.
I’m new to python and I’m trying to figure out how to make a function where you enter a number and it gives you the number prime.
Example: If I enter 6 it returns 13. Since 13 is the 6th prime.
Preferably no modules except ones in standard library,
Thank you
This is what you are looking for:
def nth_prime_number(n):
# initial prime number list
prime_list = [2]
# first number to test if prime
num = 3
# keep generating primes until we get to the nth one
while len(prime_list) < n:
# check if num is divisible by any prime before it
for p in prime_list:
# if there is no remainder dividing the number
# then the number is not a prime
if num % p == 0:
# break to stop testing more numbers, we know it's not a prime
break
# if it is a prime, then add it to the list
# after a for loop, else runs if the "break" command has not been given
else:
# append to prime list
prime_list.append(num)
# same optimization you had, don't check even numbers
num += 2
# return the last prime number generated
return prime_list[-1]
x = nth_prime_number(8)
print(x)
Try this code !
I am also attach the screenshot of the output .
num=int(input("Enter Position : "))
r =1000
count=0
import sys
for a in range(2,sys.maxsize**10):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
count=count+1
if(count==num):
print("Prime Number at position " , num , " is " , a)
break
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
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