您的位置:首页 > 产品设计 > UI/UE

project euler 14 Longest Collatz sequence

2017-12-16 16:56 453 查看

题目:

https://projecteuler.net/problem=14

题意:

Longest Collatz sequence

Problem 14

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.

对于一个数字n,有如下操作:

n是偶数,则n=n/2

n是奇数,则n=n∗3+1

直到n=1为止,这个变换过程一定有一个变换次数

求106以下的数字中,哪个数字有最多的变换次数

思路:

可以直接遍历每个数字,求每个数字的变换次数,取其中的最大值,1秒钟足够。

可以优化一些的地方:对于已经求出来变换次数的数字,将这个变换次数储存起来,之后的数字进行变换过程中一定会变换成前面的某些数字,此时可以直接使用前面这些数字的变换次数,而无需一直变换

代码:

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int N = 1000000 + 10;

int num
;
int limit = 1000000;

int check(ll x)
{
int cnt = 1;
while(x != 1)
{
if(x & 1)
x = 3*x + 1;
else
x /= 2;
if(x < limit && num[x] != -1)
{
cnt += num[x];
break;
}
++cnt;
}
return cnt;
}
int main()
{
memset(num, -1, sizeof num);
int ans = 0, len = 0;
for(int i = 1; i < limit; ++i)
{
int temp = check(i);
if(temp > len)
{
ans = i;
len = temp;
}
num[i] = temp;
}
printf("%d\n", ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: