Post date: Dec 07, 2014 1:25:39 AM
"Consider the formula a ** b, where a and b are positive integers less than 100. If you add up the digits in each answer, what is the greatest sum you will find?"
Looks like I need to use the MultiplyBigNumbers function again, because we're talking about numbers hundreds of digits long.
CREATE FUNCTION dbo.MultiplyBigNumbers (@Number1 varchar(max), @Number2 varchar(max))
RETURNS varchar(max)
AS BEGIN
...
GO
CREATE FUNCTION dbo.SumDigits (@Number varchar(1000))
RETURNS bigint
AS
BEGIN
IF @Number IS NULL
RETURN 0
DECLARE @Digits TABLE (i BIGINT NOT NULL)
WHILE 1 = 1
BEGIN
IF @Number = '' BREAK
INSERT INTO @Digits SELECT LEFT(@Number,1)
SET @Number = STUFF(@Number,1,1,'')
END
DECLARE @Result bigint
SELECT @Result = SUM(i)
FROM @Digits
RETURN @Result
END
GO
-- This is definitely clunkier than the setwise approach, but it allows me to calculate the power by multiplying times the previous result.
-- Considering how slow string multiplication is, any little time-saver is good.
-- Just start with a, multiply by itself up to 100 times, and then increment a and repeat. Keep track of the largest result and forget anything smaller.
DECLARE @Result varchar(1000), @Sum int, @BestSum int = 0, @a int = 2, @b int = 2
WHILE 1 = 1
BEGIN
SET @Result = @a
SET @b = 2
WHILE 1 = 1
BEGIN
SET @Result = dbo.MultiplyBigNumbers(@Result, @a)
SET @Sum = dbo.SumDigits(@Result)
IF @Sum > @BestSum
SET @BestSum = @Sum
SET @b = @b + 1
IF @b >= 100 BREAK
END -- Inner loop
SET @a = @a + 1
IF @a >= 100 BREAK
END -- Outer loop
SELECT @BestSum
GO
DROP FUNCTION dbo.MultiplyBigNumbers
GO
DROP FUNCTION dbo.SumDigits
GO