lib: add Int::factorial
authorJean Privat <jean@pryen.org>
Sat, 8 Nov 2014 03:34:17 +0000 (22:34 -0500)
committerJean Privat <jean@pryen.org>
Sat, 8 Nov 2014 03:58:09 +0000 (22:58 -0500)
Signed-off-by: Jean Privat <jean@pryen.org>

lib/standard/math.nit

index f6f5397..5a980aa 100644 (file)
@@ -91,6 +91,26 @@ redef class Int
        do
                return self.to_f.pow(e.to_f).to_i
        end
+
+       # The factorial of `self` (aka `self!`)
+       #
+       # Returns `1 * 2 * 3 * ... * self-1 * self`
+       #
+       #    assert 0.factorial == 1  # by convention for an empty product
+       #    assert 1.factorial == 1
+       #    assert 4.factorial == 24
+       #    assert 9.factorial == 362880
+       fun factorial: Int
+       do
+               assert self >= 0
+               var res = 1
+               var n = self
+               while n > 0 do
+                       res = res * n
+                       n -= 1
+               end
+               return res
+       end
 end
 
 redef class Float