Post date: Dec 09, 2014 1:26:6 AM
"The square root of 2 can be approximated with the following series of calculations: 1 + 1/2, 1 + 1/(2 + 1/2), 1 + 1/(2 + 1/(2 + 1/2)), or 3/2, 7/5, 17/12, to the infinite continued fraction 1 + 1/(2 + 1/(2 + 1/(2 + ... ))). In the first 1000 elements in this series, how many contain a numerator with more digits than the denominator?"
This is a fairly simple operation. Add 1 to the fraction (add the denominator to the numerator), flip the numerator and denominator, and then add 1 again. Repeat.
The numbers here get very large, so we need to break out the string addition function once again.
CREATE FUNCTION dbo.ShiftStringRight
...
GO
CREATE FUNCTION dbo.AddBigNumbers
...
GO
DECLARE @counter int = 0, @answer int = 0, @d varchar(max) = 2, @n varchar(max) = 3, @temp varchar(max)
WHILE @counter <= 1000
BEGIN
-- If this were in a table, not variables, it would not be necessary to move the data into a temp variable first. A single update would change both.
-- But SQL Server treats variables in the same statement mysql treats tables (or used to, at least), going from left to right.
-- So to swap two variables I have to move var 1 into temp, var 2 into var 1, and temp into var 2.
SELECT @temp = dbo.AddBigNumbers(@n, @d), @n = @d
SELECT @d = @temp, @n = dbo.AddBigNumbers(@n, @temp)
IF LEN(RTRIM(@n)) > LEN(RTRIM(@d)) SET @answer = @answer + 1
SET @counter = @counter + 1
END -- While
SELECT @answer
GO
DROP FUNCTION dbo.ShiftStringRight
GO
DROP FUNCTION dbo.AddBigNumbers
GO