開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- Script言語:Perl
『初めてのPerl 第6版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2012年、ISBN978-4-87311-567-2) の15章(スマートマッチとgiven-when)、15.6(練習問題)4を解いてみる。
その他参考書籍
4.
コード(BBEdit)
sample.pl
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.016;
binmode STDOUT, ':utf8';
binmode STDIN, ':utf8';
die "empty" unless defined $ARGV[0];
sub divisors{
my $number = shift;
my @divisors = ();
for(2..($number / 2)){
push @divisors, $_ unless $number % $_;
}
@divisors;
}
given($ARGV[0]){
when(/\D/){ print "エラー: 数値を指定してください\n";}
my @divisors = divisors $_;
when(@divisors ~~ []){print "素数\n";}
print "約数一覧: @divisors\n";
}
入出力結果(Terminal)
$ ./sample.pl empty at ./sample.pl line 9. $ ./sample.pl perl エラー: 数値を指定してください $ ./sample.pl 2 素数 $ ./sample.pl 3 素数 $ ./sample.pl 4 約数一覧: 2 $ ./sample.pl 5 素数 $ ./sample.pl 6 約数一覧: 2 3 $ ./sample.pl 7 素数 $ ./sample.pl 8 約数一覧: 2 4 $ ./sample.pl 9 約数一覧: 3 $ ./sample.pl 10 約数一覧: 2 5 $ ./sample.pl 100 約数一覧: 2 4 5 10 20 25 50 $
ちなみにJavaScriptの場合。
コード(BBEdit)
var result;
function divisors(n){
divs = [];
for(var i = 2; i <= n / 2; i++){
if(n % i === 0) divs.push(i);
}
return divs;
}
var n = parseInt($('#t0').val());
var divs = divisors(n);
if(divs.length === 0){
result = "素数";
} else {
result = "約数一覧(その数自身を除く): " + divs;
}
$('#pre0').text(result);
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
import sys
def divisors(n):
divs = []
for x in range(2, n // 2 + 1):
if n % x == 0: divs.append(x)
return divs
try:
n = int(sys.argv[1])
if n < 2:
print("2以上の整数を指定してください")
sys.exit()
divs = divisors(n)
if divs == []:
print("素数")
else:
print("約数一覧(その数自身を除く): {0}".format(" ".join(map(str, divs))))
except Exception as err:
print(err)
入出力結果(Terminal)
$ ./sample.py list index out of range $ ./sample.py python invalid literal for int() with base 10: 'python' $ ./sample.py 1 2以上の整数を指定してください $ ./sample.py 2 素数 $ ./sample.py 3 素数 $ ./sample.py 4 約数一覧(その数自身を除く): 2 $ ./sample.py 5 素数 $ ./sample.py 6 約数一覧(その数自身を除く): 2 3 $ ./sample.py 7 素数 $ ./sample.py 8 約数一覧(その数自身を除く): 2 4 $ ./sample.py 9 約数一覧(その数自身を除く): 3 $ ./sample.py 10 約数一覧(その数自身を除く): 2 5 $ ./sample.py 100 約数一覧(その数自身を除く): 2 4 5 10 20 25 50 $
0 コメント:
コメントを投稿