hello i am just starting in cpp
i am trying to find factorial of 99
i used unsigned long to store it but it shows the result as zero can any one tell me what sort of data type i should use to get the proper result
thanz in advance
hello i am just starting in cpp
i am trying to find factorial of 99
i used unsigned long to store it but it shows the result as zero can any one tell me what sort of data type i should use to get the proper result
thanz in advance
Try using floats or doubles. They behave quite differently from ints since they are floating point datatypes but i think it's the easiest way to accomplish what you are trying to
You could try using the GNU Multiple Precision Arithmetic Library.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
99! has 156 digits:
And I don't know of any datatype able to store THAT many.Code:933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000
It comes out as zero because unsigned long on a 32-bit machine is 4294967296 and 99! % 4294967296 == 0
Code:99! == 4294967296 (ie 2 ^ 32) * 217292028115932253845267088283474325413620025535071318663174668083008378728362535147325750384844183656977717580337132695715840000000000000000000000
Even on a 64-bit machine:
Code:99! == 18446744073709551616 (ie 2 ^ 64) * 50592242767087242995683822846849059083876205965660353811265590619996278250674376065685821321058129811887097912919040000000000000000000000
Option #1: Use double, but forego accuracy.
Option #2: Use a bignum library like GMP or Apfloat.
Option #3: Accept the fact that n! for n > 33 will always return 0
Code:#include <stdio.h> void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){ puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9 /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i] ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][ t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}