Hello Programmers, In this post, you will know how to solve the HackerRank Extra Long Factorials Solution. This problem is a part of the HackerRank Algorithms Series.
One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.
HackerRank Extra Long Factorials Solution
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
HackerRank Extra Long Factorials Solution
Extra Long Factorials Solution in C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int mult(int size,int res[],int x) { int carry=0,prod; for(int j=0;j<size;j++) { prod=res[j]*x+carry; res[j]=prod%10; carry=prod/10; } while(carry) { res[size]=carry%10; carry=carry/10; size++; } return size; } void fact(int n) { int i,size; int res[200]; res[0]=1; size=1; for(i=2;i<=n;i++) { size=mult(size,res,i); } for(i=size-1;i>=0;i--) printf("%d",res[i]); } int main() { int n; scanf("%d",&n); fact(n); /* Enter your code here. Read input from STDIN. Print output to STDOUT */ return 0; }
Extra Long Factorials Solution in Cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; string multiply(string &num1, string num2) { string res; int a, b, c, m, n, l, k, sum, carry; char d; m = num1.size() - 1; n = num2.size() - 1; carry = 0; for (int i = m; i >= 0; i--) { for (int j = n; j >= 0; j--) { l = res.size() - 1; a = num1[i] - '0'; b = num2[j] - '0'; k = (m-i) + (n-j); if (l >= k) c = res[l-k] - '0'; else c = 0; sum = a * b + c + carry; carry = sum / 10; d = char(sum % 10 + '0'); if (l >= k) res[l-k] = d; else res.insert(0, &d, 1); if (j == 0 && carry) { d = char(carry + '0'); res.insert(0, &d, 1); carry = 0; } } } return res[0] == '0' ? "0" : res; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n; cin >> n; string s = "1"; for (int i = 1; i <= n; ++i) { s = multiply(s, to_string(i)); } cout << s << endl; return 0; }
Extra Long Factorials Solution in Java
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static BigInteger factorial(int n){ BigInteger product=BigInteger.ONE; for(int i=2; i<=n; i++){ product= product.multiply(BigInteger.valueOf(i)); } return product; } public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc=new Scanner(System.in); System.out.println(factorial(sc.nextInt())); } }
Extra Long Factorials Solution in Python
import math import sys for linenum, testnum in enumerate(sys.stdin): if linenum >= 0: print math.factorial(int(testnum))
Extra Long Factorials Solution using JavaScript
function processData(input) { //Enter your code here var num = parseInt(input, 10); var result = new BigNum(input); while (num > 1) { --num; result = result.multiplyBy(new BigNum(num.toString())); } console.log(result.toString()); } var BigNum = function(num) { if (typeof num === 'string') { this.parts = []; while (num.length) { this.parts.push(parseInt(num.slice(-5),10)); num = num.substring(0,num.length-5) } } else { this.parts = num; } } BigNum.prototype.multiplyBy = function(bigNum) { var newParts = []; for (var i = 0, l1 = this.parts.length; i < l1; ++i) { for (var j = 0, l2 = bigNum.parts.length; j < l2; ++j) { var newPartIndex = i + j; newParts[newPartIndex] = this.parts[i] * bigNum.parts[j] + (newParts[newPartIndex] || 0); } } this._fixOverflows(newParts); return new BigNum(newParts); }; BigNum.prototype.add = function(bigNum) { var newParts = []; var length = Math.max(this.parts.length, bigNum.parts.length); for (var i = 0; i < length; ++i) { newParts[i] = (this.parts[i] || 0) + (bigNum.parts[i] || 0); } this._fixOverflows(newParts); return new BigNum(newParts); } BigNum.prototype._fixOverflows = function(parts) { for (var k = 0; k < parts.length; ++k) { var currentPart = parts[k].toString(); if (currentPart.length > 5) { var overflowLength = currentPart.length - 5; var overflow = parseInt(currentPart.substr(0, overflowLength), 10); parts[k] = parseInt(currentPart.substr(overflowLength), 10) parts[k + 1] = overflow + (parts[k + 1] || 0); } } } BigNum.prototype.toString = function() { var fullNumber = this.parts.map(function(num) { num = num.toString(); paddingAmount = 5 - num.length; for (var i = 0; i < paddingAmount; ++i) { num = '0' + num; } return num }).reverse().join(''); while( fullNumber.charAt(0) === '0' && fullNumber.length !== 1) { fullNumber = fullNumber.substring(1); } return fullNumber; }; process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); });
Extra Long Factorials Solution in Scala
object Solution { private def readLine: String = { scala.io.StdIn.readLine() } def main(args:Array[String]) = { val N = readLine.toInt def fact(k:Int, curr:BigInt) : BigInt = { if (k == 0) curr else fact(k - 1, curr * k) } println(fact(N, 1)) } }
Extra Long Factorials Solution in Pascal
var f:text; n:byte; s:ansistring; function cong(a,b:ansistring):ansistring; var i,n:longint; s:ansistring; begin while length(a)<length(b) do a:='0'+a; while length(b)<length(a) do b:='0'+b; n:=0; s:=''; for i:=length(a) downto 1 do begin s:=chr(((ord(a[i])+ord(b[i])+n-48*2)mod 10)+48)+s; n:=(ord(a[i])+ord(b[i])+n-48*2)div 10 end; if n=1 then s:='1'+s; exit(s) end; function nhan(s:ansistring; k:longint):ansistring; var x:ansistring; begin x:='0'; for k:=k downto 1 do x:=cong(x,s); exit(x) end; begin assign(f,''); reset(f); read(f,n); close(f); assign(f,''); rewrite(f); s:='1'; for n:=n downto 2 do s:=nhan(s,n); write(f,s); close(f) end.
Disclaimer: This problem (Extra Long Factorials) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.