[Tutor] Program to find if a number entered by user is a prime number or not

Alan Gauld alan.gauld at yahoo.co.uk
Fri Oct 16 04:44:44 EDT 2020


On 16/10/2020 07:01, Manprit Singh wrote:
> 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 ?

Provided you move the x >=2 test to the front of the all() then
there should not be any difference in them.
Pick whichever seems the most readable solution.

Or, if you want to be sure, test them both for speed and pick the
fastest. (I would hope there would be no significant difference!)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list