Post date: Dec 02, 2014 1:36:19 AM
"Consider a process where a number is added to its palindrome. How many numbers are there, below 10000, that require over 50 iterations of this process before producing a palindromic result?"
CREATE FUNCTION dbo.Lychrel50 (@Number numeric(38,0))
RETURNS INT
AS
BEGIN
/*
Find a number that might be a Lychrel number, at least as far as we can tell after the first 50 iterations. Return 1 if true, 0 if false.
This has to be stepwise code. The problem wants us to iterate 50 times and check the results.
*/
DECLARE @c int = 1
WHILE @c <= 50
BEGIN
SET @Number = @Number + REVERSE(@Number)
IF RTRIM(@Number) = REVERSE(@Number)
RETURN 0
SET @c = @c + 1
END -- Loop 50
RETURN 1
END
GO
WITH Integers (i) AS
(
SELECT 1
UNION ALL
SELECT i + 1
FROM Integers
WHERE i < 10000
)
SELECT SUM(dbo.Lychrel50(i))
FROM Integers
OPTION (MAXRECURSION 10000)
GO
DROP FUNCTION dbo.Lychrel50
GO