File tree Expand file tree Collapse file tree 1 file changed +24
-0
lines changed
Expand file tree Collapse file tree 1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change @@ -14,3 +14,27 @@ def prime_num(num):
1414 print (n , 'is a prime number' )
1515
1616prime_num (n )
17+
18+
19+ ##optimal version
20+
21+ import math
22+
23+ def prime_num (num ):
24+ if num < 2 :
25+ return # No prime numbers less than 2
26+
27+ print (2 , "is a prime number" ) # 2 is the only even prime number
28+
29+ for n in range (3 , num + 1 , 2 ): # Check only odd numbers
30+ is_prime = True
31+ #If n is not divisible by any number up to its square root, it is prime. This reduces the number of iterations significantly.
32+ for x in range (3 , int (math .sqrt (n )) + 1 , 2 ): # Check divisibility up to sqrt(n)
33+ if n % x == 0 :
34+ is_prime = False
35+ break
36+ if is_prime :
37+ print (n , "is a prime number" )
38+
39+ # Example usage
40+ prime_num (20 )
You can’t perform that action at this time.
0 commit comments