project Euler第九题

15 篇文章 0 订阅
12 篇文章 0 订阅

题目:


A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a 2 +  b 2 =  c 2

For example, 32 + 42 = 9 + 16 = 25 = 52.

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


算法:

#!/usr/bin/env python
#coding=utf-8
    
i = 1
while True:
    a = i*2 + 1
    b = (i**2)*2+i*2
    c = b + 1
    temp = 1000%(a+b+c)
    if temp == 0:
        temp = 1000/(a+b+c)
        print a*temp*b*temp*c*temp
        exit()
    elif a+b+c < 1000:
        i += 2
    else:
        break

i = 2        
while True:
    a = i*2
    b = i**2 - 1
    c = b + 2
    temp = 1000%(a+b+c)
    if temp == 0:
        temp = 1000/(a+b+c)
        print a*temp*b*temp*c*temp
        exit()
    elif a+b+c < 1000:
        i += 2
    else:
        break


结果:31875000


如果a,b,c是一组勾股数,那么na,nb,nb也是勾股数,所以只要求出一组互质的勾股数就可以得出任意组。而求互质的勾股数有一个公式:

a为大于1的奇数2n+1时,b=2*n^2+2*n, c=2*n^2+2*n+1

当a为大于4的偶数2n时,b=n^2-1, c=n^2+1

按照这个公式,求出一组满足a+b+c可以整除1000的勾股数,然后将a,b,c扩大到和为1000就是结果。

以后估计就只能抽空做做这上边的题了。做完这道题得到一个勋章:



java代码:


package ten;

public class Problem9 {
    public static void main(String args[]){
        int i=1,a=0,b=0,c=0,temp=0;
        while(true){
            if(i%2 == 1){
                a = i*2 + 1;
                b = (i*i)*2 + i*2;
                c = b +1;
            }
            else{
                a = i*2;
                b = i*i - 1;
                c = b + 2;
            }
            temp = 1000%(a+b+c);
            if(temp == 0){
                temp = 1000/(a+b+c);
                System.out.println(a*b*c*temp*temp*temp);
                System.exit(0);
            }
            else if(a+b+c<1000){
                i++;
            }
            else{
                break;
            }
            
        }
    }
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值