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

后端 未结 16 2423
离开以前
离开以前 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 14:05
    func maxProd(sum:Int)->Int{
        var prod = 0
        //    var b = 0
        var c = 0
        let bMin:Int = (sum/4)+1 //b can not be less than sum/4+1 as (a+b) must be greater than c as there will be no triangle if this condition is false and any pythagorus numbers can be represented by a triangle.
        for b in bMin..<sum/2 {
            for a in ((sum/2) - b + 1)..<sum/3{ //as (a+b)>c for a valid triangle
                c = sum - a - b
                let csquare = Int(pow(Double(a), 2) + pow(Double(b), 2))
                if(c*c == csquare){
                    let newProd = a*b*c
                    if(newProd > prod){
                        prod = newProd
                        print(a,b,c)
                    }
                }
            }
        }
        //
        return prod
    }
    

    The answers above are good enough but missing one important piece of information a + b > c. ;)

    More details will be provided to those who ask.

    0 讨论(0)
  • 2020-12-24 14:07

    I think the best approach here is this:

    int n = 1000;
    unsigned long long b =0;
    unsigned long long c =0;
    for(int a =1;a<n/3;a++){
        b=((a*a)- (a-n)*(a-n)) /(2*(a-n));
        c=n-a-b;
    
        if(a*a+b*b==c*c)
            cout<<a<<' '<<b<<' '<<c<<endl;
     }
    

    explanation: We shall refer to the N and A constant so we will not have to use two loops. We can do it because c=n-a-b and b=(a^2-(a-n)^2)/(2(a-n)) I got these formulas by solving a system of equations:

    a+b+c=n, a^2+b^2=c^2

    0 讨论(0)
  • 2020-12-24 14:08

    As mentioned above, ^ is bitwise xor, not power.

    You can also remove the third loop, and instead use c = 1000-a-b; and optimize this a little.

    Pseudocode

    for a in 1..1000
        for b in a+1..1000
            c=1000-a-b
            print a, b, c if a*a+b*b=c*c
    
    0 讨论(0)
  • 2020-12-24 14:08

    While as many people have pointed out that your code will work fine once you switch to using pow. If your interested in learning a bit of math theory as it applies to CS, I would recommend trying to implementing a more effient version using "Euclid's formula" for generating Pythagorean triples (link).

    0 讨论(0)
提交回复
热议问题