Why is my code below giving me wrong results? When I give it numbers like 2 and 3, it says they're not prime numbers. Only some numbers work but for the most part it gives wrong answers.
def prompt_input(input_msg, error_msg):
while True:
userinput = input(input_msg)
try:
integer = int(userinput)
if integer > 1:
return integer
print(error_msg)
except ValueError:
print(error_msg)
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
primenum = prompt_input(
"Give an integer that's bigger than 1: ",
"You had one job"
)
if check_prime(primenum):
print("This is a prime.")
else:
print("This is not a prime.")
First issue: Your for loop returns after one iteration, so the correct return logic would be:
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
However you are implementing this incorrectly as well, the loop needs to iterate up to the sqrt of the number.
def check_prime(number):
for i in range(2, int(sqrt(number))+1):
if number % i == 0:
return False
return True
Hope this helps!
Need to unindent the return True.
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
Related
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break
else:
return "True"
else:
return "False"
x = int(input("Enter number"))
c = acc_p(x)
print(c)
Output:
Enter number33
None -> (I want this to be 'True')
Your code reaches no return statement for the break case. You can return from there though:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
return "False"
else:
return "True"
else:
return "False"
This can be simplified as you are returning from every if-block:
def acc_p(num):
if num <= 1:
return "False"
for i in range (2, int(num/2)+1):
if num % i == 0:
return "False"
return "True"
Ultimately you would probably want to return bool values. And with the short-circuiting pattern in your loop, you can use any:
def acc_p(num):
if num <= 1:
return False
return not any(num % i == 0 for i in range (2, int(num/2)+1))
It returns None when the for loop breaks, meaning the else statement will never be met:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break # If it breaks here...
else:
return "True" # This will never be met
else:
return "False" # And of course this one will never be met
x = int(input("Enter number"))
c = acc_p(x)
print(c)
What you'll want to do is return another value under the inner else statement:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break
else:
return "True"
return "False"
else:
return "False"
x = int(input("Enter number"))
c = acc_p(x)
print(c)
Test run:
Enter number7
True
Again:
Enter number33
False
(Note that 33 is not a prime number.)
Hi I'm a beginner and I'm stuck on this question that wants me to use only while loop to solve. The question wants me to write a function that returns True when the given number is a prime number and it returns False if the given number is not a prime number.
My code so far:
def is_prime(n):
i = 2
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
The problem I have is I think my code displays the correct output for numbers 4 and above and it returns 'None' for 1, 2, and 3. I've debugged it and I think the problem is the while loop condition. But I don't know how to fix it. I would appreciate it if any of you pros can help me out!
edit:
I changed the while condition but 1 still returns None.. and 2 returns False when it's supposed to return True
def is_prime(n):
i = 2
while i <= n:
if n%i != 0:
return True
else:
return False
i+=1
import math;
def is_prime(n):
i = 2
while i < max(math.sqrt(n),2):
if n%i != 0:
return True
else:
return False
if i == 2:
i+=1
else
i+=2
You could hard-code these 3 cases, in case you dont want to use sqrt:
def is_prime(n):
i = 2
if n in (1,3):
return True
elif n == 2:
return False
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
for x in range(1, 5):
print(x, '=', is_prime(x))
Output:
(1, '=', True)
(2, '=', False)
(3, '=', True)
(4, '=', False)
Want to get really fancy? Make a Sieve of Eratosthenes:
def is_prime(n):
a = list()
# Assume all are prime
a[0:n+1] = (n+1)*[1]
# Start with removing even numbers
i = 2
while i*i <= n:
print ("I: ", i)
# Set all divisible by i to 0
a[0:n+1:i] = len(a[0:n+1:i])*[0]
# If a[n] is zero, return False
if a[n] == 0:
return False
# Increment i until we have a prime number
while a[i] == 0:
i+=1
if a[n] == 0:
return False
else:
return True
If you want to impress your lesson teacher you can show him a fast probabilistic prime number isprime for numbers larger than 2**50. I haven't found any errors in it after weeks of cpu time stress testing it on a 6 core AMD:
import random
import math
def lars_last_modulus_powers_of_two(hm):
return math.gcd(hm, 1<<hm.bit_length())
def fast_probabilistic_isprime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if lars_last_modulus_powers_of_two(hm+hm) != 2:
return False
if pow(2, hm-1, hm) == 1:
return True
else:
return False
def fast_probabilistic_next_prime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if hm % 2 == 0:
hm = hm + 1
hm += 2
while fast_probabilistic_isprime(hm) == False:
hm += 2
return hm
""" hm here is bitlength, which must be larger than 50.
usage is create_probabilistic_prime(1000)
"""
def create_probabilistic_prime(hm):
if 2**hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
num = random.randint(2**hm,2**(hm+1))
return fast_probabilistic_next_prime(num)
In the console, my program prints the first question, and once the input is entered, prints the second one and terminates. It appears to skip the function. Obviously I've done something(s) wrong, any help would be appreciated. That while-loop still feels wrong.
def Prime(n):
i = n - 1
while i > 0:
if n % i == 0:
return False
print("This number is not prime.")
else:
i = i - 1
return True
print("This number is prime.")
def Main():
n = int(input("What is the number you'd like to check?"))
Prime(n)
answer2 = input("Thank you for using the prime program.")
Main()
Your function returns before printing output, so nothing ever gets to the console. Consider printing before returning:
def Prime(n):
i = n - 1
while i > 0:
if n % i == 0:
print("This number is not prime.") # Here
return False
else:
i = i - 1
print("This number is prime.") # And here
return True
In this primality test program, 'None' is printed when I input a prime, instead of 'True'. How can I get it to print 'True'?.
def main():
import math
def check_n(n):
n_s = int(math.sqrt(n))
for i in range(2, n_s):
if (n_s % i) == 0:
return False
break
else:
return True
def msg():
n = int(input('Enter a number, I will return True if it is a prime'))
return n
print(check_n(msg()))
main()
You need to change int(math.sqrt(n)) to int(math.sqrt(n)+1), because range runs until n_s-1. So if the input is 5, range(2,int(math.sqrt(5))) is just range(2,2), which is empty.
In addition, you need to take the return True outside of the for loop, otherwise your code may stop in a too early stage. You also don't need the break statement after return False (the function will never arrive to that line, as it will return False if it enters to that if statement).
Finally, change if (n_s % i) == 0: to if (n % i) == 0:, as you need to check if n is divisible by i (and not its square root).
Here is a more clean version:
import math
def check_n(n):
n_s = int(math.sqrt(n)+1)
for i in range(2, n_s):
if (n % i) == 0:
return False
return True
def msg():
n = int(input('Enter a number, I will return True if it is a prime'))
return n
print(check_n(msg()))
First: Your break statement is redundant.
Second: For values such as 3 the for loop is never executing because value
n_s is less than 2 and since the for loop isn't executing the
python is returning the default value None(which is returned when
no value is specified).
Hence your check_n(n) function has to be
def check_n(n):
n_s = int(math.sqrt(n))
for i in range(2, n_s + 1):
if (n_s % i) == 0:
return False
return True
one liner :
check_n = lambda n : sum([i for i in range(2, int(math.sqrt(n)+1)) if n % i == 0]) == 0
don't overcomplicate things ..
Your range is (2,2) or None when you choose anything less than 9.
So to solve your first problem: add 2 to n_s (for input 3)
You also have a problem with your logic.
Your for loop should be checking that n mod i is 0, not n_s.
This should work:
def main():
import math
def check_n(n):
n_s = int(math.sqrt(n)+1)
for i in range(2, n_s):
if (n % i) == 0:
return False
return True
def msg():
n = int(input('Enter a number, I will return True if it is a prime'))
return n
print(check_n(msg()))
main()
Hello I'm very new to python and was wondering if you could help me with something.
I've been playing around with this code and can't seem to get it to work.
import math
def main():
if isPrime(2,7):
print("Yes")
else:
print("No")
def isPrime(i,n):
if ((n % i == 0) and (i <= math.sqrt(n))):
return False
if (i >= math.sqrt(n)):
print ("is Prime: ",n)
return True
else:
isPrime(i+1,n)
main()
Now the output for the isPrime method is as follows:
is Prime: 7
No
I'm sure the function should return true then it should print "Yes".
Am I missing something?
You are discarding the return value for the recursive call:
def isPrime(i,n):
if ((n % i == 0) and (i <= math.sqrt(n))):
return False
if (i >= math.sqrt(n)):
print ("is Prime: ",n)
return True
else:
# No return here
isPrime(i+1,n)
You want to propagate the value of the recursive call too, include a return statement:
else:
return isPrime(i+1,n)
Now your code prints:
>>> isPrime(2,7)
is Prime: 7
True