Post date: Oct 23, 2014 12:23:7 AM
"Are two sequences of three 4 digit prime numbers where each of the numbers is a permutation of the others and the difference between the first and second is the same as that between the second and the third. One is 1487, 4817, 8147. Find the other and concatenate the three numbers in sequence."
This is a simple query on a table of 4 digit primes. This is small enough that I can calculate it with basic brute force division. The permutation detection method I've chosen this time is to count the quantity of each digit from 0 to 9 and checking to make sure they all the same ... this means that the same digits are in each answer.
CREATE TABLE #Integers (i int not null primary key clustered)
; WITH Integers (i) AS
(
SELECT 2
UNION ALL
SELECT i + 1
FROM Integers
WHERE i < 9999
)
INSERT INTO #Integers (i)
SELECT i
FROM Integers
OPTION (MAXRECURSION 10000)
; WITH Primes (i) AS
(
SELECT i.i
FROM #Integers i
WHERE i.i >= 1000
AND NOT EXISTS (SELECT 1
FROM #Integers d
WHERE i.i % d.i = 0
AND d.i <= SQRT(i.i))
),
PrimesWithCounts AS
(
SELECT p.i
, 4 - LEN(REPLACE(p.i,'0','')) AS Count0
, 4 - LEN(REPLACE(p.i,'1','')) AS Count1
, 4 - LEN(REPLACE(p.i,'2','')) AS Count2
, 4 - LEN(REPLACE(p.i,'3','')) AS Count3
, 4 - LEN(REPLACE(p.i,'4','')) AS Count4
, 4 - LEN(REPLACE(p.i,'5','')) AS Count5
, 4 - LEN(REPLACE(p.i,'6','')) AS Count6
, 4 - LEN(REPLACE(p.i,'7','')) AS Count7
, 4 - LEN(REPLACE(p.i,'8','')) AS Count8
, 4 - LEN(REPLACE(p.i,'9','')) AS Count9
FROM Primes p
)
SELECT CONVERT(varchar(12),pc1.i) + CONVERT(varchar(12),pc2.i) + CONVERT(varchar(12),pc3.i)
FROM PrimesWithCounts pc1
INNER JOIN PrimesWithCounts pc2
ON pc1.Count0 = pc2.Count0
AND pc1.Count1 = pc2.Count1
AND pc1.Count2 = pc2.Count2
AND pc1.Count3 = pc2.Count3
AND pc1.Count4 = pc2.Count4
AND pc1.Count5 = pc2.Count5
AND pc1.Count6 = pc2.Count6
AND pc1.Count7 = pc2.Count7
AND pc1.Count8 = pc2.Count8
AND pc1.Count9 = pc2.Count9
AND pc1.i < pc2.i
INNER JOIN PrimesWithCounts pc3
ON pc2.Count0 = pc3.Count0
AND pc2.Count1 = pc3.Count1
AND pc2.Count2 = pc3.Count2
AND pc2.Count3 = pc3.Count3
AND pc2.Count4 = pc3.Count4
AND pc2.Count5 = pc3.Count5
AND pc2.Count6 = pc3.Count6
AND pc2.Count7 = pc3.Count7
AND pc2.Count8 = pc3.Count8
AND pc2.Count9 = pc3.Count9
AND pc2.i < pc3.i
AND pc3.i - pc2.i = pc2.i - pc1.i
WHERE pc1.i <> 1487
DROP TABLE #Integers