Skip to content

Instantly share code, notes, and snippets.

@aeg
Created May 11, 2013 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeg/5560726 to your computer and use it in GitHub Desktop.
Save aeg/5560726 to your computer and use it in GitHub Desktop.
階乗を計算する
// Case #1
// 階乗(n!)を計算する(再帰バージョン)
def BigInteger fact(n) {
if (n == 0) return 1
return n * fact(n - 1)
}
// 4! = 24
assert fact(4) == 24
// Case#2
// 階乗(n!)を計算する(再帰使わないバージョン)
def BigInteger fact2(n) {
BigInteger result = 1
while(n > 0) {
result *= n--
}
return result
}
// 4! = 24
assert fact2(4) == 24
// Case #3
// 1〜20の階乗を表示してみる
(1..20).each{
println "${it}!= ${fact(it)}"
}
/* 結果は
1!= 1
2!= 2
3!= 6
4!= 24
5!= 120
6!= 720
7!= 5040
8!= 40320
9!= 362880
10!= 3628800
11!= 39916800
12!= 479001600
13!= 6227020800
14!= 87178291200
15!= 1307674368000
16!= 20922789888000
17!= 355687428096000
18!= 6402373705728000
19!= 121645100408832000
20!= 2432902008176640000
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment