Chinaunix首页 | 论坛 | 博客
  • 博客访问: 239820
  • 博文数量: 47
  • 博客积分: 1229
  • 博客等级: 中尉
  • 技术积分: 568
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-20 10:06
文章分类

全部博文(47)

文章存档

2014年(1)

2013年(7)

2012年(1)

2011年(38)

分类: C/C++

2011-03-04 23:41:47

The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.
--------------------
  1. #include <stdio.h>


  2. inline long long unsigned next(long long unsigned num)
  3. {
  4.     if (num%2)
  5.         return 3*num + 1;
  6.     else
  7.         return num >> 1;
  8. }


  9. int main(int argc, const char *argv[])
  10. {
  11.     long long unsigned result = 0;
  12.     long long unsigned count;
  13.     long long unsigned num;
  14.     int i, mi;
  15.     
  16.     for (i=2; i<1000000; i++) {
  17.         num = i;
  18.         count = 0;
  19.         while (num != 1) {
  20.             num = next(num);
  21.             count++;
  22.         }
  23.         if (count > result) {
  24.             result = count;
  25.             mi = i;
  26.         }
  27.     }


  28.     printf("mi %d, result=%lu\n", mi, result);

  29.     return 0;
  30. }

  31. 穷举法。考虑某种情况下,超过LLONG_MAX怎么办? 利用系统缓冲或许可以进行一定的优化。

阅读(1377) | 评论(0) | 转发(0) |
0

上一篇:euler13

下一篇:eule16

给主人留下些什么吧!~~