Skip to content

Commit 97df875

Browse files
authored
Create Day9-Recursion3.c
1 parent d372ee8 commit 97df875

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/* Sample Input
2+
3+
3
4+
Sample Output
5+
6+
6
7+
8+
9+
Function Description
10+
Complete the factorial function in the editor below. Be sure to use recursion.
11+
12+
factorial has the following paramter:
13+
int n: an integer
14+
15+
Returns
16+
int: the factorial of n
17+
*/
18+
19+
#include <assert.h>
20+
#include <limits.h>
21+
#include <math.h>
22+
#include <stdbool.h>
23+
#include <stddef.h>
24+
#include <stdint.h>
25+
#include <stdio.h>
26+
#include <stdlib.h>
27+
#include <string.h>
28+
29+
char* readline();
30+
31+
// Complete the factorial function below.
32+
int factorial(int n) {
33+
static int fact=1;
34+
while(n!=0)
35+
{
36+
fact=fact*n;
37+
38+
39+
return factorial(n-1);}
40+
return fact;
41+
}
42+
43+
int main()
44+
{
45+
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
46+
47+
char* n_endptr;
48+
char* n_str = readline();
49+
int n = strtol(n_str, &n_endptr, 10);
50+
51+
if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }
52+
53+
int result = factorial(n);
54+
55+
fprintf(fptr, "%d\n", result);
56+
57+
fclose(fptr);
58+
59+
return 0;
60+
}
61+
62+
char* readline() {
63+
size_t alloc_length = 1024;
64+
size_t data_length = 0;
65+
char* data = malloc(alloc_length);
66+
67+
while (true) {
68+
char* cursor = data + data_length;
69+
char* line = fgets(cursor, alloc_length - data_length, stdin);
70+
71+
if (!line) { break; }
72+
73+
data_length += strlen(cursor);
74+
75+
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }
76+
77+
size_t new_length = alloc_length << 1;
78+
data = realloc(data, new_length);
79+
80+
if (!data) { break; }
81+
82+
alloc_length = new_length;
83+
}
84+
85+
if (data[data_length - 1] == '\n') {
86+
data[data_length - 1] = '\0';
87+
}
88+
89+
data = realloc(data, data_length);
90+
91+
return data;
92+
}

0 commit comments

Comments
 (0)