Pythagorean Triplets

Problem 9 Project Euler 

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

a2 + b2 = c2

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

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

O(n) Solution snippet

static long TripletOn(int n)
    {
        long product = -1;
        for(int a = 1; a < = n / 3; a++)
        {
            int b = (n * n - 2 * n * a)/(2 * n - 2 * a);
            int c = n - a - b;
            if(a * a + b * b == c * c)
            {
                if(a * b * c > product) 
                    product = a * b * c;
            }
        }
        return product;
    }

O(n2) Solution snippet

static double Triplet(int n)
    {
        double max=0;
        if(n < =0) return -1;
        for(double i=1; i < n/3; i++)
        {
            for(double j=i+1; j < n; j++)
            {
                var c2 = i*i +j*j;
                var c = Math.Pow(c2,.5);
                if(i+j+c==Convert.ToDouble(n))
                {
                    var z =i*j*c;
                    if(z > max)
                    {
                        max=z;
                    }
                }
            }
        }
        return max>0 ? max:-1;
    }

Full Code

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

    static void Main(String[] args) {
        int t = Convert.ToInt32(Console.ReadLine());
        for(int a0 = 0; a0 < t; a0++){
            int n = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(TripletOn(n));
            
        }
    }
    static double Triplet(int n)
    {
        double max=0;
        if(n<=0) return -1;
        for(double i=1; i< n/3; i++)
        {
            for(double j=i+1; j< n; j++)
            {
                var c2 = i*i +j*j;
                var c = Math.Pow(c2,.5);
                if(i+j+c==Convert.ToDouble(n))
                {
                    var z =i*j*c;
                    if(z > max)
                    {
                        max=z;
                    }
                }
            }
        }
        return max > 0 ? max:-1;
    }
    static long TripletOn(int n)
    {
        long product = -1;
        for(int a = 1; a < = n / 3; a++)
        {
            int b = (n * n - 2 * n * a)/(2 * n - 2 * a);
            int c = n - a - b;
            if(a * a + b * b == c * c)
            {
                if(a * b * c > product) 
                    product = a * b * c;
            }
        }
        return product;
    }
}
Live Code on Ide One

Comments

Popular Posts