Post date: Jan 11, 2015 12:48:15 AM
"Find the set of six cyclic numbers (the last 2 digits of each number is the first 2 of the next number), each number matches one of the following formulae (not necessarily in order): n(n+1)/2, n*n, n(3n-1)/2, n(2n-1), n(5n-3)/2, n(3n-2). Sum the sliced numbers."
The problem states that each number is cyclic with the "next" number. This implies an order. There is no order; it is random, which is why I added a clarification. That makes the solution a bit hairier but not too bad. We just need to make sure that no number is counted twice.
Each series is limited by the fact that they must be under 9999.
WITH Integers (n) AS
(
SELECT 1
UNION ALL
SELECT n + 1
FROM Integers
WHERE n < 150
),
Tri (t) AS
(
SELECT CONVERT(int,0.5 * n * (n + 1))
FROM Integers
WHERE n BETWEEN 45 AND 140
),
Squ (s) AS
(
SELECT SQUARE(n)
FROM Integers
WHERE n BETWEEN 32 AND 99
),
Pent (p) AS
(
SELECT CONVERT(int,0.5 * n * (3 * n - 1))
FROM Integers
WHERE n BETWEEN 26 AND 81
),
Hex (h) AS
(
SELECT n * (2 * n - 1)
FROM Integers
WHERE n BETWEEN 23 AND 70
),
Hept (e) AS
(
SELECT CONVERT(int,0.5 * n * (5 * n - 3))
FROM Integers
WHERE n BETWEEN 21 AND 63
),
Oct (o) AS
(
SELECT n * (3 * n - 2)
FROM Integers
WHERE n BETWEEN 19 AND 58
),
Numbers (n, t) AS
(
SELECT t, 3
FROM Tri
UNION
SELECT s, 4
FROM Squ
UNION
SELECT p, 5
FROM Pent
UNION
SELECT h, 6
FROM Hex
UNION
SELECT e, 7
FROM Hept
UNION
SELECT o, 8
FROM Oct
)
-- Find the cycle by matching the left 2 digits of one number with the right 2 of the previous number.
-- When getting the next number, avoid looping back by excluding numbers already in the row.
SELECT n1.n + n2.n + n3.n + n4.n + n5.n + n6.n
FROM Numbers n1
INNER JOIN Numbers n2 ON LEFT(n2.n,2) = RIGHT(n1.n,2) AND n2.t NOT IN (n1.t)
INNER JOIN Numbers n3 ON LEFT(n3.n,2) = RIGHT(n2.n,2) AND n3.t NOT IN (n1.t, n2.t)
INNER JOIN Numbers n4 ON LEFT(n4.n,2) = RIGHT(n3.n,2) AND n4.t NOT IN (n1.t, n2.t, n3.t)
INNER JOIN Numbers n5 ON LEFT(n5.n,2) = RIGHT(n4.n,2) AND n5.t NOT IN (n1.t, n2.t, n3.t, n4.t)
INNER JOIN Numbers n6 ON LEFT(n6.n,2) = RIGHT(n5.n,2) AND n6.t NOT IN (n1.t, n2.t, n3.t, n4.t, n5.t)
WHERE LEFT(n1.n,2) = RIGHT(n6.n,2)
AND n1.t = 3
OPTION (MAXRECURSION 150)