-
Notifications
You must be signed in to change notification settings - Fork 1k
/
is_prime.py
66 lines (51 loc) · 1 KB
/
is_prime.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#! /usr/bin/env python
#coding:utf-8
"""
判断一个数是否为素数的几种方法
"""
#方法一
import math
def isPrime1(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
#方法二
def isPrime2(n):
if n <= 1:
return False
i = 2
while i*i <= n:
if n % i == 0:
return False
i += 1
return True
#方法三
from itertools import count
def isPrime3(n):
if n <= 1:
return False
for i in count(2):
if i * i > n:
return True
if n % i == 0:
return Fals
#方法四
def isPrime4(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
if __name__=="__main__":
a=isPrime4(5)
print a