Factorial of a number in C++

Feb 5, 2017 at 2:50am
Personal contribution to open source C++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

using namespace std;

// Program to find the factorial of a given number.
void factorial (long double n){
    int total;
    long double 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(){

    long double n;
    cout << "Find the factorial of a number (Input a number): ";
    cin >> n;
    cout << endl;
    factorial(n);

    return 0;
}
Last edited on Feb 5, 2017 at 3:21am
Feb 5, 2017 at 3:00am
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).
Last edited on Feb 5, 2017 at 3:06am
Feb 5, 2017 at 3:19am
sharp eyes! :D
Yeah after you said that I realized oh I forgot about it. It is updated now.

Thanks for letting me know.
Feb 5, 2017 at 4:50pm
//I grabbed the values off the web really fast, hopefully they are correct but you get the point.

#define maxf 20 //if you want 0!
const uint64_t factlkp[maxf] = {1,1,2,6,24,120,720,5040,
40320,362880,3628800,39916800,479001600,6227020800,87178291200,
1307674368000,20922789888000,355687428096000,
6402373705728000,121645100408832000};

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.


Last edited on Feb 5, 2017 at 5:01pm
Feb 5, 2017 at 7:37pm
Nice! Thanks :)
Feb 5, 2017 at 8:14pm
@jonnin:
Why inline your function?
It's also a good idea to mark your lookup table static constexpr (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().
Topic archived. No new replies allowed.