I took a look at the Extra Long Factorials at the HackerRank web site. If interested take a look at the requirements.
The challenge is to print the factorial for a number in the range 1 <= N <= 100. I used Java 8 to solve the challenge.
A screen capture of the console of the Eclipse IDE using the test data follows:
25 15511210043330985984000000 15511210043330985984000000
Note that I have two answers instead of one. The reason is that I implemented the solution using a loop strategy and then implemented a second one using a recursion approach. In general I like to implement solutions using loops because they are more efficient conserving resources (less memory stack) and do not have the issue of running out of stack which will cause an exception. Of course in this case there is no concern about such issue given the range for N.
I only submitted the loop version to HackerRank.
My complete code in Java 8 follows:
import java.math.BigInteger; import java.util.Scanner; public class Solution { /** * Factorial recursive. */ static BigInteger factorialRecursive(int N) { if (N <= 1) { return new BigInteger("1"); } else { return BigInteger.valueOf(N).multiply(factorialRecursive(N - 1)); } } /** * Generate and print factorial for specified number. */ static void factorial(int N) { BigInteger factorial = new BigInteger("1"); for (int n = 1; n <= N; n++) { factorial = factorial.multiply(BigInteger.valueOf(n)); } System.out.println(factorial.toString()); } /** * Test code. */ public static void main(String[] args) { // **** open scanner **** Scanner sc = new Scanner(System.in); // **** **** int N = sc.nextInt(); // **** generate and print factorial (loop) **** factorial(N); // **** generate and print factorial (recursive) **** System.out.println(factorialRecursive(N)); // **** close scanner **** sc.close(); } }
The code passed the 12 test cases.
If you have comments or questions regarding this or any other entry in this blog, please do not hesitate and send me a message. Will try to respond ASAP and will not use your name unless you explicitly allow me to do so.
John
john.canessa@gmail.com
Follow me on Twitter: @john_canessa
Thank you. I was tired searching for this solution
Hi Harini,
You are welcome.
John