Small Factorials | CodeChef Solution

Today we will be solving Small Factorial CodeChef problem in Python, Java and C++ whose Code is FCTRL2.

small-factorials-codechef-solution-codebrosindia

Contents

Problem

You are asked to calculate factorials of some small positive integers.

Input

An integer t, 1<=t<=100, denoting the number of test cases, followed by t lines, each containing a single integer n, 1<=n<=100.

Output

For each integer n given at input, display a line with the value of n!

Example

Input

4
1
2
5
3

Output

1
2
120
6

Solution – Small Factorials CodeChef Solution

Python

#Solution provided by CodingBroz 
def factorial(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return n * factorial(n - 1)
n = int(input())
for i in range(n):
    num = int(input())
    print(factorial(num))

Java

/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
/* Name of the class has to be "Main" only if the class is public. */

class Codechef
{
   public static void main (String[] args) throws IOException
	{
		final BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		final int t = Integer.parseInt(bf.readLine());
		for(int i=0 ;i<t ;i++)
		{
		    System.out.println(fact(Integer.parseInt(bf.readLine())));
		}
	}
	private static BigInteger fact(int n)
    {
        BigInteger result = BigInteger.ONE;
        for(int i=2;i<=n;i++)
        {
            result = result.multiply(BigInteger.valueOf(i));
        }
        return result;
    }
}
Small Factorials CodeChef Solution in Java

C++

#include <iostream>
using namespace std;

int main()
{
	// your code goes here
	int t;
	cin>>t;
	for(int i=0;i<t;i++){
	    int num;
	    cin>>num;
	    int size=1000,nfact[size],carry=0,j=size-1;
	    nfact[size-1]=1;
	    while(num>1)
	    {
	        int x;
	        for(int k=size-1;k>=j;k--)
	        {
	            x=nfact[k]*num + carry;
	            nfact[k]=x%10;
	            carry=x/10;
	        }
	        while(carry>0)
	        {
	            nfact[--j]=carry%10;
	            carry/=10;
	        }
	        num--;
	    }
	        for(int k=j;k<size;k++){
	            cout<<nfact[k];
	        }
	        cout<<endl;
	}
	return 0;
}
Small Factorials CodeChef Solution

Disclaimer: The above problem (Small Factorials: FCTRL2) is generated by CodeChef but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning Purposes.

Broz Who Code

CodingBroz

Leave a Comment

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