Post date: May 31, 2014 1:19:31 AM
"What is 2 ** 1000?" Oh, technically, the Project Euler question actually asks for the sum of the digits in the number, but the reason it does that because asking the user to type the entire 302 digit answer into a web form would be insane. Quite a lot about the design of the problems is based around the fact that the web form contains only one input and a captcha. In any case, here we need to calculate a number bigger than any of the SQL datatypes, so I am using the string addition functions AddBigNumbers and ShiftStringRight I created to generate the 1000th Fibonacci number.
The nice thing with powers of 2 is that each result is the sum of the previous result added to itself, so I get to save implementing string multiplication for another day.
-- See link
CREATE FUNCTION dbo.ShiftStringRight
...
GO
-- See link
CREATE FUNCTION dbo.AddBigNumbers
...
GO
-- Calculate 2**1000
DECLARE @c int = 1, @answer varchar(512) = '2'
WHILE 1 = 1
BEGIN
SET @answer = dbo.AddBigNumbers(@answer, @answer)
SET @c = @c + 1
IF @c >= 1000 BREAK
END -- While
SELECT @answer
-- Sum up the digits
CREATE TABLE #SumDigits (i int NOT NULL)
WHILE 1 = 1
BEGIN
INSERT INTO #SumDigits
SELECT LEFT(@answer,1)
SET @answer = STUFF(@answer,1,1,'')
IF @answer = '' BREAK
END -- While
SELECT SUM(i)
FROM #SumDigits
GO
DROP FUNCTION dbo.AddBigNumbers
GO
DROP FUNCTION dbo.ShiftStringRight
GO