Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make this function more efficient (Project Euler Number 9)?

Tags:

java

algorithm

I just finished Project Euler problem 9 (warning spoilers):

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.

Here's my solution:

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;
}

I can't help but think that there's a solution that involves only one loop. Anyone have ideas? I'd prefer answers using only one loop, but anything that's more efficient than what I currently have would be nice.

like image 719
Steve P. Avatar asked Jun 04 '13 07:06

Steve P.


2 Answers

if a + b +c = 1000

then

 a + b + sqroot(a² + b²) = 1000

 -> (a² + b²) = (1000 - a - b)²

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

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

 -> ... (easy basic maths)

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

Then you try every b until you find one that makes a natural number out of a.

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;
    }

EDIT: b can't be higher than 499, because c>b and (b+c) would then be higher than 1000.

like image 78
Fabinout Avatar answered Oct 11 '22 06:10

Fabinout


I highly recommend reading http://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple and writing a function that will generate the Pythagorean triples one by one.

Not to give too much of a spoiler, but there are a number of other PE problems that this function will come in handy for.

(I don't consider this giving away too much, because part of the purpose of PE is to encourage people to learn about things like this.)

like image 23
btilly Avatar answered Oct 11 '22 08:10

btilly