#include <stdio.h>
#include <stdlib.h>
struct Stack {
int capacity;
int top;
int* array;
};
struct Stack* createStack(unsigned capacity) {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
return stack;
}
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
int isFull(struct Stack* stack) {
return stack->top == stack->capacity - 1;
}
void push(struct Stack* stack, int item) {
if (isFull(stack)) {
return;
}
stack->array[++stack->top] = item;
}
int pop(struct Stack* stack) {
if (isEmpty(stack)) {
return -1;
}
return stack->array[stack->top--];
}
long long int factorial(int n) {
if (n <= 1) {
return 1;
}
struct Stack* stack = createStack(n);
long long int result = 1;
while (n > 1) {
push(stack, n);
n--;
}
while (!isEmpty(stack)) {
result *= pop(stack);
}
free(stack);
return result;
}
int main(void) {
int num;
printf("insert num: ");
scanf("%d", &num);
if (num < 0) {
printf("negative cant be calculated.\n");
} else {
long long int result = factorial(num);
printf("factorial(%d): %lld\n", num, result);
}
return 0;
}