Small Factorials Codechef Solution

Hello coders, today we are going to solve Small Factorials Codechef Solution. Which is a part of Codechef Solution.

Small Factorials Codechef Solution
Small Factorials Codechef Solution

Problem

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

Input

An integer t, 1<=t<=100, denoting the number of testcases, 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

Sample Input

4
1
2
5
3

Sample Output

1
2
120
6

Small Factorials CodeChef Solution in Python

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))

Small Factorials CodeChef Solution in CPP

#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 in JAVA

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;
    }
}

Disclaimer: The above Problem (Small Factorials) is generated by  CodeChef but the solution is provided by Chase2learn.This tutorial is only for Educational and Learning purpose.

Sharing Is Caring

Leave a Comment