Reputation: 321
I'm new to programming, I need to know if it's possible to print a string like "This is a prime number" if there were no results for i
n = int(input("Digite um número inteiro positivo: "))
for i in range(2,n):
if n % i == 0:
print(i)
For example if I typed 5 Nothing show up
If I typed 8 it would show 2 and 4
How can I add a print(n,"is a prime number") if NOTHING shows up in the program? I couldn't find any command for that
Upvotes: 0
Views: 106
Reputation: 7
You could also set the range of the loop to only check values from 2 to n//2 because anything past that would be unnecessary for checking if prime.
def isPrime(n):
for i in range(2,**n//2**):
if n % i == 0:
return 'This number is not Prime.'
else:
return 'This number is Prime.'
def main():
user = int(input('Enter a number to check primeness: '))
print(isPrime(user))
main()
Upvotes: 0
Reputation: 489
def isPrime(num):
for i in range(2, num):
if num % i == 0:
return False
return True
def getFactors(n):
myList = []
for i in range(2, n):
if n % i == 0:
myList.append(i)
return myList
num = 17
num2 = 20
if isPrime(num):
print("prime")
else:
print(getFactors(17))
if isPrime(num2):
print("prime")
else:
print(getFactors(num2))
Upvotes: 0
Reputation: 1
A crude way to do it would be adding something like a counter which checks the number of factors.
n=int(input("Digite um número inteiro positivo:"))
counter=0
for i in range(2,n):
if(n%i==0):
print(i)
counter+=1
if(counter==0):
print "n is prime"
Upvotes: 0
Reputation: 22544
n = int(input("Digite um número inteiro positivo: "))
printed = False
for i in range(2,n):
if n % i == 0:
print(i)
printed = True
if not printed:
print(n,"is a prime number")
This uses a "flag" variable to show if a value was printed.
Upvotes: 2