Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

'Happy numbers' logic in SQL

ManikNov 4 2015 — edited Nov 10 2015

Hi all,

Good day....

Note : This thread is just for fun and meant for learning recursive techniques

Please ignore this if you are busy

-------------------------

https://en.wikipedia.org/wiki/Happy_number

For example, 19 is happy, as the associated sequence is:

12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1.

Just wanted to know if someone can re-write this below pl/sql snippet in plain SQL (using recursive with clause may be).. Saying so this pl/sql is not that bad either.. w.r.t performance.

SET SERVEROUTPUT ON

DECLARE
   l_res       NUMBER;
   l_var_new   NUMBER;
BEGIN
   FOR rec IN 0 .. 1000
   LOOP
      l_var_new := rec;

      WHILE (TRUE)
      LOOP
         EXECUTE IMMEDIATE
               'select '
            || RTRIM (REGEXP_REPLACE (l_var_new, '(.)', 'power(\1,2)+'), '+')
            || ' from dual'
            INTO l_res;

         IF ( (LENGTH (l_res) = 1 AND l_res <> 1) OR l_res = 1)
         THEN
            IF (l_res = 1)
            THEN
               --logmein.in ('NUMBER -> ' || rec);   ---- logging method
               DBMS_OUTPUT.put_line (rec);  ---just for our comfort.. (not for logging ;-))
            END IF;

            EXIT;
         END IF;

         l_var_new := l_res;
      END LOOP;
   END LOOP;
END;

Cheers,

Manik.

This post has been answered by Scott Swank on Nov 4 2015
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 8 2015
Added on Nov 4 2015
29 comments
9,818 views