Small factorials - C code

what is wrong in this code??

#include<stdio.h>
int main()
{
long int t,n,fact=1,i;
scanf("%d",&t);
for(n=0;n<=t;n++)
{
scanf("%d",&n);
for(i=n;i>=1;i++)

fact= i*fact;

printf("%d\n",fact);
}
return 0;
}

@ishan412, here are some of your mistakes :

  1. your code is running into infinite loop in the second for loop for(i=n;i>=1;i++ ) in this case i will always be greater than 1 so the loop never stops running. You need to decrement the value of i.

  2. you have to declare fact = 1 for each test case otherwise it will compute the result using the previous value.

  3. after the above corrections your code will give wrong answer for n>20 because the value of factorial will be larger than 1018 so no data type in c/c++ can store such large number. Therefore to avoid this problem you need to use character array or string.

Read here - Tutorial for computing factorials of very large numbers.

Hope this helps.

1 Like

#include<stdio.h>
int main()
{
int t,i,n[100],f=1,j=1;
for(i=0;i<t;i++)
{
scanf("%d",&n[i]);
while(j<=n[i])
{
f=f*j;
j++;
}
printf("%d\n",f);
}
return 0;
}
can someone tell me whats wrong with the code?

Read the above editorial and try to understand.

Okay Thanks

Check this out editorial Extra Long Factorials | HackerRank .

import java.util.Scanner ;
class codechef{
int facto(int n){
int fact=1;
for(int i=1;i<=n;i++)
fact=fact*i;
return fact;
}
public static void main(String[] args){
codechef cc=new codechef();
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
if((1<=t)&&(t<=100))
for(int i=1;i<=t;i++){
int n=sc.nextInt();
if((1<=n)&&(n<=100))
System.out.println( cc.facto(n));
}
}
}

can someone say what’s wrong with my code ?

//C++ solution
#include<bits/stdc++.h>
using namespace std;
int fact(int n)
{
int res;
for(int i=1;i<=n;i++)
{
res*=i;
}
return res;
}
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
int num;
cin>>num;
cout<<fact(num)<<endl;
}

by using this code you can’t able to find factorial of 99 so just use this one

#include
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
using namespace std;
cpp_int fact(int n)
{
//long long unsigned int temp=1;
cpp_int temp=1;
if(n==0||n==1)
return 1;

while(n!=0)
{
    temp=temp*n;
    n--;
}
return temp;

}
int main() {
int n,a;
cin>>n;
//long long unsigned int arr[n];
for(int i=0;i<n;i++)
{
cin>>a;
cout<<fact(a)<<endl;
}
return 0;
}