Skip to content
  • Home
  • Contact Us
  • About Us
  • Privacy Policy
  • DMCA
  • Linkedin
  • Pinterest
  • Facebook
thecscience

TheCScience

TheCScience is a blog that publishes daily tutorials and guides on engineering subjects and everything that related to computer science and technology

  • Home
  • Human values
  • Microprocessor
  • Digital communication
  • Linux
  • outsystems guide
  • Toggle search form
HackerRank Extra Long Factorials Problem Solution

HackerRank Extra Long Factorials Problem Solution

Posted on April 16, 2023April 16, 2023 By Yashwant Parihar No Comments on HackerRank Extra Long Factorials Problem Solution

In this post, We will solve HackerRank Extra Long Factorials Problem Solution.

The factorial of the integer n, written n!, is defined as:
n! = n x (n-1) x (n-2) x x3x2 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 265252859812191058636308480000000.
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 Problem Solution
HackerRank Extra Long Factorials Problem Solution

Table of Contents

  • Extra Long Factorials C Solution
  • Extra Long Factorials C++ Solution
  • Extra Long Factorials C Sharp Solution
  • Extra Long Factorials Java Solution
  • Extra Long Factorials JavaScript Solution
  • Extra Long Factorials Python Solution

Extra Long Factorials C Solution

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

#define MaxC    200

char O[MaxC];
char S[MaxC];
char T[MaxC];

void Asd(int d1, int d2, int c1, char *o, int *c2) {
    int Sum;
    
    Sum = d1 + d2 + c1;
    
    *o = (Sum % 10) + 0x30;
    *c2 = (Sum / 10);
}

void Msd(int d1, int d2, int c1, char *o, int *c2) {
    int Sum;
    
    Sum = (d1 * d2) + c1;
    
    *o = (Sum % 10) + 0x30;
    *c2 = (Sum / 10);
}

void DoFactorial(int i) {
    int o, c;
    
    if (i == 100) {
        o = 2;
        while (o < MaxC-2) {
            O[o-2] = O[o];
            o++;
        }
        O[MaxC-3] = '0';
        O[MaxC-2] = '0';
    }
    else {     
        o = MaxC-2;
        c = 0;
        while (O[o] != ' ') {
            Msd(O[o]-0x30, i%10, c, S+o, &c);
            o--;
        }
    
        if (c > 0) S[o] = c + 0x30;
    
        if (i>9) {
            o = MaxC-2;
            c = 0;
            while(O[o] != ' ') {
                Msd(O[o]-0x30, i/10, c, T+o-1, &c);
                o--;
            }
    
            if (c > 0) T[o-1] = c + 0x30;
        }
    
        o = MaxC-2;
        c = 0;
        while ((S[o] != ' ') || (T[o] != ' ')) {
            if (S[o] == ' ')
                Asd(0, T[o]-0x30, c, O+o, &c);
            else
                if (T[o] == ' ')
                    Asd(S[o]-0x30, 0, c, O+o, &c);
                else
                    Asd(S[o]-0x30, T[o]-0x30, c, O+o, &c);
            o--;
        }
    
        if (c > 0) O[o] = c + 0x30;
    
    }
}

int main() {
    int n, i;
    
    for (i=0; i<MaxC-2; i++) {
        O[i] = ' ';
        S[i] = ' ';
        T[i] = ' ';
    }
    O[MaxC-2] = '1';
    S[MaxC-2] = '0';
    T[MaxC-2] = '0';
    O[MaxC-1] = 0;
    S[MaxC-1] = 0;
    T[MaxC-1] = 0;
    
    scanf("%d", &n);
    
    for (i=1; i<=n; i++) {
        DoFactorial(i);
    }
    
    i=0;
    while (O[i] == ' ') {
        i++;
    }    
    printf("%s", O+i);
    
 #if 0  
    i=0;
    while (S[i] == ' ') {
        i++;
    } 
    printf("\n%s", S+i);
    
    i=0;
    while (T[i] == ' ') {
        i++;
    }
    printf("\n%s", T+i); 
#endif
    
    return 0;
}

Extra Long Factorials C++ Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int number[300] = {};
    int n = 0;
    cin >> n;
    number[0] = 1;
    int len = 1;
    for (int i = 2; i <= n; ++i) {
        for (int pos = 0, r = 0; pos < len || r != 0; ++pos) {
            if (pos < len)
                r += number[pos] * i;
            else
                ++len;
            number[pos] = r % 10;
            r /= 10;
        }
    }
    for (int i = len - 1; i >= 0; --i)
        cout << number[i];
    return 0;
}

Extra Long Factorials C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
class Solution {
    
