2020年4月6日 星期一

4.1-Collatz_Conjecture-Lab

解題心得:
典型的3N+1問題。

程式碼:
#include <iostream>
using namespace std;

int main() {
 int a, b;
 while (cin >> a >> b)
 {
  int maxCycleLength = 0, cycleLength = 0, n;
  cout << a << " " << b << " ";
  if (a > b)
   swap(a, b);
  for (int i = a; i <= b; i++)
  {
   n = i;
   cycleLength = 1;
   while (n != 1)
   {
    if (n % 2) // even
     n = 3 * n + 1;
    else //odd
     n = n / 2;
    cycleLength++;
   }
   maxCycleLength = cycleLength > maxCycleLength ? cycleLength : maxCycleLength;
  }
  cout << maxCycleLength << endl;
 }
    return 0;
}

沒有留言:

張貼留言