Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Read input and implement factorial
function (recursive or imperative) using Big Integer if desired language does not support automatic conversion to Big Integers by default.
I created solution in 3 languages:
Normally, I implement a solution also in JavaScript. But my solution for this problem is not correct. Large numbers use scientific notation. After trying to format I have had problem with decimal precision.
All solutions are also available on my GitHub.
Scala
1 2 3 4 5 6 7 8 9 10 |
object ExtraLongFactorials extends App { def factorial(n: BigInt): BigInt = { if(n < 1) 1 else n * factorial(n - 1) } val n = io.Source.stdin.bufferedReader().readLine().toInt; println(factorial(n)) } |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.math.BigInteger; import java.util.Scanner; public class ExtraLongFactorials { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); BigInteger n = stdin.nextBigInteger(); System.out.println(factorial(n)); } private static BigInteger factorial(BigInteger n) { if(n.compareTo(BigInteger.ONE) <= 0) { return BigInteger.ONE; } else { return n.multiply(factorial(n.subtract(BigInteger.ONE))); } } } |
Ruby
1 2 3 4 5 6 7 8 9 10 |
n = gets.to_i; def factorial(n) if n <= 1 return 1 end return n * factorial(n - 1) end puts factorial(n) |