Update readme, create factorial_examples folder and move existing code into it
This commit is contained in:
parent
4a346e5dd9
commit
b786aa21a3
4 changed files with 2 additions and 1 deletions
37
factorial.c
37
factorial.c
|
@ -1,37 +0,0 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
uintmax_t factorial(uintmax_t n) {
|
||||
if(n < 2)
|
||||
return 1;
|
||||
return n * factorial(n-1);
|
||||
}
|
||||
|
||||
uintmax_t factorial_iter(uintmax_t n) {
|
||||
uintmax_t fact = 1;
|
||||
uintmax_t i = 2;
|
||||
while(i <= n) {
|
||||
fact *= i;
|
||||
i++;
|
||||
}
|
||||
return fact;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
size_t bufsize = 1024;
|
||||
char **lineptr = calloc(bufsize, sizeof(char));
|
||||
fputs("Enter number to factor: ", stdout);
|
||||
int err = getline(lineptr, &bufsize, stdin);
|
||||
if(err == -1) {
|
||||
puts("Error reading line from user input");
|
||||
return 1;
|
||||
}
|
||||
|
||||
uintmax_t user_input = abs(atoi(*lineptr));
|
||||
printf("\nRecursive factorial for number: %ju\n", factorial(user_input));
|
||||
printf("Iterative factorial for number: %ju\n", factorial_iter(user_input));
|
||||
free(lineptr);
|
||||
return 0;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue