How can I write a program to find the factorial of any natural number?
A closed form is an expression that can be computed by applying a fixed number of familiar operations to the arguments. For example, the expression 2 + 4 + … + 2n is not a closed form, but the expression n(n+1) is a closed form. " = a1 +L+an .
To find the factorial of a number, multiply the number with the factorial value of the previous number. For example, to know the value of 6! multiply 120 (the factorial of 5) by 6, and get 720. For 7!
An equation is said to be a closed-form solution if it solves a given problem in terms of functions and mathematical operations from a given generally-accepted set. For example, an infinite sum would generally not be considered closed-form.
A closed expression (or closed formula) refers to a formula that has no free variables [1]. This is also called sentence.
This will work for the factorial (although a very small subset) of positive integers:
unsigned long factorial(unsigned long f) { if ( f == 0 ) return 1; return(f * factorial(f - 1)); } printf("%i", factorial(5));
Due to the nature of your problem (and level that you have admitted), this solution is based more in the concept of solving this rather than a function that will be used in the next "Permutation Engine".
This calculates factorials of non-negative integers[*] up to ULONG_MAX, which will have so many digits that it's unlikely your machine can store a whole lot more, even if it has time to calculate them. Uses the GNU multiple precision library, which you need to link against.
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <gmp.h> void factorial(mpz_t result, unsigned long input) { mpz_set_ui(result, 1); while (input > 1) { mpz_mul_ui(result, result, input--); } } int main() { mpz_t fact; unsigned long input = 0; char *buf; mpz_init(fact); scanf("%lu", &input); factorial(fact, input); buf = malloc(mpz_sizeinbase(fact, 10) + 1); assert(buf); mpz_get_str(buf, 10, fact); printf("%s\n", buf); free(buf); mpz_clear(fact); }
Example output:
$ make factorial CFLAGS="-L/bin/ -lcyggmp-3 -pedantic" -B && ./factorial cc -L/bin/ -lcyggmp-3 -pedantic factorial.c -o factorial 100 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
[*] If you mean something else by "number" then you'll have to be more specific. I'm not aware of any other numbers for which the factorial is defined, despite valiant efforts by Pascal to extend the domain by use of the Gamma function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With