Extra Long Factorials

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:


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));
	 * 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) ****
		// **** generate and print factorial (recursive) ****

		// **** close scanner ****

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.



Follow me on Twitter:  @john_canessa

One thought on “Extra Long Factorials”

Leave a Reply

Your email address will not be published. Required fields are marked *