加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 我能使这个功能更有效(Project Euler Number 9)?

发布时间:2020-12-14 16:47:00 所属栏目:Java 来源:网络整理
导读:我刚刚完成了项目欧拉问题9(警告扰流板): A Pythagorean triplet is a set of three natural numbers,a b c,for which,a^2 + b^2 = c^2For example,3^2 + 4^2 = 9 + 16 = 25 = 5^2.There exists exactly one Pythagorean triplet for which a + b + c = 100
我刚刚完成了项目欧拉问题9(警告扰流板):
A Pythagorean triplet is a set of three natural numbers,a < b < c,for which,a^2 + b^2 = c^2

For example,3^2 + 4^2 = 9 + 16 = 25 = 5^2.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

这是我的解决方案:

public static int specPyth(int num)
{
    for (int a = 1; a < num; a++)
        for (int b = 2; b < a; b++)
            {
                if (a*a +b*b == (num-a-b)*(num-a-b))
                    return a*b*(num-a-b); //ans = 31875000 
            }

    return -1;
}

我不禁想到有一个只有一个循环的解决方案.有人有想法吗?我只想使用一个循环,但是比现在更有效的任何东西都会很好.

解决方法

if a + b +c = 1000

然后

a + b + sqroot(a2 + b2) = 1000

 -> (a2 + b2) = (1000 - a - b)2

 -> a2 + b2 = 1000000 - 2000*(a+b) + a2 + 2*a*b + b2

 -> 0 = 1000000 - 2000*(a+b) + 2*a*b

 -> ... (easy basic maths)

 -> a = (500000 - 1000*b) / (1000 - b)

然后你尝试每一个b,直到你找到一个自然数字的一个.

public static int specPyth(int num)
    {
        double a;
        for (int b = 1; b < num/2; b++)
        {
            a=(num*num/2 - num*b)/(num - b);

            if (a%1 == 0)
                return (int) (a*b*(num-a-b));
        }   

        return -1;
    }

编辑:b不能高于499,因为c> b和(b c)然后将高于1000.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读