Chinaunix首页 | 论坛 | 博客
  • 博客访问: 223247
  • 博文数量: 68
  • 博客积分: 3120
  • 博客等级: 中校
  • 技术积分: 715
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-08 09:53
文章分类
文章存档

2012年(29)

2011年(3)

2010年(18)

2009年(18)

我的朋友

分类: C/C++

2012-01-18 20:33:09

问题:

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.



答案: 837799

#include

int euler14(long long n){
    int count = 0; 
    while (n != 1) { 
        if (n % 2 == 0) { 
            n /= 2; 
        } else { 
            n = (3 * n + 1); 
        } 
        count++; 
    } 
    return count; 
}


int main(void)
{
    int max = 0; 
    int num = 0; 
    for (int i = 1; i <= 1000000; i++) { 
        int temp = euler14(i); 
        if (temp > max) { 
            num = i; 
            max = temp; 
        } 
    } 

    printf("max=%d  count=%d\n",max, num);
    return 0;
}

该方法属于暴力遍历每个数,实际上可以对程序优化一下,把之前己经得到的结果存储到数组中,减少不必要的计算步骤。

阅读(847) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~