Project Euler: Problem 14 Longest Collatz sequence

来源:互联网 发布:ch341a编程器软件1.30 编辑:程序博客网 时间:2024/05/17 06:52

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




0 0
原创粉丝点击