      private static string Add(string first, string second)
        {
            var split = 0;
            if (first.Length < second.Length)
            {
                var s = new StringBuilder();
                s.Append('0', second.Length - first.Length);
                s.Append(first);
                first = s.ToString();
            }
            if (second.Length < first.Length)
            {
                var s = new StringBuilder();
                s.Append('0', first.Length - second.Length);
                s.Append(second);
                second = s.ToString();
            }
            var ret = new StringBuilder();

            for (int i = first.Length - 1; i >= 0; i--)
            {
                var rr = int.Parse(first[i].ToString()) + int.Parse(second[i].ToString()) + split;

                split = int.Parse(rr.ToString("00")[0].ToString());
                ret.Append(rr.ToString("00")[1]);
            }

            ret.Append(split);

            return new string(ret.ToString().ToCharArray().Reverse().ToArray());
        }

        private static string mul(string first, string second)
        {
            var ret = new string('0', first.Length);

            for (int i = second.Length - 1; i >= 0; i--)
            {
                var b = new StringBuilder();
                b.Append(mul(first, int.Parse(second[i].ToString())));
                b.Append('0', second.Length - 1 - i);

                ret = Add(ret, b.ToString());
            }
            var r = new StringBuilder();


            return ret.TrimStart('0');

        }

        private static string mul(string first, int second)
        {

            var split = 0;

            var ret = new StringBuilder();

            for (int i = first.Length-1; i >= 0; i--)
            {
                var rr = int.Parse(first[i].ToString()) * second+split;

                split = int.Parse(rr.ToString("00")[0].ToString());
                ret.Append(rr.ToString("00")[1]);
            }

            ret.Append(split);

            return new string(ret.ToString().ToCharArray().Reverse().ToArray());
        }    
    static void Main(String[] args) {
             var inp = int.Parse(Console.ReadLine());

            string ret = inp.ToString();
            for (int i = inp - 1; i > 0; i--)
            {
                ret = mul(ret, i.ToString());
                //Console.WriteLine(ret);
                
            }

            Console.WriteLine(ret);
        
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
    }
}

Extra Long Factorials Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.math.BigInteger;

class Result {

    /*
     * Complete the 'extraLongFactorials' function below.
     *
     * The function accepts INTEGER n as parameter.
     */

    public static void extraLongFactorials(int n) {
        BigInteger sum=new BigInteger("1");
    for(int i=1;i<n+1;i++){
        sum=sum.multiply(BigInteger.valueOf(i));
    }
    System.out.println(sum);

    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        Result.extraLongFactorials(n);

        bufferedReader.close();
    }
}

Extra Long Factorials JavaScript Solution

function processData(input) {
    //Enter your code here
    input
    var res = 1
    for (var i = 1; i <= input; i++) {
        res = mult(res.toString(), i.toString())
    }
    process.stdout.write(res)
    function mult(num1,num2){
        var a1 = num1.split("").reverse();
        var a2 = num2.split("").reverse();
        var aResult = new Array;

        for ( iterNum1 = 0; iterNum1 < a1.length; iterNum1++ ) {
            for ( iterNum2 = 0; iterNum2 < a2.length; iterNum2++ ) {
                idxIter = iterNum1 + iterNum2;	// Get the current array position.
                aResult[idxIter] = a1[iterNum1] * a2[iterNum2] + ( idxIter >= aResult.length ? 0 : aResult[idxIter] );

                if ( aResult[idxIter] > 9 ) {	// Carrying
                    aResult[idxIter + 1] = Math.floor( aResult[idxIter] / 10 ) + ( idxIter + 1 >= aResult.length ? 0 : aResult[idxIter + 1] );
                    aResult[idxIter] -= Math.floor( aResult[idxIter] / 10 ) * 10;
                }
            }
        }
        return aResult.reverse().join("");
    }

} 

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 Python Solution

import math

case = int(input())

print(math.factorial(case))

other solutions

  • HackerRank Append and Delete Problem Solution
  • HackerRank Sherlock and Squares Solution
c, C#, C++, HackerRank Solutions, java, javascript, python Tags:C, cpp, CSharp, Hackerrank Solutions, java, javascript, python

Post navigation

Previous Post: HackerRank Find Digits Problem Solution
Next Post: HackerRank Append and Delete Problem Solution

Related Posts

HackerRank Quadrant Queries Problem Solution HackerRank Quadrant Queries Problem Solution c
HackerRank Equalize the Array Problem Solution HackerRank Equalize the Array Problem Solution c
HackerRank Dijkstra: Shortest Reach 2 Problem Solution HackerRank Dijkstra: Shortest Reach 2 Solution c
HackerRank Minimum Loss Problem Solution HackerRank Minimum Loss Problem Solution c
HackerRank Palindromic Border Problem Solution HackerRank Palindromic Border Problem Solution c
HackerRank Sherlock and The Beast Problem Solution HackerRank Sherlock and The Beast Solution c

Leave a Reply Cancel reply

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

Pick Your Subject
Human Values

Copyright © 2023 TheCScience.

Powered by PressBook Grid Blogs theme