Skip to content

Instantly share code, notes, and snippets.

@NSG650
Created January 12, 2023 04:21
Show Gist options
  • Save NSG650/97fc860fe59d58c3ce97c38b64aca413 to your computer and use it in GitHub Desktop.
Save NSG650/97fc860fe59d58c3ce97c38b64aca413 to your computer and use it in GitHub Desktop.
very fast factorial function
#include <stdint.h>
#include <stddef.h>
// An uint64_t can't hold more than 18446744073709551616 and 21! is very huge
// just store a table of these values upto 20
static uint64_t factorial_table[21] = {
1,
1,
2,
6,
24,
120,
720,
5040,
40320,
362880,
3628800,
39916800,
479001600,
6227020800,
87178291200,
1307674368000,
20922789888000,
355687428096000,
6402373705728000,
121645100408832000,
2432902008176640000
};
uint64_t factorial_return(int n) {
if (n > 20 || n < 0)
return -1; // uint64_t max lmao
return factorial_table[n];
}
@kenan238
Copy link

"just use a lookup table itll be faster"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment