项目欧拉45 [英] Project euler 45
问题描述
我还不是一个熟练的程序员,但我认为这是一个有趣的问题,我想我会试一试。
I'm not yet a skilled programmer but I thought this was an interesting problem and I thought I'd give it a go.
三角形,五角形和六角形
数字由以下
公式生成:
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
- 三角形T_(n )= n(n + 1)/ 2
1,3,6,10,15,...... - 五角形P_(n)= n(3n-1) / 2 1,5,12,22,35,
... - 六边形H_(n)= n(2n-1)1,
6, 15,28,45,...
可以验证T_(285)=
P_(165) = H_(143)= 40755。
It can be verified that T_(285) = P_(165) = H_(143) = 40755.
找到下一个三角形数字,即
,也是五边形和六边形。
Find the next triangle number that is also pentagonal and hexagonal.
是任务描述。
我知道六边形数字是三角形数字的子集,这意味着你只需要找到Hn = Pn的数字。
但我似乎无法让我的代码工作。我只知道java语言,这就是为什么我在网络上找不到解决方案的原因。无论如何希望有人可以帮忙。这是我的代码
I know that Hexagonal numbers are a subset of triangle numbers which means that you only have to find a number where Hn=Pn. But I can't seem to get my code to work. I only know java language which is why I'm having trouble finding a solution on the net womewhere. Anyway hope someone can help. Here's my code
public class NextNumber {
public NextNumber() {
next();
}
public void next() {
int n = 144;
int i = 165;
int p = i * (3 * i - 1) / 2;
int h = n * (2 * n - 1);
while(p!=h) {
n++;
h = n * (2 * n - 1);
if (h == p) {
System.out.println("the next triangular number is" + h);
} else {
while (h > p) {
i++;
p = i * (3 * i - 1) / 2;
}
if (h == p) {
System.out.println("the next triangular number is" + h); break;
}
else if (p > h) {
System.out.println("bummer");
}
}
}
}
}
我意识到它可能是一个非常缓慢且无效的代码,但这并不关心我此时我只关心找到下一个数字,即使它需要我的计算机多年。
I realize it's probably a very slow and ineffecient code but that doesn't concern me much at this point I only care about finding the next number even if it would take my computer years.
推荐答案
我们知道T 285 = P 165 = H < sub> 143 = 40755.我们从 nt = 286
开始, np = 166
和 nh = 144
并计算出相应的三角形,五边形和六边形数字。无论结果数量最小,我们都会提高其 n
值。继续执行此操作,直到所有数字相等并且您有答案。
We know that T285 = P165 = H143 = 40755. We start with nt=286
, np=166
and nh=144
and work out the respective triangle, pentagonal, and hexagonal numbers. Whichever resulting number is smallest, we bump up its n
value. Continue doing this until all numbers are equal and you have your answer.
此算法的Python实现在我的计算机上运行0.1秒。
A Python implementation of this algorithm runs in 0.1 seconds on my computer.
代码问题是溢出。虽然答案适合32位 int
,但临时值 i *(3 * i - 1)
溢出之前得到答案。使用64位 long
值可修复您的代码。
The problem with your code is overflow. While the answer fits into a 32 bit int
, the temporary values i * (3 * i - 1)
overflows before reaching the answer. Using 64 bit long
values fixes your code.
这篇关于项目欧拉45的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!