開発環境
- 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(練習問題)5を解いてみる。
その他参考書籍
5.
コード(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 + 1)){
push @divisors, $_ unless $number % $_;
}
push @divisors, $number;
@divisors;
}
given($ARGV[0]){
when(/\D/){ print "エラー: 数値を指定してください\n";}
my $fav = 10;
my @divisors = divisors $_;
when(2 ~~ @divisors){print "偶数\n"; continue;}
when(!(2 ~~ @divisors)){print "奇数\n"; continue;}
when( $fav ~~ @divisors ){ print "好きな数${fav}の倍数\n"; continue;}
when([$_] ~~ @divisors){print "素数\n";}
print "約数一覧: @divisors\n";
}
入出力結果(Terminal)
$ ./sample.pl empty at ./sample.pl line 9. $ ./sample.pl perl エラー: 数値を指定してください $ ./sample.pl 10 偶数 好きな数10の倍数 約数一覧: 2 5 10 $ ./sample.pl 11 奇数 素数 $ ./sample.pl 12 偶数 約数一覧: 2 3 4 6 12 $ ./sample.pl 13 奇数 素数 $ ./sample.pl 14 偶数 約数一覧: 2 7 14 $ ./sample.pl 15 奇数 約数一覧: 3 5 15 $ ./sample.pl 20 偶数 好きな数10の倍数 約数一覧: 2 4 5 10 20 $
ちなみにJavaScriptの場合。
コード(BBEdit)
var result = "";
function divisors(n){
divs = [];
for(var i = 2; i <= n / 2 + 1; i++){
if(n % i === 0) divs.push(i);
}
divs.push(n);
return divs;
}
var n = parseInt($('#t0').val());
var fav = parseInt($('#t1').val());
var divs = divisors(n);
if(divs[0] === 2){
result += "偶数\n";
} else {
result += "奇数\n";
}
for(var i = 0; i < divs.length; i++){
if(divs[i] === fav){
result += "好きな数" + fav + "の倍数\n";
}
}
if(divs.length === 1){
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 + 2):
if n % x == 0: divs.append(x)
divs.append(n)
return divs
fav = 10
try:
n = int(sys.argv[1])
if n < 2:
print("2以上の整数を指定してください")
sys.exit()
divs = divisors(n)
if 2 in divs:
print("偶数")
else:
print("奇数")
if fav in divs: print("好きな数の倍数")
if divs == [n]:
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 10 偶数 好きな数の倍数 約数一覧: 2 5 10 $ ./sample.py 11 奇数 素数 $ ./sample.py 12 偶数 約数一覧: 2 3 4 6 12 $ ./sample.py 13 奇数 素数 $ ./sample.py 14 偶数 約数一覧: 2 7 14 $ ./sample.py 15 奇数 約数一覧: 3 5 15 $ ./sample.py 20 偶数 好きな数の倍数 約数一覧: 2 4 5 10 20 $
0 コメント:
コメントを投稿