Project Euler in PL/SQL: Problem 9

  • by

Problem 9:

Special Pythagorean Triplet

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.

This solution is pretty straightforward, we just loop through different possible values to find the case that’s the solution.

DECLARE
a PLS_INTEGER := 0;
b PLS_INTEGER;
c PLS_INTEGER;
total PLS_INTEGER := 1000;
BEGIN
    WHILE a <= total/3 LOOP
    a := a + 1;
    b := a;
        WHILE b <= total/2 LOOP
        b := b + 1;
        c := total - a - b;
        
        IF c > 0 AND ( (a**2 + b**2) = c**2 )
        THEN
            dbms_output.put_line(a||', '||b||', '||c);
            dbms_output.put_line(a*b*c);
            EXIT;
        END IF;
        END LOOP;
    END LOOP;

END;
--output: 31875000

Questions or comments? Feel free to leave them below or reach out to me on Twitter!

Leave a Reply

Your email address will not be published. Required fields are marked *