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 Find Maximum Possible Product Puzzle in SQL

December 18th, 2008 By Frank Zhou

The following is an interesting problem posted by mathforum.org:

Use all the digits from 1 to 9 without repeating, to form two numbers such that their product is maximum. A digit used should be unique across both the numbers. For example, the numbers formed could be 1234 and 56789.

—————————————— SQL Solution——————————————————

SELECT n1, n2, product as MAX_PRODUCT
FROM
(SELECT max(n1 * n2 ) over ( ) max_product, n1, n2, n1 * n2 product
 FROM
 (
  WITH DATA AS
  (SELECT replace(sys_connect_by_path(num, ','), ',') str_num
   FROM (SELECT LEVEL num FROM dual CONNECT BY LEVEL <10)
   WHERE LEVEL = 9
   START WITH num = 9
   CONNECT BY NOCYCLE PRIOR num != num
   AND LEVEL <= 9
  )
  SELECT to_number(substr(str_num,0,LEVEL)) n1, to_number(substr(str_num,LEVEL+1)) n2
  FROM DATA
  CONNECT BY PRIOR str_num = str_num
    AND LEVEL <= length(str_num)-1
  AND PRIOR DBMS_RANDOM.STRING ('P',20) IS NOT NULL
 )
)
WHERE max_product = product;

        N1                  N2                   MAX_PRODUCT
----------               ----------                -----------
      9642                87531                      843973902

One Response to “How to solve the Find Maximum Possible Product Puzzle in SQL”

  1. newkid Says:

    This one is better in performance:

    SELECT n1, n2, product as MAX_PRODUCT
    FROM
    (SELECT max(n1 * n2 ) over ( ) max_product, n1, n2, n1 * n2 product
     FROM
     (
      WITH DATA AS
      (SELECT replace(sys_connect_by_path(num, ','), ',') str_num
       FROM (SELECT LEVEL num FROM dual CONNECT BY LEVEL <10)
       WHERE LEVEL = 9
       START WITH num = 9
       CONNECT BY NOCYCLE PRIOR num != num
       AND LEVEL <= 9
      )
      SELECT to_number(substr(str_num,1,rn)) n1, to_number(substr(str_num,rn+1)) n2
      FROM DATA,(SELECT ROWNUM rn FROM DUAL CONNECT BY ROWNUM<=8)
     )
    )
    WHERE max_product = product;
    

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this question