Python prime checker - python

I recently started learning python (by which I mean, 35 minutes ago at the time of posting...) and I've wrote a few things e.g. square root generator, factorial generator, Fibonacci number generator, prime checker etc. After I wrote the prime checker, I thought I'd try modifying it so that instead of checking every number in the specified range, it would accept an input and check that one specifically.
DISCLAIMER: If I were better at Python then I would only check numbers up to sqrt(p) and I would add an option to check if it is even and not 2 then it automatically returns that it's not prime but let me walk before I run! :)
CODE:
p = input("Enter a potential prime.")
for n in range (2,p):
if p % n == 0:
print(p, "equals", n, "x", p//n, "so it isn't a prime number")
break
else:
print(p, "is a prime number.")
It works for p = 2 but that's it...
NB - Obviously the code is indented accordingly, it's just not formatted properly here.

I see some errors: You need to convert your user input to an int, plus you need to move the else: clause to beneath your for-loop instead of beneath your if-statement. The following code works for what you want:
p = int(input("Enter a potential prime."))
for n in range (2,p):
if p % n == 0:
print(p, "equals", n, "x", p//n, "so it isn't a prime number")
break
else:
print(p, "is a prime number.")
Yes, this is correct - the else: is NOT part of the if-statement, it is part of your for-loop. This syntax means that if your for-loop runs to a break, then it'll break as normally. If there is no break, then the else: clause will be executed. Thus, it'll do the basic trial division, and if the number passes the test, it'll print "is a prime number" only once. The code you posted will print "is a prime number" for every iteration of your loop.
Edit: Try the following code for your followup question.
def primeChecker():
# Function that keeps prompting for input, and checks if it's prime. Enter "quit"
# to exit:
user_input = input("Enter a potential prime (or type 'quit' to exit): ")
if user_input == 'quit':
return
else:
p = int(user_input)
# Trial division algorithm:
for n in range (2,p):
if p % n == 0:
print(p, "equals", n, "x", p//n, "so it isn't a prime number")
break
else:
print(p, "is a prime number.")
# Recursive function call:
primeChecker()
# Start by calling the main function:
primeChecker()

Related

Inputting large numbers and check if it is prime (Python)

I am making a program using python wherein it checks large numbers if it is a prime number or not. (this is for RSA Encryption)
Here is my code:
p = int(input("Enter first prime number: "))
while(1):
if isPrime(p) is False:
print("%d is not a prime number!" % p)
p = int(input("Please enter first prime number again: "))
else:
print("%d is a prime number." % p)
break
q = int(input("Enter second prime number: "))
while(1):
if isPrime(q) is False:
print("%d is not a prime number!" % q)
q = int(input("Please enter second prime number again: "))
else:
print("%d is a prime number." % q)
break
p is the first large number and q is the second large number.
here is the function that checks if it is a prime number:
def isPrime(num):
if num > 1:
for i in range(2, num):
if(num % i) == 0:
return False
else:
return True
else:
return False
I tried running it using small numbers like 17 and 11 and it works but when I tried to input a 16-digit number, it doesn't work anymore.
Here is the sample run:
On the second image, when I entered a large number, it does not continue. I tried waiting for half an hour and see if it works but it still, it's just like that. Why is it so?
It's taking so long because you're looping over A LOT of numbers, every one up until your 16 digit one, which is a lot of loop iterations. Even if you're only doing constant work per iteration, getting through that many numbers will still take awhile. Loops in python are notoriously slow. Luckily, you can use sympy like so:
from sympy.ntheory import factorint
def isPrime(n):
return len(factorint(n)) == 1
and then things should be going much faster. For reference:
factorint(133453565475464563453)
took about half a second

Stuck in an infinite loop with my prime number finder program

I've been working on a program for my class for a bit. It is supposed to be a prime number finder, where the def is_prime (num) function loops and continually asks the user to input more numbers, checks whether they are prime, and prints whether they are or not. If a negative number is entered, it is supposed to then quit.
def is_prime (num):
while num >= 0:
if num % 1 == num or num % num == 0:
print(num, "is a prime")
elif num % 2 == 0:
print(num, "is not a prime")
continue
elif num < 0:
print("Done. Thanks for using the program!")
break
return 0
if __name__ == "__main__":
print("This program checks if a given number is a prime number\n")
num1 = int(input("Please enter a positive number (or a negative number to exit):\n"))
is_prime(num1)
However, it only has part of that right. It reads and determines prime numbers...but instead of looping back to the function beginning it just endlessly prints the statement of whether or not it is a prime. I'm pretty sure it's a problem of where I've put my while loops, but I'm not entirely sure how to fix that.
Any help would be appreciated.
You haven't described your intended algorithm; it's not at all clear from your code. YOur first if checks whether the input number is divisible by 1 or divisible by itself ... both of which are algebraic tautologies.
Then you repeat this as long as the input remains positive. Since you never change the value of num, this is a pretty direct infinite loop.
You can't test for divisibility for each candidate factor with a different if in an if ladder.
You'll need to stash each prime you find in a list.
EG:
def sieve_primes(stop=100000):
"""Yield primes below stop."""
primes = [2]
for candidate in range(3, stop + 1, 2):
if not any(candidate % prime == 0 for prime in primes):
primes.append(candidate)
yield candidate
for prime in sieve_primes():
print(prime)
Raid it for ideas, but don't copy it verbatim. You could speed it up a lot with math.sqrt(), BTW.
HTH

creating a python program which ask the user for a number - even odd

I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0

Generating a prime number bigger than a number found in a list

What isn't working below: I can't make the genPrim function work, as I get the "TypeError: 'int' object is not subscriptable".
A few observations:
1. What my program should do is first input a number into a list and then apply the other functions on that number.
2. The problem is that I can't seem to use that number from the list to do so. How can I do it? I was first thinking about asking for its position, but when going for the genPrim, both genPrim and Prim work because they are interdependent but they ask for the same thing.
def Adauga(L):
n = int(input("Give number:"))
L = L + [n]
return L
#Verify if number is prime
def Prim(L):
poz = int(input("Position of number: "))
n = L[poz]
if n<2 :
return False
NrDiv=0
for a in range (2,int(n/2+1)):
if n%a==0:
NrDiv=NrDiv+1
if (NrDiv==0):
return True
else:
return False
#Generate prime number
def genPrim(L):
poz = int(input("Give number: "))
a = L[poz]
b=a+1
while Prim(b)==False:
b=b+1
return b
#Display menu
def AfisMeniu():
print()
print("1.Add number")
print("2.Check if number is prime")
print("3.Generate prime number")
print("0.End of program")
i = int(input("Your option: "))
return i
def Main():
"""
Start the program
"""
L = []
Opt = AfisMeniu()
while (Opt != 0):
if Opt == 1:
L=Adauga(L)
elif Opt ==2:
L=Prim(L)
print (L)
elif Opt ==3:
L=genPrim(L)
print (L)
else:
print ("Wrong!")
Opt = AfisMeniu()
print()
print("End of program")
Main()
You are getting that error because genPrim returns an int, but Main() assigns that result to L, so L no longer contains a list of numbers, just that single int.
Similarly, Prim() returns a boolean (True or False) but Main() assigns that to L, too.
FWIW, the basic logic of your Prim() function is correct, but it's a very inefficient way to test if a number is prime. At the very least you should change it to return False as soon as it has found one divisor, i.e. when n%a==0.
I've managed to make the third option work, as in generating a prime number. However, what I would also like is to make the second option work as well, the prime verification.
My idea is modifying the code in the Main() function, by taking the len of the position, however I can't really make it work.
elif Opt ==2:
L=Prim(L)
poz1=int(len(L))
print (L[poz1])
Or perhaps, should I attempt a different method?

How to add up a variable?

I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)

Categories