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

Project Euler: Problem 14 Longest Collatz sequence

2015-05-30 21:22 513 查看
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.

用了一个傻逼的方法,尽管答案对了,但跑起来非常慢

#include <iostream>
#include <string>
using namespace std;

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

int main()
{
	long long max = 0;
	long long res;
	for (int i = 1000000; i >= 1; i--)
	{
		//cout << i << endl;
		long long tp = count(i);
		if (max < tp)
		{
			res = i;
			max = tp;
		}
	}
	cout << res << endl;
	system("pause");
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: