質問するログイン新規登録

回答編集履歴

3

edit

2018/09/05 14:45

投稿

mkgrei
mkgrei

スコア8562

answer CHANGED
@@ -46,4 +46,64 @@
46
46
 
47
47
  print(ps)
48
48
  print(len(ps))
49
+ ```
50
+
51
+ いろいろと悲しみしかなかったといっておく…
52
+
53
+ ```python
54
+ import time
55
+ from math import sqrt
56
+
57
+ def timer(func):
58
+ def itimer(*args, **kwargs):
59
+ st = time.time()
60
+ ret = func(*args, **kwargs)
61
+ print(time.time() - st)
62
+ return ret
63
+ return itimer
64
+
65
+ N = 10000
66
+
67
+ @timer
68
+ def f():
69
+ ps = [2]
70
+
71
+ def is_prime_countup(num, ps):
72
+ l = sqrt(num)
73
+ for p in ps:
74
+ if num % p == 0:
75
+ return False
76
+ if p > l:
77
+ return True
78
+ return True
79
+
80
+ i = 3
81
+ while len(ps) < N:
82
+ if is_prime_countup(i, ps):
83
+ ps.append(i)
84
+ i += 1
85
+
86
+ return ps
87
+
88
+ @timer
89
+ def g():
90
+ ps = [2]
91
+
92
+ def is_not_prime_countup(num, ps):
93
+ l = sqrt(num)
94
+ return any(num % p == 0 for p in ps if p <= l)
95
+
96
+ i = 3
97
+ while True:
98
+ if not is_not_prime_countup(i, ps):
99
+ ps.append(i)
100
+ if len(ps) == N:
101
+ break
102
+ i += 1
103
+
104
+ return ps
105
+
106
+ ansf = f()
107
+ ansg = g()
108
+ assert all(i == j for i, j in zip(ansf, ansg))
49
109
  ```

2

edit

2018/09/05 14:45

投稿

mkgrei
mkgrei

スコア8562

answer CHANGED
@@ -24,4 +24,26 @@
24
24
 
25
25
  print(ps)
26
26
  print(len(ps))
27
+ ```
28
+
29
+ 気持ち高速化してみる。
30
+
31
+ ```python
32
+ from math import sqrt
33
+ ps = [2]
34
+
35
+ def is_not_prime_countup(num, ps):
36
+ l = sqrt(num)
37
+ return any(num % p == 0 for p in ps if p <= l)
38
+
39
+ i = 3
40
+ while True:
41
+ if not is_not_prime_countup(i, ps):
42
+ ps.append(i)
43
+ if len(ps) == 5000:
44
+ break
45
+ i += 1
46
+
47
+ print(ps)
48
+ print(len(ps))
27
49
  ```

1

edit

2018/09/05 14:26

投稿

mkgrei
mkgrei

スコア8562

answer CHANGED
@@ -1,4 +1,27 @@
1
1
  https://ja.m.wikipedia.org/wiki/エラトステネスの篩
2
2
 
3
3
  普通はこういうのを使います。
4
- for文とif文で書けますよ。
4
+ for文とif文で書けますよ。
5
+
6
+ ---
7
+
8
+ 参考程度に。本当にあってるかな…
9
+
10
+ ```python
11
+ ps = [2]
12
+
13
+ def is_prime_countup(num, ps):
14
+ for p in ps:
15
+ if num % p == 0:
16
+ return False
17
+ return True
18
+
19
+ i = 3
20
+ while len(ps) < 2000:
21
+ if is_prime_countup(i, ps):
22
+ ps.append(i)
23
+ i += 1
24
+
25
+ print(ps)
26
+ print(len(ps))
27
+ ```