Post date: Sep 14, 2014 10:11:11 PM
"Find the pair of integers where each number, their sum, and difference all are in the series n(3n−1)/2,if n is any positive integer, and the absolute value of their difference is the smallest. What is the absolute value of their difference (because the website has a single field for answers, which makes entry of two numbers difficult)?"
This is pretty simple. As n gets larger, the numbers get larger, and so the differences get larger too, so the record with the smallest difference will be the earliest. We can focus on smaller numbers near the beginning of the series. It isn't actually required to waste time looking at the absolute values, because the question says the difference of the numbers is in the series, which contains only positives, so the absolute value is also positive.
-- Load a table with the first 2500 numbers in the series. That should be good enough to play with.
CREATE TABLE #Pentagon (p INT PRIMARY KEY NOT NULL, n INT NOT NULL)
; WITH Pentagon (n,p) AS
(
SELECT 1, 1
UNION ALL
SELECT n + 1, CONVERT(int,0.5 * (n + 1) * (3 * (n + 1) - 1))
FROM Pentagon
WHERE n < 2500
)
INSERT INTO #Pentagon (n, p)
SELECT n, p
FROM Pentagon
OPTION (MAXRECURSION 2500)
-- Select the result. Easy as that.
SELECT p2.p - p1.p
FROM #Pentagon p1
CROSS JOIN #Pentagon p2
WHERE p1.p + p2.p IN (SELECT p FROM #Pentagon)
AND p2.p - p1.p IN (SELECT p FROM #Pentagon)
ORDER BY p2.p - p1.p
DROP TABLE #Pentagon