[Tutor] Program to find if a number entered by user is a prime number or not
Manprit Singh
manpritsinghece at gmail.com
Fri Oct 16 02:01:22 EDT 2020
Dear sir ,
So now i have two ways :
First way :
_________________________________
x = int(input("Enter a number"))
if x < 2 or any(x % i == 0 for i in range(2, int(x**0.5) + 1)):
print(x,"is not a prime number")
else:
print(x,"is a prime number")
Second way :
______________________________________
x = int(input("Enter any positive number"))
if all(x%i for i in range(2, int(x**0.5) + 1)) and x >= 2:
print(x," is prime")
else:
print(x,"is not prime")
What to prefer ?
Regards
Manprit Singh
On Fri, Oct 16, 2020 at 7:19 AM Manprit Singh <manpritsinghece at gmail.com>
wrote:
> Dear sir,
> If i simply write this program as given below:
>
> x = int(input("Enter any positive number"))
> a = "not prime"
> if all(x%i for i in range(2, int(x**0.5) + 1)):
> if x >= 2:
> a = "prime"
> print(x,"is",a)
>
> Will it be ok ?
>
> On Fri, Oct 16, 2020 at 7:00 AM Manprit Singh <manpritsinghece at gmail.com>
> wrote:
>
>> Dear Sir ,
>>
>> I was trying to write a program which allows the user to input a number
>> from a keyboard , it then prints the message x is prime if number input by
>> user is a prime number and x is not prime if the number input by user is
>> not a prime number. (here x represents the number). The program is written
>> below:
>>
>> x = int(input("Enter any positive number"))
>> a = "not prime"
>> if all(x%i for i in range(2, int(x**0.5) + 1)):
>> if x < 2:
>> pass
>> else:
>> a = "prime"
>> else:
>> pass
>> print(x,"is",a)
>>
>> I have these questions in my mind :
>> 1) If you can see I have used pass two times , Initially I have assigned
>> a string "not prime" to variable a . Now if user input is either 0 or 1 ,
>> it is not a prime number. That's why i have written a pass inside the
>> below written block, which will maintain a = 'not prime" when user input
>> is either 0 or 1.
>>
>> if all(x%i for i in range(2, int(x**0.5) + 1)):
>> if x < 2:
>> pass
>> for any value of user input greater than 1 if the iterable inside all( )
>> is empty or all(x%i for i in range(2, int(x**0.5) + 1)) return True , the
>> user input for sure is a prime number , and hence i have assigned a =
>> "prime" inside that block.
>>
>> Again for the second time i have used pass when all(x%i for i in range(2,
>> int(x**0.5) + 1)) returns False, in that case the number input by user is
>> again not a prime number , and hence i have used pass again in the block to
>> maintain the old value of variable a ="not prime".
>>
>> Just need to know if my way of implementing the problem is correct ? Can
>> this program be further optimised ?
>>
>> Regards
>> Manprit Singh
>>
>>
>>
>>
More information about the Tutor
mailing list