OraQA

Oracle Question and Answer


Latest Comments

  • Laurent Schneider:
    if you like a Base64 format, maybe this… select utl_raw.cast_to_varchar 2(...

  • hsafra:
    You need to give more specs for the question: What letter are acceptable? What letters aren’t? Do you...

  • ragunathansd:
    I am not inserting sequence numbers from database. I need to populate the data in a grid. If a user...

  • gamyers:
    “redo log file gets full” That is the nature of a redo log file. It gets full, switched and...

Comments RSS feed


  • 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 Change One Puzzle in SQL

May 5th, 2008 By Frank Zhou

The following is an interesting puzzle posted by Usenet rec-puzzles.org archive:

What is the smallest number that cannot be made prime by changing a single digit?

variable input number
exec :input := 10000;

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

SELECT min(not_prime_num) Min_Chang_A_digit_Not_Prime
FROM
(SELECT num,
        CASE WHEN num + 1 != lead(num) OVER (ORDER BY num)
             THEN (num +1) * 10 END AS not_prime_num
FROM
(SELECT DISTINCT trunc(num/10) as num
 FROM
 (WITH data AS (SELECT LEVEL+1 num FROM dual
                WHERE LEVEL+1 <=:input
                CONNECT BY LEVEL <=:input)
  SELECT num
  FROM  data,
  (SELECT d1.num * d2.num as n2
     FROM data d1, data d2
     WHERE  d1.num <= d2.num
     AND d1.num <= sqrt(:input)
     AND d1.num * d2.num <= :input)
     WHERE num = n2(+)
     AND n2 IS NULL
  )
 )
)
WHERE not_prime_num IS NOT NULL;

MIN_CHANG_A_DIGIT_NOT_PRIME
---------------------------
                        200

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this question