開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のIV部(関数)のまとめ演習8(素数)を解いてみる。
その他参考書籍
8.
コード(TextWrangler)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- def prime(n): if n <= 1: raise Exception("{0}: 2以上の整数を指定してください。".format(n)) a = n // 2 while a > 1: if n % a == 0: print("{0} has factor {1}".format(n, a)) break a -= 1 else: print("{0} is prime".format(n)) for x in range(-1, 15): try: prime(x) except Exception as err: print(err) for x in [13.0, 15.0]: try: prime(x) except Exception as err: print(err)
入出力結果(Terminal)
$ ./sample.py -1: 2以上の整数を指定してください。 0: 2以上の整数を指定してください。 1: 2以上の整数を指定してください。 2 is prime 3 is prime 4 has factor 2 5 is prime 6 has factor 3 7 is prime 8 has factor 4 9 has factor 3 10 has factor 5 11 is prime 12 has factor 6 13 is prime 14 has factor 7 13.0 is prime 15.0 has factor 5.0 $
ちなみにJavaScriptの場合。
コード(TextWrangler)
function prime(n){ if(n <= 1) throw n + ": 2以上の数を指定してください。"; label:{ for(var a = Math.floor(n / 2); a > 1; a--){ if(n % a == 0){ $('#pre0').append(n + " has factor " + a + "\n"); break label; } } $('#pre0').append(n + " is prime\n"); } } for(var i = -1 ; i < 15; i++){ try{ prime(i); } catch(e){ $('#pre0').append(e + "\n"); } } prime(13.0); prime(15.0);
0 コメント:
コメントを投稿