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 “2008″ Puzzle in SQL

January 23rd, 2008 By Frank Zhou

The following is an interesting puzzle posted by MathPuzzles :

The number 2008 can be expressed as the sum of 3 positive cubes in exactly 2 different ways. One way is 2^3 + 10^3 + 10^3 = 2008. What is the other way of expressing 2008 as the sum of 3 positive cubes?

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

SELECT DISTINCT rtrim(ltrim(regexp_replace(XMLAgg(XMLElement(X,num)
   ORDER BY num),'<X>|</X><X>|</X>','^3 + '), '^3 + '),' + ') AS OUTPUT
FROM
(SELECT CASE lev
                 WHEN 1 THEN a
                 WHEN 2 THEN b
                 WHEN 3 THEN c END as num,
                rn
FROM
(SELECT a, b, c, rownum rn from
(SELECT LEVEL a from dual CONNECT BY power(LEVEL,3) <=2008) a,
(SELECT LEVEL b from dual CONNECT BY power(LEVEL,3) <=2008) b,
(SELECT LEVEL c from dual CONNECT BY power(LEVEL,3) <=2008) c
WHERE power(a,3) + power(b,3) + power(c,3) = 2008 ),
(SELECT LEVEL lev FROM dual CONNECT BY LEVEL <=3)
)
GROUP BY rn;

OUTPUT
----------------------------------------------
2^3 + 10^3 + 10^3
4^3 + 6^3 + 12^3

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this question