開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7)のIV部(関数)のまとめ演習8.(素数)を解いてみる。
その他参考書籍
8.(素数)
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def isPrime_while(y):
x = y // 2
while x > 1:
if y % x == 0:
print("{0} has factor {1}".format(y, x))
break
x -= 1
else:
print("{0} is prime".format(y))
# for loop(とrange)を使った方がwhile loopより速い
def isPrime_for(n):
for x in range(int(n // 2), 1, -1):
if n % x == 0:
print("{0} has factor {1}".format(n, x))
break
else:
print("{0} is prime".format(n))
for n in [13, 13.0, 15, 15.0]:
isPrime_while(n)
import time
n = 11111111
for func in [isPrime_while, isPrime_for]:
start = time.time()
func(n)
print("{0}: {1}秒".format(func.__name__, time.time() - start))
入出力結果(Terminal)
$ ./sample.py 13 is prime 13.0 is prime 15 has factor 5 15.0 has factor 5.0 11111111 has factor 1010101 isPrime_while: 1.4564869403839111秒 11111111 has factor 1010101 isPrime_for: 1.0004630088806152秒 $
0 コメント:
コメントを投稿