I have written a code to find out if a number is prime or composite.
The code works fine when I input a prime number but when I input a composite number the output is:
enter number: 100
The number is not prime.
The number is prime.
I don't want The number is prime output for composite number input.
Here is my code:
print ('This program tells whether the number is prime or not')
print ('')
def prime(x):
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
print('The number is prime.')
i = input('enter number: ')
prime(int(i))
Please tell me what can I do to correct it.
The problem is the indentation, you've to move the indentation of the last line and add a break after that, so try using:
print ('This program tells whether the number is prime or not')
print ('')
def prime(x):
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
print('The number is prime.')
break
i = input('enter number: ')
prime(int(i))
I can see why. you are missing else after if. try this:
print ('This program tells whether the number is prime or not')
print ('')
def prime(x):
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
else:
print('The number is prime.')
i = input('enter number: ')
prime(int(i))
if num > 1:
for n in range(2, x-1):
if x % n == 0:
print('The number is not prime.')
break
else:
print('The number is prime.')
else:
print('The number is not prime.')
Simply fix that indentation in the for loop. Also, this looks a lot cleaner.
This is the recommended way to solve this problem.
do not use hard coded print statement.
try to return True or False instead.
def is_prime(x:str):
if x < 2:
return False
else:
for n in range(2, int(x/2)): # Use this for more speed
if x % n == 0:
return False
return True
Now you can check the number is prime or not by calling this is_prime function
print('Number is prime' if is_prime(6) else 'Number is not prime')
The problem is that when you break the loop the last print statement is called. If you end the function using return statement you will not reach the last print statement.
def prime(x):
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
return
print('The number is prime.')
Related
#Write your code below this line ๐
def prime_checker(number):
for num in range (2, number):
if num % number == 0:
print("It is not a prime number")
else:
print("It is a prime number")
#Write your code above this line ๐
#Do NOT change any of the code below๐
n = int(input("Check this number: "))
prime_checker(number=n)
How can I print a text that number is prime or not only once?
Fix
number % num == 0 and not num % number == 0
A number isn't prime the moment you find a number that doesn't divide it, but only when you have tested all and none divides it
Use for/else construction, it goes into else if no break has been used
def prime_checker(number):
for num in range(2, number):
if number % num == 0:
print("It is not a prime number")
break
else:
print("It is a prime number")
Note that this only fixes your way to do, but that isn't the optimal way to check if a numbre is a prime one, at least, ending range at square root of number, and directly verifying division by small numbers like 2,3,5,7
There are few mistakes in your code. I have modified them.
def prime_checker(number):
for num in range(2, number):
if number % num == 0:
print('Not prime')
return
print('Prime number')
# Write your code above this line ๐
# Do NOT change any of the code below๐
n = int(input("Check this number: "))
prime_checker(number=n)
For loop is to check if any of the number starting from 2 is a factor of number or not.
First, a slightly more efficient prime check by
going until the sqrt of the number only
going in steps of 2
import math
def is_prime(n: int) -> bool:
if n in (2, 3, 5):
return True
if n < 2 or n % 2 == 0:
return False
for i in range(3, math.ceil(math.sqrt(n)), 2):
if n % i == 0:
return False
return True
Now you can wrap that function in yours
def prime_checker(n: int):
msg = "%d is prime" if is_prime(n) else "%d is not prime"
print(msg % n)
prime_checker(11)
# 11 is prime
I think it's good to check a number is prime or not
def is_prime(n):
st = "prime" # being prime status
for i in range(2,n):
if n % i == 0: # if number is prime
st = "not prime"
break;
return st
n = int(input("enter n: "))
print (is_prime(n))
You only need to change the end of your code
your function is true except for these lines:
if num % number == 0:
print("It is not a prime number")
else:
print("It is a prime number")
you should change these to:
st = "Prime"
if number % num == 0:
st = "not prime"
return st
I need to do as the title suggests however I have ran into a problem. This is my code so far:
#Input
n = int(input('Enter n: '))
#Prime = 0
p = []
#Loopidty
for i in range(n):
#Ask user to input x
x = int(input('Enter a Number: '))
#Check if prime
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
else:
print('The number is prime.')
p.append(x)
#Answer
Answer = sum(p) / n
print('The answer is: ', Answer)
The issues is when I add the prime numbers to the list it only adds the first number and stops there, how do I combat this?
Many thanks
It's a good idea to break your code into smaller parts. We can create a function to check if a number is prime or not and check that it is correct. After that just add the rest of the code.
import math
def is_prime(x):
"""Check that a number `x``is prime"""
# You only need to go up to sqrt(x)
for n in range(2, int(math.sqrt(x) + 1)):
if x % n == 0:
return False
return True
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sum = 0.0
num_entries = 0 # Number of prime numbers entered by the user
n = int(input('Enter n: '))
for i in range(n):
x = int(input('Enter a Number: '))
if is_prime(x):
sum += x
num_entries += 1
if num_entries == 0:
print("You didn't enter any prime number")
else:
print("The average of the entered prime numbers is ", sum / num_entries)
I created a simple primality test algorithm, but it fails for numbers like 15. Why?
number = int(input("Test if Prime: "))
print ("Is " + str(number) + " Prime?: ")
for i in range (2, number):
if number % i == 0:
print ("No")
break
else:
print ("Yes")
I tried an elif statement with other variations, but it still doesn't work:
number = int(input("Test if Prime: "))
print ("Is " + str(number) + " Prime?: ")
for i in range (2, number):
if number % i == 0:
break
elif number % i != 0:
print ("Yes")
Any help is appreciated.
You have your else condition inside the loop. At any point in time, it'll only check for one value...
Modifying your for loop to print out the number it is checking for:
for i in range (2, number):
print (i)
if number % i == 0:
print ("No")
break
else:
print ("Yes")
prints out (for number = 15):
2
Yes
3
No
Which you know works if it prints out 'No' number - 1 times
To slightly modify what you did, we can just change it to:
flag = False
for i in range (2, number):
if number % i == 0:
print ("No")
flag = True
break
if (!flag)
print("Yes")
All this does is push the print statement outside the loop (for a number to be prime it needs to be non-divisible by all numbers less than it). The flag ensures that you only print out True or False (you don't want to print out both)
Here's a quick refactor I did based on your example:
def is_prime_simple(number):
is_prime = True
for i in range(2, number):
if number % i == 0:
is_prime = False
break
return is_prime
number = int(input("Test if Prime: "))
print ("Is " + str(number) + " Prime?: ")
print('Yes' if is_prime_simple(number) else 'No')
due to wrong indentation, else will be will executed for all non-divisors of odd numbers
for i in range (2, number):
if number % i == 0:
print ("No")
break
else:
print ("Yes")
My objective of the below code is
check if entered number is a prime
if not print the next biggest prime
def primetest (num):
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 any output.
Time comlexity of your code is O(N) when it find a number which is prime or not.
There is no pointing on dividing from 2 to len(num)-1. It is enough to loop from 2 to sqrt of the given number. Therefore time complexity reduce to O(n) to O(log(n)).
import math
num = int (input ("enter a number:"))
def primeTest(num):
isPrime = 0
for i in range(2,int(math.sqrt(num)+1)):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print(num, "is a prime number")
else:
num = num + 1
repeatTest(num)
def repeatTest (num):
isPrime = 0
for i in range(2,int(math.sqrt(num))):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print("Next Prime: ", num)
else:
num = num + 1
repeatTest(num)
primeTest(num)
The logic which you are using to find if a number if prime seems wrong .
Taking a integer like 9 prints "9 is a prime number" .
And also you are checking for next prime numbers from 2 to Num .
Num being the input , you cant get a number greater than that .
It exits from the loop without even getting in , therefore not printing anything when you are searching for next prime .
You need to change the logic .
write a separate function for checking prime and end the loop when you find the next prime number instead of stopping at num .
Question:
A program that take a positive integer n as input and returns True if n is a prime number, otherwise returns False.
My Answer:
n = int(input("Enter a number: "))
for i in range(2,n):
if n%i == 0:
print(False)
print(True)
when I enter a prime number it works but when I enter a non prime number it doesn't work.
Example:
>>>
Enter a number: 12
False
False
False
False
True
>>>
please help!
You can break and use else:
n = int(input("Enter a number: "))
for i in range(2, n):
if n % i == 0:
print(False)
break
else:
print(True)
True will only be printed if the loop completes fully i.e no n % i was equal to 0.
Your code always prints True at the end, and prints a number of Falses before that. Instead, you should have a variable (isPrime?) that gets initialized to True and gets set to False when you find it is divisible by something. Then print that variable at the end.
You're just printing each intermediate value, if you use return in a function it works fine
def prime(n):
for i in range(2, n):
if n%i == 0:
return False
return True
>>> prime(5)
True
>>> prime(12)
False
You could use the for-else clause here. Also, you don't need to go beyond the square root of n:
import math
for i in range(2, int(math.sqrt(n))):
if n % i == 0:
print "False"
break
else:
print "True"
There's a lot of different ways to fix your code, but all of them hinge on the fact that you should be breaking out of that loop if you find a divisor (ie if n%i == 0)
Usually, you'd have a boolean value storing whether or not you've found a divisor, but python lets you do the following
n = int(input("Enter a number: "))
for i in range(2,n):
if n%i == 0:
print(False)
break
else:
#else statement only happens if you don't break out of the loop
print(True)
Check out the algorithm here:
http://www.programiz.com/python-programming/examples/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")
If you encounter an i which gives modulo zero with n, then you have to print False and then do nothing. For this you can use a flag variable which takes care of this condition. If no such i is encountered, flag remains 1 and True is printed.
n = int(input("Enter a number: "))
flag = 1
for i in range(2,n):
if n%i == 0:
print(False)
flag = 0
break
if flag:
print(True)
check this one, it should make clear why the else statement is indented 'non conventionally':
num = int(input('Enter the maximum value: '))
for number in range(3, num+1):
#not_prime = False
for factor in range(2, number):
if number%factor == 0:
#not_prime = True
break
#if not_prime:
#continue
else:
print(number)
All of the above things are correct but I want to add thing that you should check for the condition of 1. if someone puts 1 as an integer you will have to return False. 1 is not prime
def prime_num(num):
if num <= 0:
return "the number is not primary"
for i in range(2, num - 1):
if num % i == 0:
return "The number is not primary, it can be divided: " + str(i)
return "The number: " + str(num) + " is primary"
This is one of the many ways to solve it:
def is_prime(num):
if (num == 2):
return True
elif any(x for x in range(2, num - 1) if (num % x == 0)):
return False
else:
return True