Project Euler‎ > ‎

Project euler problem 34

posted Aug 27, 2009, 1:12 AM by Peter Henell   [ updated Aug 27, 2009, 1:15 AM ]
drop table problem34
CREATE TABLE problem34 (numValue BIGINT, facSum BIGINT, isspecial bit);


GO

ALTER FUNCTION dbo.Factorial ( @iNumber BIGINT )
RETURNS BIGINT
AS
BEGIN
DECLARE @i BIGINT

SET @i =
CASE @iNumber
WHEN 1 THEN 1
WHEN 2 THEN 2
WHEN 3 THEN 6
WHEN 4 THEN 24
WHEN 5 THEN 120
WHEN 6 THEN 720
WHEN 7 THEN 5040
WHEN 8 THEN 40320
WHEN 9 THEN 362880
WHEN 0 THEN 1
ELSE 1 / 0
END

RETURN (@i)
END
GO


GO
ALTER FUNCTION CalcFacSum(@input BIGINT) RETURNS BIGINT
AS
BEGIN
DECLARE @ret BIGINT
DECLARE @str VARCHAR(20)
SET @ret = 0
SET @str = CONVERT(VARCHAR(20), @input)

WHILE LEN(@str) > 0
BEGIN
SET @ret = @ret + dbo.Factorial(CONVERT(BIGINT, LEFT(@str, 1)))
SET @str = RIGHT(@str, LEN(@str) - 1)
END

return @ret
END
GO

DECLARE @counter BIGINT
DECLARE @tmpFacSum BIGINT
DECLARE @isSpecial BIT

SET @tmpFacSum = 0
SET @counter = 3

WHILE @counter < 3628800 -- 9999999
BEGIN
SET @tmpFacSum = dbo.CalcFacSum(@counter)

SET @isSpecial =
CASE @tmpFacSum
WHEN @counter THEN 1
ELSE 0
END

IF @isSpecial = 1
INSERT INTO problem34 VALUES(@counter, @tmpFacSum, @isSpecial)

SET @counter = @counter + 1
END

select * from problem34

SELECT SUM(facSum) from problem34
--40730
Comments