## Weird Algorithm [題目連結](https://cses.fi/problemset/task/1068) 給定一整數 $n$,如果 $n$ 是偶數就 $\div 2$ ,如果 $n$ 是奇數就 $\times 3-1$ 直到 $n = 1$ 請輸出 $n$ 到 $1$ 的過程比如 $n = 3 \rightarrow 3\ 10\ 5\ 16\ 8\ 4\ 2\ 1$ --- 題目標籤 : 迴圈、判斷 本題提示 : ```cpp= while (???) { // 直到 ??? 之前都要持續運算 if (n % 2 == ???) { // n 是奇數或偶數? ??? } else { // n 是另一種情況 ??? } } ``` 解題思路 : 題目說從 $n$ 到 $1$ 的過程作運算,可以理解成還沒到 $1$ 之前都要重複運算 重複直到變成 $1$,這樣其實就跟 while 迴圈一樣,所以運算過程包在 while 裡面 題目還有說偶數與奇數的不同處理方法,這裡用 if 去判斷偶數或是奇數即可 ```cpp= #include<bits/stdc++.h> using namespace std ; typedef long long LL ; int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0) ; LL n ; cin >> n ; cout << n << ' ' ; while (n != 1) { // 沒變成 1 之前都重複運算 if (n % 2 == 1) // 奇數 n = n*3 + 1 ; else // 偶數 n /= 2 ; cout << n << ' ' ; } return 0 ; } ``` ### 心得(可跳過) 這其實是一個數學的猜想,至今還沒被證明,但是已經證明比題目範圍還大很多的情況了 就是在證明範圍內的所有數字最後都會變成 $1$,最後都會進入 $4\ 2\ 1$ 的輪迴
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.