Post date: Nov 08, 2014 12:19:4 AM
"What is the smallest positive integer where the number multiplied by 1, 2, 3, 4, 5, and 6 all contain the same digits in different orders."
This is simple but simpler in Python than in SQL. If you sort the characters in each string, then all six of our numbers will be identical once sorted. There is no good way to do this in SQL, so most of the 1-2 minutes is spent doing the sorting. First I break each number up into separate rows, one for each digit, and then I order by the digits.
I'll make a SWAG and assume that there is an answer under a million.
CREATE TABLE #Ten (i INT PRIMARY KEY NOT NULL)
INSERT INTO #Ten VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)
; WITH Integers AS
(
SELECT o.i +
(10 * d.i) +
(100 * h.i) +
(1000 * k.i) +
(10000 * k10.i) +
(100000 * k100.i) AS i
, k100.i AS k100
, k10.i AS k10
, k.i AS k
, h.i AS h
, d.i AS d
, o.i AS o
FROM #Ten o
CROSS JOIN #Ten d
CROSS JOIN #Ten h
CROSS JOIN #Ten k
CROSS JOIN #Ten k10
CROSS JOIN #Ten k100
),
TempIntegers (i, digit) AS
(
SELECT i, k100 FROM Integers
UNION ALL SELECT i, k10 FROM Integers
UNION ALL SELECT i, k FROM Integers
UNION ALL SELECT i, h FROM Integers
UNION ALL SELECT i, d FROM Integers
UNION ALL SELECT i, o FROM Integers
)
SELECT *
INTO #TempIntegers
FROM TempIntegers
WHERE i > 0
CREATE INDEX IX_TempIntegers ON #TempIntegers(i)
-- Save each integer along with the sorted string.
CREATE TABLE #Integers (i int primary key not null, sorted varchar(10) NOT NULL)
INSERT INTO #Integers (i, sorted)
SELECT DISTINCT i,
(SELECT N'' + digit
FROM #TempIntegers t2
WHERE t2.i = t1.i
ORDER BY digit
FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)')
FROM #TempIntegers t1
-- Find the lowest number where the sorted number is the same when multiplied by 2 through 6.
SELECT MIN(i.i)
FROM #Integers i
INNER JOIN #Integers i2
ON i2.i = i.i * 2
AND i2.sorted = i.sorted
INNER JOIN #Integers i3
ON i3.i = i.i * 3
AND i3.sorted = i.sorted
INNER JOIN #Integers i4
ON i4.i = i.i * 4
AND i4.sorted = i.sorted
INNER JOIN #Integers i5
ON i5.i = i.i * 5
AND i5.sorted = i.sorted
INNER JOIN #Integers i6
ON i6.i = i.i * 6
AND i6.sorted = i.sorted
DROP TABLE #Integers
DROP TABLE #TempIntegers
DROP TABLE #Ten