Python Print statement in a loop, generating prime numbers - python

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.

Related

Python, trying to sum prime numbers, why is '7' not getting appended?

I am trying to make a simple function to sum the prime numbers of a given input. I am wondering why '7' isn't coming up in my appended list of prime numberS:
def sum_primes(n):
empty = []
for i in range(2,n):
if n % i == 0:
empty.append(i)
print(empty)
sum_primes(10)
Your method for determining if numbers are prime is a bit off. Your function seems to determine if the input num n is prime but not sum all prime numbers to it.
You could make an isprime function and then loop over that for all numbers less than n to find all primes.
Actually your program have logical error. First you have to understand the prime number logic.
Step 1: We must iterate through each number up to the specified number in order to get the sum of prime numbers up to N.
Step 2: Next, we determine whether the given integer is a prime or not. If it is a prime number, we can add it and keep it in a temporary variable.
Step 3: Now that the outer loop has finished, we can print the temporary variable to obtain the total of primes.
sum = 0
for number in range(2, Last_number + 1):
i = 2
for i in range(2, number):
if (int(number % i) == 0):
i = number
break;
if i is not number:
sum = sum + number
print(sum)
def sum_primes(y):
sum = 0
# for each number in the range to the given number
for i in range(2, y):
# check each number in the sub range
for j in range(2, int(i/2)+1):
# and if its divisble by any number between
# 2 and i/2
if i % j == 0:
# then it is not a prime number
break
else:
# print current prime
print(i)
# add prime to grand total
sum += i
return sum
print(sum_primes(10))
I think you have some problems with the way you are checking if your number is prime or not. A much simpler way would be to use a library that does this for you. It takes less time, is usually a better implementation than you or I could come up with, and it takes fewer lines, therefore, looking cleaner.
I would recommend primePy. Its whole point is to work with prime numbers.
I don't have my computer with me atm so I can't make any sample code for you and test it. But something like this should work.
from primePy import primes
prime_list = primes.upto(n)
print(prime_list)
I believe that function returns a list of all prime numbers up to n. And if you wanted to get the sum of all of those numbers, you can go about whatever method you want to do that.
Afterward, slap it into a def and you should be good to go.
If it doesn't work let me know, and I will try to test and fix it when I am in front of a computer next.

Check for prime number and list factors for non prime

My assignment is
Create a program that checks whether a number is a prime number. The display should include whether or not the number is prime and a list of the number’s factors.For numbers that are not prime, also include the number of factors for that number.
I have the code
while choice.lower() == "y":
def is_prime_number(x):
if x >= 2:
for y in range(2,x):
if not ( x % y ):
return False
else:
return False
return True
for i in range(int(input("Please enter an interger between 1 and 5,000: "))):
if is_prime_number(i):
prime_numbers += 1
print (i)
print (str(prime_numbers) + " is a prime number.")
the output i get is
Please enter an interger between 1 and 5,000: 22
2
3
5
7
11
13
17
19
8 is a prime number.
Continue (y/n)?:
I need the output to be the factors of that number. Please help i am a begginer
Obviously, you can't just return False as soon as you find a factor if you're supposed to be counting the number of factors. Instead, you need to increment some count of factors and keep going through the loop:
for y in range(2,x):
if not ( x % y ):
factors += 1
Of course you also need code that starts off with factors = 0.
Also, you can't just return True for prime and False for composite; you have to return the number of factors as well. And, since you're no longer returning early as soon as you find a factor, you can't just return True at the end; you need to decide whether the number is prime or not based on the number of factors you've found.
More importantly, you need to return the number of factors, either instead of or in addition to returning whether the number is prime. Maybe you can just return factors. Although you need to figure out what to do about 0 and 1 now; the existing else: return False doesn't make any sense with that.
And you probably want to change your function name from is_prime_number to, say, count_factors.
And then, finally, you need to change your main loop to do something like this:
factors = count_factors(i)
if not factors: # and maybe some other condition for 0 and 1?
print(i, 'is prime')
prime_numbers += 1
else:
print(i, 'has', factors, 'factors')
Hopefully this is enough for you to fill in the rest yourself.

Creating a tool for divisors

import requests
def repeat():
x = int(input("Common divisors of: "))
listrange = list(range(2,x))
emptylist = []
for number in listrange:
if x % number == 0:
emptylist.append(number)
print (emptylist)
elif x % number not in listrange:
print ("Prime number")
while True:
repeat()
Whenever I run this code it it prints prime number several times no matter what I type in.
What I want it to do instead is to give all common divisors for any integer except for 1 and the integer. If the integer is a prime number I want it to print prime number.
However as I previously mentioned this causes a problem for some reason resulting in that whenever the code is executed it prints prime number over and over again even though an elif statement is used.
Your current logic prints 'Prime number' every time it encounters an integer in the range which doesn't divide the number, irrespective of whether any other numbers divide it (i.e. it is not prime) or not (i.e. it is prime).
This logic corrects that:
def repeat():
x = int(input("Common divisors of: "))
listrange = list(range(2,x))
emptylist = []
for number in listrange:
if x % number == 0:
emptylist.append(number)
if not emptylist: #Checks if emptylist is empty i.e. is prime
print ("Prime number")
else:
print (emptylist)
e.g.
Common divisors of: 5
Prime number
Common divisors of: 28
[2, 4, 7, 14]
Your x % number not in listrange is going to be true a lot of the time, even for prime numbers. It is the wrong thing to test for prime numbers.
Say you start with 7, a prime number. The first number to be tested is 2:
>>> x = 7
>>> number = 2
>>> x % number
1
So the remainder is 1. 1 is not in the listrange() values (which go from 2 through to 6, inclusive). That's because for any given prime number larger than 2, division by 2 will always result in 1 as the remainder, and 1 is never in your list.
2 is not the only such value for which the remainder of the division is 1. For the prime number 7919, there are 7 such numbers:
>>> [i for i in range(2, 7919) if 7919 % i < 2]
[2, 37, 74, 107, 214, 3959, 7918]
so your code will print Prime number 7 times. And the test would be true for non-prime numbers too; 9 is not a prime number, but 9 % 2 is 1 too, so your code would claim 9 to be a prime number. For 1000, not a prime number, your code would print Prime number 32 times!
You can't state that a number is a prime number until you have tested all the values in listrange() and have determined that none of those numbers can divide the number without a remainder. So you need to test after you loop; you could test if emptylist is empty; that means there were no divisors, the very definition of a prime number:
for number in listrange:
if x % number == 0:
emptylist.append(number)
if not emptylist:
print ("Prime number")
As a side note: you don't need to turn a range object into a list of numbers, not only does testing if number in range(...): work, it's a lot faster than using the same test on a list.

Identify whether or not a number is prime

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

How could I check if a number is a prime number? [duplicate]

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

Categories

Resources