Skip to content

Instantly share code, notes, and snippets.

@clojj
Created Nov 7, 2018
Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <factorial.h>
/* Calculates max and allocate table. Returns !0 if
* memory could not be allocated.
*/
int factorial_table_init(factorial_table *t)
{
unsigned i, factorial;
t->max = factorial = 1;
while (INT_MAX / factorial > t->max + 1)
factorial *= ++t->max;
t->table = malloc((t->max + 1)*sizeof(unsigned));
if (!t->table) return !0;
t->table[0] = 1;
for (i = 1; i <= t->max; i++)
t->table[i] = i * t->table[i-1];
fprintf(stdout,"A factorial table was just allocated.\n");
return 0;
}
/* Uses a table to get the factorial of an integer number n. Returns
* (-1) if n is negative and (-2) if n is too big.
*/
int factorial_get(factorial_table *t, int n)
{
if (n < 0) return (-1);
if (n > t->max) return (-2);
return t->table[n];
}
/* Frees the table we used. */
void factorial_table_free(factorial_table *t)
{
free(t->table);
fprintf(stdout,"A factorial table was just freed.\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment