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.
Related
I am trying to create a program that gets an integer from the user and then creates a list of integers starting after 1 to the integer the user inputed. For example, if the user inputs "8", then a list will be created [2, 3, 4, 5, 6, 7, 8]. After that I want it to go through each integer of the list and display only the prime numbers up to (or including) the user input.
def main():
#get user input of integer
user_integer = int(input('Please enter an integer greater than 1: '))
#call function that creates list of numbers up to user input
integer_list = create_list(user_integer)
#call function that returns prime numbers
prime_numbers = prime_number(integer_list)
#display prime numbers
print('The prime numbers up to the integer you entered are:', prime_numbers)
def create_list(x):
integer_list = []
numbers = 2
while numbers != x:
integer_list.append(numbers)
numbers += 1
return integer_list
def is_prime_number(num):
for i in range(2,num):
if num%i==0:
return False
else:
return True
def prime_number(x):
prime_numbers = []
for i in (x):
if is_prime_number(i):
prime_numbers.append(i)
return (prime_numbers)
main()
Edit: I edited the code to include a function that tests each number individually if its a prime number. However, it seems to be returning only odd numbers rather than prime numbers. For example, if I enter "13" it returns a list of [3, 5, 7, 9, 11]. Obviously 9 is not a prime number.
What am I doing wrong?
The problem is you're trying to find the remainder of diving a list by a number. That is why you are getting the error: % is an unsupported operand for types list and int. I'd suggest breaking out the logic to determine if a number is prime, then in your for loop, call that method. If it returns true, add it to the prime numbers list.
def is_prime_number(num):
for i in range(2, num):
if num % i == 0:
return False
return True
def prime_number(x):
prime_numbers = []
for i in (x):
if is_prime_number(x):
prime_numbers.append(i)
return prime_numbers
You don't need parenthesis around lists, and since you aren't using the composite numbers list, you don't need to keep track of it. Pulling the logic into its own function helps make the code cleaner and easier to look at. Feel free to make optimizations to the prime number function as well
I think your code could be improved by eliminating the modulo calculation and looping.It is also better to use a tried and tested algorithm for generating primes called the Sieve of Eratosthenes
def main():
user_integer = int(input('Please enter an integer greater than 1: '))
integer_list = list(range(2,user_integer))
prime_numbers = prime_number(integer_list)
#display prime numbers
print('The prime numbers up to the integer you entered are:', prime_numbers)
def prime_number(nums):
highest = nums[-1] + 1
sieve = [True] * (highest)
sieve[0:1] = [False, False]
for i in range(2, highest):
if sieve[i]:
for j in range(2 * i,highest,i):
sieve[j] = False
primes = []
for i in range(2, highest):
if sieve[i]:
primes.append(i)
return primes
if __name__ == "__main__":
main()
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.
n = int(input("input n"))
prime = [2]
base = 3
order = 0
while base < n + 1:
if order < len(prime):
if base % prime[order] == 0:
order = len(prime)
else:
order += 1
else:
prime.append(base)
order = 0
base += 1
print (prime)
I am trying to create a list of prime numbers from 1 to given number 'n'.
(ignoring the case for numbers less than 3)
What I intend to do is:
bring first number from 3 to n (let's call this base)
compare base to first number in prime list (in this case, 2)
if the base is not divisible, compare this to next number in prime list.
repeat step 3 until all numbers in the prime list are compared or at least one number divisible to base in the prime list appears.
if base compared to all numbers in the prime list and is not divisible by any of them, append base to prime list.
increase the value of base by 1 and repeat step 2 to 5 upto base = n.
Whatever the value i put for n, i only get single value of 2 in the prime list printed. Please help to find out which part is wrong.
The reason your code is failing is because you are not actually checking through all of the stored prime numbers correctly - you need a second loop for this. Fortunately, Python makes this easy for you in two different ways: A list of values can be easily looped through, and else is supported by for. The modified code should look something like this:
n = int(input("input n"))
prime = [2]
base = 3
while base < n + 1:
for p in prime:
if base % p == 0:
# base is NOT a prime, break out
break
else:
# loop ran to completion
prime.append(base)
base += 1
print (prime)
So instead of some other if statement that doesn't quite do what you think it does, we instead use a for loop check all values in the prime list (assign that to p) and do the division as you might expect. If the modulus is 0, the loop breaks uncleanly and the else block will not run, and if none of the primes result in a modulus of 0 the else block will be triggered, adding that newly discovered prime number to the list and so on.
Example:
$ python3 foo.py
input n19
[2, 3, 5, 7, 11, 13, 17, 19]
If you wish to keep the existing logic (i.e. no for loops), you can do another while loop inside and remember to set order to 0 before it.
Why is it that when you input 2 into this program, it returns "2 is prime"? According to the code, if the remainder of the number divided by i, where i is any number from (and including) 2 up to the number, is equal to 0, then the number is not a prime number. But the remainder of 2 divided by 2 is 0, so why does the program say that 2 is a 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")
because for i in range(2,2): will never be true / will not execute.
think about it range(start, stop)... the start and stop are the same so it will not enter into the for loop.
2 is a prime number but is the one case where the if statement doesn't need to be computed to determine if its a prime number
more details about pythons range function
range(2, 2) is actually an empty list, so the for loop doesn't iterate at all. It just jumps straight to the else clause:
>>> num = 2
>>> range(2, num)
[]
>>> for i in range(2, num):
... print "executing loop"
... else:
... print "done!"
...
done!
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.