Project Euler 题解 #45 Triangular, pentagonal, and hexagonal
2013-10-29 11:04
302 查看
题目:Triangular, pentagonal, and hexagonal
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:Triangle | Tn=n(n+1)/2 | 1, 3, 6, 10, 15, ... | ||
Pentagonal | Pn=n(3n![]() 1)/2 | 1, 5, 12, 22, 35, ... | ||
Hexagonal | Hn=n(2n![]() 1) | 1, 6, 15, 28, 45, ... |
Find the next triangle number that is also pentagonal and hexagonal.
分析
经计算可得出以下判定方法:1.一个数X为三角数,等价于
为整数,n表示X的下标。
2.一个数X为五边形数,等价于
为整数,n表示X的下标。
3.一个数X为六边形数,等价于
为整数,n表示X的下标。
那么可以用来解该题,显然这种方法会很慢。
进一步观察,凡六边形数均为三角数,那么就不用判断三角数了。
若用判定条件来检验,由于存在开方或平方,效率会很低。
对五边形数来说,Pn-1-Pn = 3n+1。
对六边形数来说,Hn-1-Hn = 4n+1。
那么具体实现中,可以用加法代替开方。
代码实现
/http://projecteuler.net/problem=45 //Triangular, pentagonal, and hexagonal #include <cmath> #include <iostream> #include <iomanip> #include <limits> int _tmain(int argc, _TCHAR* argv[]) { unsigned __int64 x = 1, y = 1; unsigned __int64 i = 1, j = 1; while (x < LLONG_MAX) { while (y < x) { y += 4 * j + 1; ++j; } if (x == y) { cout<<"<"<<i<<","<<j<<"> = "<<std::setprecision(30)<<x<<endl; } x += (3 * i + 1); ++i; } system("pause"); return 0; }
输出:
相关文章推荐
- goldengate的HANDLECOLLISIONS参数
- hdu 1847 - Good Luck in CET-4 Everybody!(简单博弈)
- Lucky and Good Months by Gregorian Calendar(模拟)
- Mongo之Morphia API
- GO学习第一天——环境搭建
- Golang 做的几个跟性能有关的工具
- Ubuntu 13.10 安装Google Earth(免ia32-libs)
- The Knuth-Morris-Pratt Algorithm in my own words
- Go 语言做的几个验证码
- Dijkstra算法笔记---最短路
- Gold Balanced Lineup hash函数,第一次接触,借鉴了大神的博客思想,看了很久才看懂,弱菜啦
- 水推磨轮转-Google的大规模流式处理系统MillWheel
- django 静态文件配置
- Django class-based views
- 算法导论第五章习题答案(第三版) Introduction to Algorithm
- golang精华资源
- Debian Google Chrome
- Mongo导出数据文件导致错误 Got signal: 6 (Aborted)解决方法
- [LeetCode] Pascal's Triangle II
- GoldenGate快速实战-视频分享