Project Euler 12,Java解决方案尝试,递归错误? [英] Project Euler 12, Java solution attempt, recursion error?

查看:43
本文介绍了Project Euler 12,Java解决方案尝试,递归错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要一些指导来改进我的问题解决方案.请不要把解决方案交给我,因为我想自己完成.这是我尝试使用递归解决 Project Euler Prob 12 的尝试.该问题要求第一个除数超过 500 的三角形数.

I just need some pointers on improving my solution to the problem. Please don't hand me the solution, as I would like to accomplish that myself. Here is my attempt at solving Project Euler Prob 12, using recursion. The problem asks for the first triangular number that has over 500 divisors.

我看不出有什么问题;Eclipse 也没有显示任何错误.它只是继续运行而没有得到答案.

I don't see anything wrong with it; Eclipse doesn't show any error as well. It just keeps on running without reaching the answer.

public class P012 {
    public static void main(String[] args) {

        int m=2;
        int c=1;
        int d=(c*(c+1)/2);

        while (numDivs(d,m)<=499) {
            c++;
            d=(c*(c+1)/2);
        }
        System.out.println(d);

    }

    public static int numDivs(int a, int b) {
        int foo=2;
        while (b < a/2) {
            if ((a%b)==0)
                foo++;
            b++;
            numDivs(a,b);
        }
        return foo;

    }
}

推荐答案

我只是自己计算了这个问题,我可以说你的方法大多有效.数字并不像我一开始假设的那么大.最大的问题是 numDivs 中不必要的递归调用.只需使用 while 循环计算它(在这种情况下,您也只需要一个函数参数).然后这一切都需要大约一两分钟才能运行(您需要计算多于 12000 个三角形数,这还不错).但是,您的 numDivs 有错误,您应该在 b <= a/2 处中断 while 循环(或者在某些情况下不计算因子).有了这些修复程序,您的方法应该可行.祝你好运.

I just calculated the problem myself, and I can say your approach would mostly work. The numbers aren't that big as I assumed in the beginning. The biggest problem is the unnessecary recursive call in numDivs. Just calculate it with a while-loop (you also need only one parameter for the function in that case). then it all does need around a minute or two to run (you need to calculate a bit more than 12000 triangle numbers, that is not that bad). Your numDivs has an error though, you should break your while-loop at b <= a/2 (or you don't count a factor in some cases). With these fixes your approach should work. Good luck.

通过我提到的修复程序,我尝试了您的程序 - 结果与我的相同,因此您已经发现该解决方案只有一些小错误.顺便说一下,有趣的数字,由此产生的数字.:-)

With the fixes I mentioned I tried your program - and it get's to the same result as mine, so you already found the solution only have some minor bugs. Funny number by the way, the resulting number. :-)

这篇关于Project Euler 12,Java解决方案尝试,递归错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