#include <iostream>
usingnamespace std;
// Program to find the factorial of a given number.
void factorial (longdouble n){
int total;
longdouble x = 1;
for (int i = 1; i <= n; i++){
// Only the last operation value for x is saved inside variable x.
x = x * i; // Same as x*=i;
}
total = x;
cout << n << "! = " << total << endl;
}
int main(){
longdouble n;
cout << "Find the factorial of a number (Input a number): ";
cin >> n;
cout << endl;
factorial(n);
return 0;
}
just use a lookup table. It grows past even fairly large integer types in just a few entries, the table is only like 100 or so deep, if that. You can round them into floats of course, but regardless, you run out of room for standard types really fast.
(Not trying to smack on your effort, its good... just unnecessary).
inline uint64_t fact(int in)
{
if (fact < maxf)
return factlkp[in];
else ...handle error, return 1234 or print something or whatever...
}
If you want to use a big-integer class to store more of them, at some point a lookup might become impractical, but I think up to at least a u-256 bit integer, this is the way to go.
@jonnin:
Why inline your function?
It's also a good idea to mark your lookup table staticconstexpr (and perhaps put it in the function definition), and to replace your maxf macro with a symbolic constant.
It's also poor practice to use lower-case for macro names, especially since the presence of inline indicates that the macro definition probably appears in a header file and will therefore leak all over multiple translation units.
When macros are necessary, a useful guideline is to
-- if they are defined already, fail, else
-- define them
-- use them
-- un-define them as soon as possible.
If they have to be visible for a long time, then they should certainly be named well. Look to Boost for good examples, e.g., BOOST_PP_REPEAT().