Introduction

This is my blog of programming, I take notes and leave codes of computer science problems I solved here. Be my guest to comment :)

Wednesday, January 30, 2013

uva 100 - The 3n + 1 problem

/*
Problem link
Type: Adhoc
Algorithm: Straight forward 
*/ 
 1  #include <iostream>
 2  #include <cmath>
 3  using namespace std;
 4  
 5  long long cycle(long long n);
 6  
 7  int main()
 8  {
 9      //freopen("input.inp","r",stdin);
10      //freopen("output.out","w",stdout);
11      while (!cin.eof())
12      {
13          int a,b,aa,bb,
14              result = 0;
15          cin >> a >> b;
16          if (cin.eof()) break;
17          aa = a; bb = b;
18          if (a>b) swap(a,b);
19          for (int i=a; i<=b; i++)
20              if (cycle(i)>result) result = cycle(i);
21          cout << aa << " " << bb << " " << result << endl;
22      }
23      return 0;
24  }
25  
26  long long cycle(long long n)
27  {
28      long long result = 1;
29      while (n!=1)
30      {
31          if (n%2==0) n/=2;
32          else n = 3*n+1;
33          result++;
34      }
35      return(result);
36  }

No comments:

Post a Comment