Project Euler – Problem 4

By | May 18, 2011

Problem 4 from Project Euler:

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.

My solution:

DECLARE
    v_p PLS_INTEGER;

    FUNCTION is_palendrome(
        num_in IN NUMBER
    )
    RETURN BOOLEAN
    IS
        v_val VARCHAR2(255) := to_char(num_in);
        v_ret BOOLEAN := TRUE;
    BEGIN
        FOR i in 1..ceil(length(v_val)/2)
        LOOP
            IF substr(v_val, i, 1) <> substr(v_val, -1*i, 1)
            THEN
                v_ret := FALSE;
            END IF;
        END LOOP;
        RETURN v_ret;
    END is_palendrome;

    FUNCTION largest_palendrome(
        num_digits_in IN PLS_INTEGER
    )
    RETURN PLS_INTEGER
    IS
        v_max PLS_INTEGER := to_number(rpad('9',num_digits_in, '9'));
        v_lp PLS_INTEGER := 0;
    BEGIN
        FOR i in 1 .. v_max
        LOOP
            FOR j in 1 .. v_max
            LOOP
                IF is_palendrome(i*j) and i*j > v_lp
                THEN
                    v_lp := i*j;
                END IF;
            END LOOP;
        END LOOP;
        RETURN v_lp;
    END largest_palendrome;
BEGIN
    dbms_output.put_line('lp: '||largest_palendrome(3));
END;

As always.. I am no mathmatician, so If you know of a better solution please let me know.

Leave a Reply

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

Turn on pictures to see the captcha *