Euler 2项目:
Fibonacci序列中的每个新项都是通过添加前两个项来生成的。从1和2开始,前10项将是:1、2、3、5、8、13、21、34、55、89、.通过考虑Fibonacci序列中值不超过400万的项,找出偶数项的和。
这是我的解决方案:
public class EvenFibonacciFinder {
private static final double PHI = 1.618033989;
private static final double _PHI = -(PHI - 1);
private static final double SQRT_5 = Math.sqrt(5);
private static final int MAX_NUM = 4_000_000;
public static void main(String[] args) {
long time = System.nanoTime();
double max = MAX_NUM * SQRT_5;
long sum = 0;
for (int i = 3, result = (int) Math.round(2 * SQRT_5); result < max; result = (int) Math.round(Math.pow(PHI, i += 3) - Math.pow(_PHI, i))) {
sum += result;
}
sum = Math.round(sum / SQRT_5);
System.out.println("Result: " + sum + "\nTime used for calculation in nanoseconds: " + (System.nanoTime() - time));
}
}输出:
结果: 4613732 计算时间,以纳秒为单位: 60243
问题:
发布于 2014-12-23 05:11:01
这是最有效的方法吗?
有时,最简单的解决方案也是最有效的解决方案。我不知道为什么您决定使用Math.pow和PHI来计算一些简单的加法可以很容易(而且更快)计算的内容:
public class EvenFibonacciFinder {
private static final int MAX_NUM = 4_000_000;
public static void main(String[] args)
{
long time = System.nanoTime();
int f1 = 1;
int f2 = 2;
long sum = 0;
while (f2 <= MAX_NUM) {
int f3;
sum += f2;
// This skips three ahead in the sequence.
f3 = f1 + f2;
f1 = f2 + f3;
f2 = f1 + f3;
}
long end = System.nanoTime();
System.out.println("Result: " + sum +
"\nTime used for calculation in nanoseconds: " +
(end - time));
}
}输出:
使用pow: 的原始代码结果:4613732 用于计算的纳秒时间: 9952使用加法而不是pow: 结果:4613732 时间用于计算,以纳秒为单位: 934
(注意:两个程序都被修改以测量println()之前的结束时间,否则一些字符串级联时间就会被计算)。
发布于 2014-12-23 02:47:36
有这么多的评论,真的很难理解。即使在数学上优越的人(我不是),你需要提供更多关于你的常量是什么,为什么需要它们,以及函数是如何工作的信息。
考虑到您拥有的常量,以及它的硬编码方式,我几乎可以说您的代码可以通过以下方式得到改进:
System.out.println("Result: 4613732\nTime used for calculation in nanoseconds: 0");;-0
这和你的复杂公式一样有道理,而且.它产生正确的结果,更快。
发布于 2014-12-23 02:16:10
写这个程序真是太好了。我所看到的唯一可以优化的是:
Math.pow(PHI, i += 3) - Math.pow(_PHI, i)
// PHI^(i+3) - PHI^i = PHI^i*(PHI^3-1) = PHI^i * PHI_CUBE_LESS_1 (Constant). Add comment if used.int是否足够而不是使用long?只需在注释中添加wiki链接,让其他人查看数学公式:)
干得好!
https://codereview.stackexchange.com/questions/74581
复制相似问题