Extra Long Factorials – HackerRank Solution

In this post, we will solve Extra Long Factorials HackerRank Solution. This problem (Extra Long Factorials) is a part of HackerRank Algorithms series.

Task

The factorial of the integer n, written n!, is defined as:

n! = n x (n – 1) x (n – 2) x . . . x 3 x 2 x 1

Calculate and print the factorial of a given integer.

For example, if n = 30, we calculate 30 x 29 x 28 x . . . x 2 x 1 and get 26525285981219105636308480000000.

Function Description

Complete the extraLongFactorials function in the editor below. It should print the result and return.

extraLongFactorials has the following parameter(s):

  • n: an integer

Note: Factorials of n > 20 can’t be stored even in a 64 – bit long long variable. Big integers must be used for such calculations. Languages like Java, Python, Ruby etc. can handle big integers, but we need to write additional code in C/C++ to handle huge values.

We recommend solving this challenge using BigIntegers.

Input Format

Input consists of a single integer n

Constraints

  • 1 <= n <= 100

Output Format

Print the factorial of n.

Sample Input

25

Sample Output

15511210043330985984000000

Explanation

25! = 25 x 24 x 23 x . . . x 3 x 2 x 1

Solution – Extra Long Factorials – HackerRank Solution

C++

#include<iostream>
#include<stdio.h>
using namespace std;

int main(void)
{
    int i=0,j=0,fact[20000],k=0,l=0,n=0,temp=0;

    fact[0]=1;
    l=1;
 
   cin>>n;
    for(i=2;i<=n;i++)
    {
        for(j=0;j<l;j++)
        {
            k=temp+i*fact[j];
            fact[j]=k%10;
            temp=k/10;
        }
        while(temp>0)
        {
            fact[l++]=temp%10;
            temp=temp/10;
        }
    }
    for(i=l-1;i>-1;i--)
    cout<<fact[i];

    return 0;
}

Python

#!/bin/python3
# this should work

import sys
from math import factorial

def extraLongFactorials(n):
    return factorial(n)
    

if __name__ == "__main__":
    n = int(input().strip())
    print(extraLongFactorials(n))

Java

import java.io.*;
import java.util.*;
import java.math.BigInteger;

public class Solution {

    public static void main(String[] args) {
        int N,i;
            Scanner in=new Scanner(System.in);
            N=in.nextInt();
        BigInteger res=BigInteger.ONE;
       for(i=2;i<=N;i++){
       res = res.multiply(BigInteger.valueOf(i));
 
}
        System.out.println(res);
    }
}

Note: This problem (Extra Long Factorials) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published.