OraQA

Oracle Question and Answer

  • Do you have a solution to a problem? Do you have an unanswered question? Login and share it with the Oracle community. More...

Oracle News


Entries RSS feed

Comments RSS feed

How to solve the Social Security Number puzzle in SQL

February 17th, 2008 By Frank Zhou

The following is an interesting puzzle posted on MathPuzzles:

I had great difficulty trying to remember my social security identity number, a long string of digits, until I realized that it is the largest number in which every block of two adjacent digits is a different prime or square number. What number is it?

—————————SQL Solution———————————-

SELECT
max(to_number(replace(sys_connect_by_path(
                      CASE LEVEL
                           WHEN 1 THEN to_char(num)
                           ELSE second
                       END,','),','))) as SSN#
FROM
(SELECT num, substr(num,1,1) first, substr(num,2,1) second
 FROM
 (SELECT num
  FROM
  (WITH data AS (SELECT LEVEL+1 num FROM dual CONNECT BY LEVEL <=100)
   SELECT num FROM data WHERE num <= 100
   MINUS
   SELECT  d1.num * d2.num
   FROM data d1, data d2
   WHERE  d1.num <= d2.num
   AND d1.num <= sqrt(100)
  )
  WHERE num >=10
  UNION
  SELECT power(LEVEL,2) num from dual WHERE power(LEVEL,2) >=10
  CONNECT BY LEVEL <=9
 )
)
WHERE LEVEL = 8
CONNECT BY NOCYCLE PRIOR first != second
AND PRIOR second = first
AND LEVEL <=8;
      SSN#
---------------------
 973671649

Elapsed: 00:00:00.03

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this question