UVA 一星題筆記(4)100 The 3n+1 Problem

Sharon Peng
2 min readSep 26, 2019

--

也是不會太難的題目,但不知道為什麼就是很難寫出來,結果換一種方式就成功了,這就是程式的奧妙吧~

題目大意如下:

有一種算法是下面這樣

所以要照著這種算法,然後看這個數字要經過多少次計算會得到1。

題目想要,輸入兩個數字,並找到兩個數字間經過這神奇的計算的最大值(比其他數字計算後都大)

解題步驟:

  1. 知道要怎麼算出神奇算式
  2. 讓他從範圍裡面一個一個做計算,然後比大小。

簡單程式碼:

我自己是包了一個函式去做計算,因為原本沒有包都跑不動(我也不知道為什麼)

while(cin >> num1)
{
cin >> num2;
int big = 0, small = 0;
// who is bigger than the other one
if(num1 > num2)
{
big = num1;
small = num2;
} else
{
big = num2;
small = num1;
}
int temp = 0, max = 0;
for(int i = small; i <= big; ++i)
{
temp = count(i);
if(max < temp)
max = temp;
}

cout << num1 << " " << num2;
cout << " " << max << endl;
}
int count(int num1)
{
int count = 1;
while(num1 != 1)
{
count++;
if(num1 % 2 == 0)
num1 /= 2;
else
{
num1 = num1 * 3 + 1;
}
}
return count;
}

--

--

Sharon Peng
Sharon Peng

No responses yet