# 3n+1 問題 https://neoj.sprout.tw/problem/801/ ### Problem Description "考拉茲猜想"是指對於每一個正整數 n ,如果它是奇數,則對它乘3再加1,如果它是偶數,則對它除以2,如此循環,最終都能夠得到1。 例如: n = 6,得到序列6, 3, 10, 5, 16, 8, 4, 2, 1,共需要8個步驟。 現在,請聰明的你計算一下,給定一個正整數,計算出它得到1所需的步驟數。 ### I/O Format #### Input 輸入的第一行有一個整數n 。 保證 0<n<100 #### Output 請輸出一行包含一個整數,循環進行操作,得到1所需的步驟數。 ### Sample I/O #### Sample Input 1 ``` 6 ``` #### Sample Output 1 ``` 8 ``` ### Reference [考拉茲猜想](https://zh.wikipedia.org/wiki/%E8%80%83%E6%8B%89%E5%85%B9%E7%8C%9C%E6%83%B3) # Code ```cpp #include <iostream> using namespace std; int main(){ int X, n = 0; cin >> X; while (X != 1) { if (X == 1) break; n = n + 1; if ((X % 2) != 0) X = 3 * X + 1; else X = X / 2; } cout << n; }
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up