aboutsummaryrefslogtreecommitdiff
path: root/challenge-137/luca-ferrari/postgresql/ch-2.sql
blob: ed96d27b8f5cc7dca9a9a3df699ebaeb8c44492a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
testdb=> select * from f_lychrel( 59, true );
INFO:  Found 1111 after 3 iterations
f_lychrel
-----------
0
*/
CREATE OR REPLACE FUNCTION
f_lychrel( n int, verb boolean default false )
RETURNS smallint
AS $CODE$
DECLARE
        result    bigint := n;
        iteration int    := 0;
BEGIN
        IF n < 10 OR n > 10000 THEN
           RAISE 'n is out of bounds!';
        END IF;

        WHILE result < 10000000 AND iteration < 500 LOOP
              iteration = iteration + 1;
              result    = result + reverse( result::text )::int;
              IF result = reverse( result::text )::int THEN
                 IF verb THEN
                    RAISE INFO 'Found % after % iterations', result, iteration;
                 END IF;

                 RETURN 0;
             END IF;

        END LOOP;

        RETURN 1;
END
$CODE$
LANGUAGE plpgsql;