i have exactly 5 days of practise, an hour daily so kindly forgive if my questions are very low level. No prior coding exp
My objective of the below code is
1- check if entered number is a prime
2- if not print the next biggest prime
def primetest (num): # check if number is a prime
for c in range (2, num):
if num % c == 0:
repeattest (num) #not prime? increment number
else :
print (num,"is a prime number")
break
def repeattest (num): # check prime if not increment number by 1
for z in range (2, num):
num = num+1
primetest (num)
if num % z == 0:
num = num+1
else:
print ("Next Prime:", num+1)
break
num = int (input ("enter a number:")) # main code:
for y in range (2, num):
if num % y == 0:
repeattest (num)
else:
print (num,"is a prime number")
break
I think the logic is fine, but not sure why im not getting an output. Please help
The way you have done has a lot of errors not efficient. By making some modification to your code i have made it much simpler. Read the comments to understand:
def primetest (num): # check if number is a prime
return(all(num % i for i in range(2, num)))
num = int (input ("enter a number:")) # main code:
while True: #loop continues until prime number found(True)
if primetest(num):
print(num,"is a prime number.")
break #(stops loop if prime found)
else: #otherwise repeat by incrementing to the next num until found
print(num,"is not a prime number.")
num += 1
Output:
enter a number:45
45 is not a prime number.
46 is not a prime number.
47 is a prime number.
Related
Hi my goal is to write a program where I can check whether a number is prime. However, I have made an error in my code that I'm not sure how to fix. For example, if I input 15, which is not a prime number, it prints out both "num is not a prime number" and "num is a prime number".
num = int(input("Enter a positive number to test: "))
while num < 0:
print("Invalid input, try again")
num = int(input("Enter a positive number to test: "))
prime = False
for i in range(2,num):
if num % i == 0: #if remainder is zero, then there is a factor
print(i, "is a factor of", num, "...stopping")
print("")
print(num, "is a not a prime number")
break
if num % i != 0:
print(i, "is not a divisor of", num, "... continuing")
prime = True
if prime == True: #once the condition from earlier is met, then it'll prove it's a
prime numer
print(num, "is a prime number")
When trying to determine if a number (N) is prime, your first test is to see if it's less than 2. If that condition is met then it's not prime. From then on you need to check the modulus of N with a range of prime numbers up to the square root of N. So then it's a question of how to generate prime numbers quickly and efficiently and this has been answered many times in Stackoverflow. There are also strategies for determining probability of N being prime (usually only used for very large numbers)
Here is the output from your code.
Enter a positive number to test: 15
2 is not a divisor of 15 ... continuing
3 is a factor of 15 ...stopping
15 is a not a prime number
15 is a prime number
The problem is in your bool variable prime. Before the for-cycle you assign it FALSE value. Every time in for-cycle when the number is not divided by i, you assign TRUE to prime variable. So if the second condition is met for once, your code always prints:
given_number is a prime number
You should change the logic of your code. Before the for-cycle always assume that the given number is prime number(prime = True).
prime = True
for i in range(2,num):
if num % i == 0: #if remainder is zero, then there is a factor
print(i, "is a factor of", num, "...stopping")
print("")
print(num, "is a not a prime number")
prime = False
break
if num % i != 0:
print(i, "is not a divisor of", num, "... continuing")
num = 13
if num > 1:
for i in range(2, num//2):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
I wrote a piece of code to check whether a number is a prime or not. It works in Powershell, but won't work on the online submission platform.
I have re-read how to define whther a number is prime and I can't find anything else that I might have missed in my code.
x = int(input('Please enter a number: '))
if x > 1:
for i in range(2, x):
if (x % i) == 0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
break
else:
print('The number you inputted is not a prime number.')
Should print out whether a number is prime or not.
You can use the for-else construct so that a prime number is only determined when the loop finishes without breaking due to finding a divisor. Also, you only need to iterate up to the square root of the input number when looking for a divisor:
x = int(input('Please enter a number: '))
for i in range(2, int(x ** .5) + 1):
if x % i == 0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
Well, first of all you have to remove the innermost else clause.
Think in the case that x = 9, for example. Control flow will enter the for clause, starting with i=2. It will test if x % i == 0, that is, if x is divisible by i. It isn't. Then you go to the else clause. Prints that "The number you inputted is a prime number" and breaks, ending the for loop. That is not what you want.
You only conclude that the number is prime after looking if it is divisible by all of the i's. That is, you want the code concluding the number is prime (the print("The number you inputted is a prime number")) to be outside the for loop.
Some tweaks are needed overall. Here is a working solution:
x = int(input('Please enter a number: '))
if x > 1:
for i in range(2, x):
if (x % i) == 0:
print('The number you inputted is not a prime number.')
break
if i==x-1:
print('The number you inputted is a prime number.')
else:
print('The number you inputted is not a prime number.'
x = int(input('Please enter a number: '))
if x > 1:
for i in range(2, x):
if (x % i) == 0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
else:
print('The number you inputted is not a prime number.')
This correction worked!
Solution
Here's a solution modeled after the way you tried the code. Note that sometimes, if you copy a code from certain websites, you could run into code formatting issues/problems with indentation. For example, when I copied a similar code-block from programiz.com: prime-number it repeatedly returned indentation error. The only way I could get around that is hand typing the code logic.
Perhaps one could try fixing this by copy pasting the code into a plain-text-editor (like notepad) and then copy-pasting that into the IDE you are using.
def is_prime(num):
isprime = False
# prime numbers are greater than 1
if (num>1):
for i in range(2,num):
# check if divisible by any number
# other than itself and 1
if (num % i) == 0:
isprime = False
break
# Not divisible by any number
# other than itself and 1
else:
isprime = True
# numbers 0 and 1 are not prime numbers
else:
isprime = False
return isprime
is_prime(31), is_prime(42)
Output:
(True, False)
I would like to suggest a more pythonic way:
x = int(input('Please enter a number: '))
if x<2:
print('The number you inputted is not a prime number.')
elif x==2:
print('The number you inputted is a prime number.')
else:
y = range(2,x)
mod = map(lambda a:divmod(x,a)[1],y)
if all(mod):
print('The number you inputted is a prime number.')
else:
print('The number you inputted is not a prime number.')
What about removing that else statement. You really need to check all numbers 2 ... (k-1)
x = int(input('Please enter a number: '))
if x > 1:
is_prime = True
for i in range(2, x - 1):
if (x % i) == 0:
is_prime = False
break
if is_prime:
print('The number you inputted is a prime number.')
else:
print('The number you inputted is not a prime number.')
else:
print('The number you inputted is not a prime number.')
I tried out this code in Python for testing whether or not a number is prime.
x = int(raw_input('Enter a number:'))
for i in range (2, x):
if (x % i) == 0:
print (x, 'is not prime')
else:
print(x, 'is prime')
But when I entered 25 I get the following output.Why?
Why is the output printed for so many times?Also, why is there suddenly a line that says 25 is not a prime (correct) amidst so many 'is a prime'?
Since you are looping from 2 to x for a value of x i.e. looping x-2 times and you are printing for each iteration. Hence, 23 print statements for x = 25.
You can do something like this :
x = int (raw_input('Enter a number:'))
answer = "{} is prime"
for i in range (2,x):
if (x%i)==0:
answer = "{} is not prime"
break
else:
pass
print(answer.format(str(x)))
You have to use break
x=int (raw_input('Enter a number:'))
for i in range (2,x):
if (x%i)==0:
print (x,'is not prime')
break
else:
print(x,'is prime')
A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. So, it is good to check if variable x is greater than 1.
x=int (raw_input('Enter a number:'))
# prime numbers are greater than 1
if x > 1:
# check for factors
for i in range(2,x):
if (x % i) == 0:
print(x,"is not a prime number")
print(i,"times",x//i,"is",x)
break
else:
print(x,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(x,"is not a prime number")
when you run this code, python will continue executing code in a for loop for all i in that range.
when you input 25, python first divides it by 2. Since 25%2=1, it prints that it is prime
it does the same for 3 and 4 and prints that both are prime
at 5, it calculates that 25%5=0 and correctly prints that 25 is not prime
try this
x=int (raw_input('Enter a number:'))
for i in range (2,x):
if (x%i)==0:
print(x,'is not prime')
break
elif i==x-1:
print('x is prime')
Python divides the number by i. If at any point the remainder is 0, it prints that the number is not prime and the code ends.
If the remainder is not zero, the code loops back to the beginning of the for loop
If x%i has never equaled zero by the second to last iteration (represented by i==x-1), then the code prints that x is prime
use a for loop statements
x = int(raw_input('Enter a number:'))
for i in range(1, x):
if x <= 2:
print(x, 'is prime')
break
elif (x % i) == 0:
print (x, 'is not prime')
break
else:
print(x, 'is prime')
break
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!
#Enter an integer
num = int(input("Enter a number: "))
#Prime number is a positive integer that is evenly divisible by 1 and itself
#Zero and one shouldn't be prime numbers
#Use for loop in the range of 2 as the first prime to any integer num
#If else statements: If integer num is divisible by any integer between
#2 and itself the integer num isn't a prime number
#or else the integer is a prime number
if num < 2:
print(num, "isn't a prime number")
for x in range(2, num):
if num % x == 0:
print(num, "isn't a prime number")
break
else:
print(num, "is a prime number")
Observations -
The output I am getting when I enter the integer 0 and integer 1 individually, is:
0 isn't a prime number
0 is a prim number
1 isn't a prime number
1 is a prime number
Keeping in mind this is with the if statement before the for loop. With it the entire program outputs every other integer correct. But still for integer 0 and 1:
It outputs:
0 is a prime number
1 is a prime number
You don't return when checking for num < 2. You could change to:
if num < 2:
print(num, "isn't a prime number")
return
assuming that you are in a function. Otherwise you could use else:
if num < 2:
print(num, "isn't a prime number")
else:
for x in range(2, num):
if num % x == 0:
print(num, "isn't a prime number")
break
else:
print(num, "is a prime number")
You do not have a return statement or else clause after your initial IF condition.
Also just a quick tip, no need to check modulo of every integer up to the number. I believe only up to half the number is necessary. Been awhile since I programmed a prime number algorithm.
You need to stop once you've confirmed it's lower than 2:
Use only one of the following ...
If you're looping, to continue to next iteration:
if num < 2:
print(num, "isn't a prime number")
continue
If you're in a function, and want to return a value:
if num < 2:
print(num, "isn't a prime number")
return False
If you're not looping or in a function, and want to terminate the program:
if num < 2:
print(num, "isn't a prime number")
sys.exit()