Skip to content

Instantly share code, notes, and snippets.

@glapa-grossklag
Created November 13, 2021 01:06
Show Gist options
  • Save glapa-grossklag/b3339fba783182c0ea3a3ddf9984174f to your computer and use it in GitHub Desktop.
Save glapa-grossklag/b3339fba783182c0ea3a3ddf9984174f to your computer and use it in GitHub Desktop.
GMP Factorial
#include <gmp.h>
#include <stdio.h>
#include <stdlib.h>
/**
* Compute the factorial of `n` and store it in `f`.
*/
void factorial(mpz_t f, mpz_t n) {
// f ← 1
mpz_set_ui(f, 1);
// for i ∈ [2, n]:
// f ← f × i
mpz_t i;
mpz_init(i);
for (mpz_set_ui(i, 2); mpz_cmp(i, n) <= 0; mpz_add_ui(i, i, 1)) {
mpz_mul(f, f, i);
}
mpz_clear(i);
return;
}
/**
* Prompt the user for `n` and print the factorial of `n`.
*/
int main(void) {
// What is n?
mpz_t n;
mpz_init(n);
printf("n = ");
gmp_scanf("%Zd", n);
// Calculate factorial(n).
mpz_t f;
mpz_init(f);
factorial(f, n);
// Print factorial(n).
gmp_printf("%Zd! = %Zd\n", n, f);
// Free memory.
mpz_clear(n);
mpz_clear(f);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment