-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter4.c
198 lines (164 loc) · 2.08 KB
/
chapter4.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#include "simpio.h"
#include "genlib.h"
#include "strlib.h"
#include "random.h"
#include <string.h>
#include <stdio.h>
// Question 1
int Cannonball(unsigned n)
{
if (n == 1)
{
return n;
}
else
{
return n*n + Cannonball(n - 1);
}
}
// Question 2
int RaiseIntToPower(int n, int k)
{
if (n == 1)
{
return 1;
}
else if (k == 0)
{
return 1;
}
else
{
return n * RaiseIntToPower(n, k - 1);
}
}
// Question 3
int gcd(int x, int y)
{
if (x % y == 0)
{
return y;
}
else
{
return gcd(y, x % y);
}
}
// Question 4
int Fib_Iter(int n)
{
int n0 = 0;
int n1 = 1;
int ret = 0;
for (int i = 0; i < n; i++)
{
int temp = n1;
n1 = n0 + n1;
n0 = temp;
}
ret = n0;
return ret;
}
// Question 5
static count1 = 0;
static count2 = 0;
int CountFib1(int n)
{
count1++;
if (n < 2)
{
return n;
}
else
{
return CountFib1(n - 1) + CountFib1(n - 2);
}
}
int AdditiveSequence(int n, int t0, int t1)
{
count2++;
if (n == 0)
{
return t0;
}
else if (n == 1)
{
return t1;
}
else
{
return AdditiveSequence(n - 1, t1, t0 + t1);
}
}
int CountFib2(int n)
{
return AdditiveSequence(n, 0, 1);
}
// Question 6
int DigitSum(int n)
{
if (n < 10)
{
return n;
}
else
{
return n % 10 + DigitSum(n / 10);
}
}
// Question 7
int DigitRoot(int n)
{
if (n < 10)
{
return n;
}
else
{
return DigitRoot(DigitSum(n));
}
}
// Question 8
int PascalFactorial(int n, int k)
{
if (n == k || k == 0)
{
return 1;
}
else
{
return PascalFactorial(n - 1, k - 1) + PascalFactorial(n - 1, k);
}
}
// Question 9
string ReverseString(string str, int n)
{
if (n == 0)
{
return str;
}
else
{
return Concat(CharToString(IthChar(str, n)), ReverseString(SubString(str, 0, n - 1), n - 1));
}
}
string Reverse(string str)
{
int len = StringLength(str);
return ReverseString(str, len);
}
// Question 10
#define ASCII_DIGIT_BEGIN 48
string MyIntegerToString(int n)
{
if (n < 10)
{
return CharToString(n + ASCII_DIGIT_BEGIN);
}
else
{
return Concat(MyIntegerToString(n / 10), CharToString(n % 10 + ASCII_DIGIT_BEGIN));
}
}
// Question 11
// 略