Created
May 11, 2013 17:31
-
-
Save aeg/5560726 to your computer and use it in GitHub Desktop.
階乗を計算する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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