-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathisPrime.py
More file actions
23 lines (20 loc) · 1021 Bytes
/
isPrime.py
File metadata and controls
23 lines (20 loc) · 1021 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Define a function that takes an integer argument and returns a logical value true or false depending on if the integer is a prime.
# Per Wikipedia, a prime number ( or a prime ) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
# Requirements
# You can assume you will be given an integer input.
# You can not assume that the integer will be only positive. You may be given negative numbers as well ( or 0 ).
# NOTE on performance: There are no fancy optimizations required, but still the most trivial solutions might time out. Numbers go up to 2^31 ( or similar, depending on language ). Looping all the way up to n, or n/2, will be too slow.
# Example
# is_prime(1) /* false */
# is_prime(2) /* true */
# is_prime(-1) /* false */
from math import sqrt
def is_prime(num):
if num==2 or num==3:
return True
if num%2==0 or num<2:
return False
for n in range(3,int(num**0.5)+1,2):
if num%n==0:
return False
return True