博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Project Euler Problem 14 Longest Collatz sequence
阅读量:6950 次
发布时间:2019-06-27

本文共 2217 字,大约阅读时间需要 7 分钟。

Problem 14

The following iterative sequence is defined for the set of positive integers:

nn/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.

C++:

#include 
#include
using namespace std;const int MAXN = 1000000;const int ONE_HUNDRED_MILLION = 100000000;int cs[ONE_HUNDRED_MILLION+1];// Collatz sequence countint cscount(long long x){ if(x <= ONE_HUNDRED_MILLION && cs[x]) return cs[x]; int count; if(x % 2 == 0) count = 1 + cscount(x / 2); else count = 1 + cscount(x * 3 + 1); if(x <= ONE_HUNDRED_MILLION) cs[x] = count; return count;}int main(){ memset(cs, 0, sizeof(cs)); cs[1] = 1; int n, ans; while(cin >> n && n <= MAXN) { ans = 1; for(int i=1; i<=n; i++) { cs[i] = cscount(i); if(cs[i] > cs[ans]) ans = i; } cout << ans << endl; } return 0;}
Input data:

999999

C++(Too slow):

#include 
using namespace std;//#define DEBUGconst int MAXN = 1000000;// Collatz sequence countint cscount(int start){#ifdef DEBUG cout << start << ": ";#endif int count = 0; for(;;) {#ifdef DEBUG cout << start << " ";#endif count++; if(start == 1) break; if(start & 1) start = 3 * start + 1; else start >>= 1; }#ifdef DEBUG cout << endl;#endif return count;}int main(){ int n, ans, maxcount=0, temp; while(cin >> n && n <= MAXN) { for(int i=1; i<=n; i++) { temp = cscount(i); if(temp > maxcount) { maxcount = temp; ans = i; } } cout << ans << endl; } return 0;}

转载于:https://www.cnblogs.com/tigerisland/p/7564021.html

你可能感兴趣的文章
前端临床手札——单元测试
查看>>
Java IO : File
查看>>
JavaScript Ajax与Comet——“进度事件”的注意要点
查看>>
[单刷APUE系列]第四章——文件和目录[2]
查看>>
MySQL Replication
查看>>
JavaScript数组去重总结
查看>>
MVVM_Android-CleanArchitecture
查看>>
iOS开发-协议Protocol&代理delegate
查看>>
【系统架构师修炼之道】(4):绪论——Zachman 框架
查看>>
Foxify v0.10.7 发布,基于 TypeScript 的 Node 框架
查看>>
Python数据结构——双端队列
查看>>
GitHub 项目推荐:用深度学习让你的照片变得美丽 ...
查看>>
2.HtmlAgilityPack 爬取优酷电影名进阶(所有分类+多线程)
查看>>
Rails 6.0.0 beta2 发布,开源 Web 应用框架
查看>>
Nginx 加/的区别
查看>>
UWP 大爆炸你个锤子
查看>>
Confluence 6 空间
查看>>
Kubernetes下一站,要做云的“分布式”Linux?
查看>>
Java性能优化的50个细节(珍藏版)
查看>>
[译]聊聊C#中的泛型的使用(新手勿入)
查看>>