Project Euler in PL/SQL: Problem 4

  • by

Time for another Project Euler problem. This problem is somewhat simple, but we need to dive into some SQL to solve it!

Problem 4:

Largest Palindrome Product

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

DECLARE
lower_range PLS_INTEGER := 100;
upper_range PLS_INTEGER := 999;
product VARCHAR2(1000);
reverse_product VARCHAR2(1000);
answer PLS_INTEGER := 0;
BEGIN
    FOR x IN REVERSE lower_range..upper_range
    LOOP
        FOR y IN REVERSE lower_range..upper_range
        LOOP
            product := x * y;
            
            --we can exit as our y value is too low
            IF product < answer
            THEN
                exit;
            END IF;

            SELECT REVERSE(product)
            INTO reverse_product
            FROM dual;
            
            IF product = reverse_product AND product >  answer
            THEN
                answer := product;
                EXIT;
            END IF;
        END LOOP;
    END LOOP;
    
    dbms_output.put_line(answer);
END;

--output: 906609

This solution is pretty easy to understand if you can wrap your mind around why we use an inner and outer loop. We speed things up in the inner loop by exiting when our y value has gotten so small that our product would no longer be greater than our current answer, saving us a lot of time.

PL/SQL has no built-in REVERSE function, but rather than write a subfunction I opted to use the SQL REVERSE call, which works exactly as we need it to.

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.