+ 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")
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
+ 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)
+ 2
that helps a lot!
+ 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.