码迷,mamicode.com
首页 > 其他好文 > 详细

Project Euler: Problem 14 Longest Collatz sequence

时间:2015-05-31 09:27:37      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:c++   project euler   

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;
}




Project Euler: Problem 14 Longest Collatz sequence

标签:c++   project euler   

原文地址:http://blog.csdn.net/youb11/article/details/46278413

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!