+ 1

Is this code practical and efficient enough to detect prime number?

num = int(input("enter a positive integer: ")) if num > 1 and num != 2 : for di in range(2,num): if num % di == 0: print("it isn't a prime number.") exit() print("it is a prime number.") elif num == 2: print("it is a prime number.") else: print("please enter a positive integer")

14th Mar 2020, 3:35 AM
bamboo
bamboo - avatar
4 Respuestas
+ 3
Yes this code works perfectly. But for large inputs, it will take a huge amount of time so it is better to check for prime number till square root of that number. It will decrease the number of times the loop is running and hence saves time without compromising the correct answer
14th Mar 2020, 3:45 AM
Arsenic
Arsenic - avatar
+ 2
After the square root of n, there will be repetition by inversion. n = 100 5*20==100 10*10==100 (sqrt) 20*5==100 (we had this already)
14th Mar 2020, 4:34 AM
HonFu
HonFu - avatar
+ 2
that helps a lot!
14th Mar 2020, 4:35 AM
bamboo
bamboo - avatar
+ 1
Thank you!But I don't get the point that why we take the square root of it instead of dividing it by half.
14th Mar 2020, 3:52 AM
bamboo
bamboo - avatar