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 Remainder Puzzle in SQL

September 26th, 2008 By Frank Zhou

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

Find the smallest number, M, such that:

M/10 leaves a remainder of 9;
M/9 leaves a remainder of 8;
M/8 leaves a remainder of 7;
M/7 leaves a remainder of 6;
M/6 leaves a remainder of 5;
M/5 leaves a remainder of 4;
M/4 leaves a remainder of 3;
M/3 leaves a remainder of 2;
M/2 leaves a remainder of 1.

variable input number
exec :input := 10

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

SELECT MIN (num)
  FROM (SELECT   num
            FROM (SELECT     LEVEL num
                        FROM DUAL
                  CONNECT BY LEVEL <= (SELECT EXP (SUM (LN (l)))
                                         FROM (SELECT     LEVEL l
                                                     FROM DUAL
                                               CONNECT BY LEVEL <= :input))) a,
                 (SELECT     LEVEL div
                        FROM DUAL
                  CONNECT BY LEVEL <= :input) b
           WHERE MOD (a.num, b.div) = b.div - 1
        GROUP BY num
          HAVING COUNT (*) = :input)

MIN(NUM)
----------
2519

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this question