首页 > 其他 > 详细

(Problem 14)Longest Collatz sequence

时间:2014-02-12 08:57:59      阅读:370      评论:0      收藏:0      [点我收藏+]

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

n bubuko.com,布布扣 n/2 (n is even) n bubuko.com,布布扣 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 bubuko.com,布布扣 40 bubuko.com,布布扣 20 bubuko.com,布布扣 10 bubuko.com,布布扣 5 bubuko.com,布布扣 16 bubuko.com,布布扣 8 bubuko.com,布布扣 4 bubuko.com,布布扣 2 bubuko.com,布布扣 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.

题目大意:

以下迭代序列定义在整数集合上:

n bubuko.com,布布扣 n/2 (当n是偶数时) n bubuko.com,布布扣 3n + 1 (当n是奇数时)

应用以上规则,并且以数字13开始,我们得到以下序列:

13 bubuko.com,布布扣 40 bubuko.com,布布扣 20 bubuko.com,布布扣 10 bubuko.com,布布扣 5 bubuko.com,布布扣 16 bubuko.com,布布扣 8 bubuko.com,布布扣 4 bubuko.com,布布扣 2 bubuko.com,布布扣 1

可以看出这个以13开始以1结束的序列包含10个项。虽然还没有被证明(Collatz问题),但是人们认为在这个规则下,以任何数字开始都会以1结束。

以哪个不超过100万的数字开始,能给得到最长的序列? 注意: 一旦序列开始之后,也就是从第二项开始,项是可以超过100万的。

方法1:

bubuko.com,布布扣
#include<stdio.h>
#include<math.h>
#include<stdbool.h>

int powcount(long long n)  //计算2的幂数
{
    int count=0;
    while(n>>=1) count++;
    return count;
}

bool ispower(long long v)  //判断n是否为2的幂
{
    if(((v & (v - 1)) == 0))  return true;
    else return false;
}

int length(long long n)
{
    int sum=1;
    while(1)
    {
        if(n==1) break;
        if((n & 1)==0)
        {
            if(ispower(n)) return sum+powcount(n);
            else n=n/2;
        }
        else n=3*n+1;
        sum++;
    }
    return sum;
}

int main()
{
    int i,t,k,max=0;
    for(i=2; i<1000000; i++)
    {
        t=length(i);
        if(t>max)
        {
            max=t;
            k=i;
        }
    }
    printf("%lld\n",k);
    return 0;
}
bubuko.com,布布扣

方法2:

bubuko.com,布布扣
#include<stdio.h>
#include<math.h>
#include<stdbool.h>

int a[1000001];

void find()
{
    long long i,j,k,f,sum,max=0;
    a[1]=1,a[2]=2;
    for(j=3; j<1000000; j++)
    {
        sum=1,k=i=j;
        while(1)
        {
            if((i & 1)==0)
            {
                i=i/2;
                if(i<k)
                {
                    a[k]=sum+a[i];
                    break;
                }
            }
            else
            {
                i=3*i+1;
            }
            sum++;
        }
        if(a[k]>max)
        {
            max=a[k];
            f=k;
        }
    }
    printf("%d\n",f);
}

int main()
{
    find();
    return 0;
}
bubuko.com,布布扣

 

Answer:
837799

(Problem 14)Longest Collatz sequence

原文:http://www.cnblogs.com/acutus/p/3545218.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!