Posted By

dirkchang on 03/02/11


Tagged


Versions (?)

The 3n + 1 problem


 / Published in: C++
 

  1. /*
  2.  * 3np1.cpp
  3.  *
  4.  * Created on: Feb 14, 2011
  5.  * Author: dirk
  6.  */
  7.  
  8. #include <iostream>
  9. #include <algorithm>
  10.  
  11. inline unsigned cycle_len(unsigned n) {
  12. unsigned c = 1;
  13. while( n != 1 ) {
  14. if( n % 2 ) n = 3 * n + 1;
  15. else n = n / 2;
  16. ++c;
  17. }
  18. return c;
  19. }
  20.  
  21. int main(int argc, char **argv) {
  22. unsigned i(0), j(0), max(0), start(0), end(0);
  23.  
  24. while (std::cin >> i) {
  25. std::cin >> j;
  26.  
  27. max = 0;
  28. if(i < j) {
  29. start = i;
  30. end = j;
  31. }
  32. else {
  33. start = j;
  34. end = i;
  35. }
  36. for(unsigned x = start; x <= end; ++x) {
  37. max = std::max(max, cycle_len(x));
  38. }
  39. std::cout << i << ' ' << j << ' ' << max << '\n';
  40. }
  41. }

Report this snippet  

You need to login to post a comment.