top1编程
← 返回题目
题解

角谷猜想

1 条题解

  • 0
    @ 2026-7-29 20:22:30
    #include <iostream>
    using namespace std;
    //f(n)是n变为1所需要的次数
    //找递归出口f(1) = 0,也就是不需要再变换了
    //如果n是奇数 f(n) = 1 + f(3 * n + 1)
    //如果n是偶数 f(n) = 1 + f(n / 2)
    // 1 +  表示这一步需要变换,剩下的交给f()自己计算
    int f(int n) {
    	if (n == 1) return 0;
    	else if (n % 2 == 0) {
    		return 1 + f(n / 2);
    	} else {
    		return 1 + f(3 * n + 1);
    	}
    }
    int main() {
    	int n;
    	cin >> n;
    	cout << f(n);
    }
    
    • 1