You are not logged in. Please login at www.codechef.com to post your questions!

×

small factorials-why is this code a wrong answer?

#include<iostream>
using namespace std;
int main()
{ int t,j,i;
  int n[100];
  long double fact;
  cin>>t;

  if(t>=1 && t<=100)
  { for(i=1;i<=t;i++)
   { cin>>n[i];
   }
   for(i=1;i<=t;i++)
   { fact=1;
     if(n[i]>=1 && n[i]<=100)
     { for(j=1;j<=n[i];j++)
       { fact= fact*j;
       }
       cout<<fact<<endl;
     }
   }
 }
   return 0;
}

asked 21 Sep '14, 23:30

muskan9's gravatar image

0★muskan9
12
accept rate: 0%

edited 22 Sep '14, 00:03

kunal361's gravatar image

4★kunal361
6.0k133272


your algorithm is true only up to certain factorial like 19 after that overflow occurs and thus you encounter wrong answer, this is implemented using arrays storing each digit in an array, for eg: 123 can be stored in an array as a[0]=3,a1=2,a[2]=1 and so on... there is a tutorial to solve this problem. you can look at this tutorial to solve this problem. if you have any doubts after looking at this tutorial comment below. happy coding :)

link

answered 21 Sep '14, 23:55

pudge's gravatar image

2★pudge
758413
accept rate: 37%

1

I would like to suggest... http://discuss.codechef.com/questions/7349/computing-factorials-of-a-huge-number-in-cc-a-tutorial ...this is a very good tutorial written by @kuruma!!!

(21 Sep '14, 23:59) kunal3614★

Ohh...got it!! Thanks a lot! :)

link

answered 23 Sep '14, 21:14

muskan9's gravatar image

0★muskan9
12
accept rate: 0%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×163
×42
×5
×4

question asked: 21 Sep '14, 23:30

question was seen: 651 times

last updated: 23 Sep '14, 21:14