Reputation: 21
in my program for finding a prime number, only the else statement gets displayed,even if the user enters a prime number. is there a problem in my if else statement? or in some mathematical operator? i have tried to indent it properly by python syntax. and please rectify the code.
num=int(input("enter a number : "))
ctr=0
i=1
for i in range(1,num):
if(num%i==0):
ctr+=1
if(ctr==2):
print(num," is prime")
else:
print(num," is not prime")
Upvotes: 0
Views: 79
Reputation: 9192
If you're still having trouble, try using the following function:
def isprime(number):
if number == 1:
return False
for i in range(2,int(number**0.5)+1):
if number%i==0:
return False
return True
To use it type isprime(number)
and replace number
with the number which you want to check.
Upvotes: 0
Reputation: 49813
When the user enters a prime for n
, it is only divisible by 1 and itself. But range(1,n)
never gets to n
, so ctr
is 1 for prime numbers, not 2.
Upvotes: 2