Initial commit
This commit is contained in:
commit
4a346e5dd9
3 changed files with 58 additions and 0 deletions
1
README.md
Normal file
1
README.md
Normal file
|
@ -0,0 +1 @@
|
||||||
|
Some example factorial functions in various programming languages
|
37
factorial.c
Normal file
37
factorial.c
Normal file
|
@ -0,0 +1,37 @@
|
||||||
|
#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;
|
||||||
|
}
|
20
factorial.py
Normal file
20
factorial.py
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
def factorial(n: int) -> int:
|
||||||
|
if n < 2:
|
||||||
|
return n
|
||||||
|
else:
|
||||||
|
return n * factorial(n-1)
|
||||||
|
|
||||||
|
def factorial_iter(n: int) -> int:
|
||||||
|
fact = 1
|
||||||
|
# Grab absolute value to ensure n is a positive integer
|
||||||
|
n = abs(n)
|
||||||
|
for i in range(2, n+1):
|
||||||
|
fact *= i
|
||||||
|
return fact
|
||||||
|
|
||||||
|
user_input = int(input("Insert number to calculate factorial for: "))
|
||||||
|
|
||||||
|
# Avoid recursion limit
|
||||||
|
if user_input < 1000:
|
||||||
|
print(f"Recursive factorial {user_input}: {factorial(user_input)}")
|
||||||
|
print(f"Iterative factorial {user_input}: {factorial_iter(user_input)}")
|
Loading…
Add table
Add a link
Reference in a new issue