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.
用了一个傻逼的方法,尽管答案对了,但跑起来非常慢
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; }
相关文章推荐
- Java for LeetCode 128 Longest Consecutive Sequence
- UINavigationItem不显示
- spinner requestlayout() improperly called by during layout running second layout pass
- iOS7 与 iOS8上 uisegementcontrol 设置image不显示问题
- 设置UILabel背景和文字的透明度(代码和SB两种实现)
- Algs4 union-find算法 带路径压缩的加权Quick-Union实现
- Android 开发工具类 29_sendPOSTRequest
- SpriteWithHue,通过修改色调实现资源复用
- Arduino学习笔记 函数的秘密~~~
- Arduuino复合运算符+Arduino基础~~~
- UISearchBar
- Android 开发工具类 28_sendGETRequest
- android UI 仿 win 8 模块化 标题,并实现 可长按拖动交换图片位置、可点击,且伴随动画特效
- The JSP specification requires that an attribute name is preceded by whitespace
- android build系统
- PHP include 和 require
- UIImageView 的contentMode属性
- UEFI+GPT引导全方位讲解:什么是GPT,什么是UEFI
- Bluemix实战教程: CF命令学习分享
- 【测试】关于UI自动化的疑问(记录ing)