c - Cannot calculate factorials bigger than 20! ! How to do so? -
i using unsigned long long integer format in order calculate big factorials. code fails @ point can have @ it? part of larger code taylor expansion of exponential function, part irrelevant @ point. appreciate suggestions.
thanks
#include <stdio.h> #include <math.h> //we need write factorial function beforehand, since //have factorial in denominators. //remembering factorials defined integers; //possible define factorials of non-integer numbers using //gamma function omit that. //we first declare factorial function follows: unsigned long long factorial (int); //long long integer format allows numbers in order of 10^18 //we shall use sign bit in order increase our range. //now define it, unsigned long long factorial(int n) { //here s free parameter increased 1 in each step , //pro initial product , setting pro 0 cover //case of 0 factorial. int s = 1; unsigned long long pro = 1; if (n < 0) printf("factorial not defined negative number \n"); else { while (n >= s) { printf("%d \n", s); pro *= s; s++; printf("%llu \n", pro); } return pro; } } int main () { int x[12] = { 1, 5, 10, 15, 20, 100, -1, -5, -10, -20, -50, -100}; //here array named "calc" defined store //the values of x. unsigned long long k = factorial(25); printf("%llu \n", k); //int k; ////the upper index controls accuracy of taylor series, ////it suitable make adjustable parameter. //int p = 500; //for ( k = 0; k < p; k++); }
the limit on unsigned long long 18446744073709551615, or 1.8e+19. 20! 2.4e+18, within range, 21! 5.1e+19, exceeding maximum size of unsigned long long.
you may find helpful: are there types bigger long long int in c++?
Comments
Post a Comment