We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent be06cef commit c6f54dcCopy full SHA for c6f54dc
prime_number.py
@@ -14,3 +14,27 @@ def prime_num(num):
14
print(n, 'is a prime number')
15
16
prime_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)
0 commit comments