Find Pythagorean triplet for which a + b + c = 1000

后端 未结 16 2428
离开以前
离开以前 2020-12-24 13:13

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2

For example, 32 + 4

16条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 13:53

    I know this question is quite old, and everyone has been posting solutions with 3 for loops, which is not needed. I got this solved in O(n), by **equating the formulas**; **a+b+c=1000 and a^2 + b^2 = c^2**

    So, solving further we get;

    a+b = 1000-c
    
    (a+b)^2 = (1000-c)^2
    

    If we solve further we deduce it to;

    a=((50000-(1000*b))/(1000-b)). We loop for "b", and find "a".

    Once we have "a" and "b", we get "c".

    public long pythagorasTriplet(){
        long a = 0, b=0 , c=0;
    
        for(long divisor=1; divisor<1000; divisor++){
            if( ((500000-(1000*divisor))%(1000-divisor)) ==0){
                a = (500000 - (1000*divisor))/(1000-divisor);
                b = divisor;
                c = (long)Math.sqrt(a*a + b*b);
                System.out.println("a is " + a + " b is: " + b + " c is : " + c);
                break;
            }
        }
        return a*b*c;
    }
    

提交回复
热议问题