Post date: Jun 26, 2014 11:58:3 PM
"Of the series from 1/1, 1/2, 1/3, ... 1/1000, which number has the longest repetend (the repeating part of a repeating decimal)?"
There are several interesting facts about repetends. None of them are useful in solving this problem easily. It has to be done in a tedious long division way, looking for the point at which the remainder has already been found for the current number or is zero. In the first case, this is the point at which the number starts to repeat, and in the second, it means it isn't a repeating decimal.
Keep in mind that if the numer has a few digits before the repetition starts, those don't count. The problem asks for the longest repeating part, not the longest decimal part before repeating. If you want to see something interesting, look at divisors that are multiples of 7. The repeating part, even when it has a few padding digits, is always the same.
CREATE FUNCTION dbo.GetPeriod (@Divisor int)
RETURNS INT
AS
BEGIN
DECLARE @Dividend int = 1, @Result int
DECLARE @History TABLE (id INT PRIMARY KEY NOT NULL IDENTITY(1,1), remainder INT NOT NULL)
WHILE 1 = 1
BEGIN
SET @Dividend = 10 * (@Dividend % @Divisor)
-- Terminating decimal.
IF @Dividend = 0 RETURN 0
IF EXISTS (SELECT 1 FROM @History WHERE remainder = @Dividend) BREAK
INSERT INTO @History (remainder) VALUES (@Dividend)
END -- While
DELETE FROM @History WHERE id < (SELECT TOP 1 id FROM @History WHERE remainder = @Dividend)
SELECT @Result = COUNT(*)
FROM @History
RETURN @Result
END
GO
CREATE TABLE #Integers (i INT PRIMARY KEY NOT NULL)
; WITH Ten(i) AS
(
SELECT 0
UNION ALL
SELECT i + 1
FROM Ten
WHERE i < 9
)
INSERT INTO #Integers
SELECT 100 * h.i + 10 * t.i + o.i + 1
FROM Ten o
CROSS JOIN Ten t
CROSS JOIN Ten h
SELECT TOP (1) i, dbo.GetPeriod(i)
FROM #Integers i
ORDER BY 2 DESC
DROP TABLE #Integers
GO
DROP FUNCTION dbo.GetPeriod
GO