image.png
分析:
分析边界条件: n为1, 直接返回1即可。
状态转移方程:
n为奇数: f(n) = f(n * 3 + 1)
n为偶数: f(n) = f(n / 2)
代码:
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
void print_procedures(int n) {
if (n == 1) {
return;
}
if (n % 2 != 0) {
printf("%d*%d+1=%d\n", n, 3, n * 3 + 1);
print_procedures(n * 3 + 1);
}
else {
printf("%d/%d=%d\n", n, 2, n / 2);
print_procedures(n / 2);
}
}
void solve(int n) {
print_procedures(n);
}
int main(int argc, char const *argv[])
{
int n;
scanf("%d", &n);
solve(n);
return 0;
}
运行结果:image.png