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 problem34CREATE TABLE problem34 (numValue BIGINT, facSum BIGINT, isspecial bit);GOALTER FUNCTION dbo.Factorial ( @iNumber BIGINT )RETURNS BIGINTASBEGINDECLARE @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 ENDRETURN (@i)ENDGOGOALTER FUNCTION CalcFacSum(@input BIGINT) RETURNS BIGINTASBEGIN 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 @retENDGODECLARE @counter BIGINTDECLARE @tmpFacSum BIGINTDECLARE @isSpecial BITSET @tmpFacSum = 0SET @counter = 3WHILE @counter < 3628800 -- 9999999BEGIN 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 + 1ENDselect * from problem34SELECT SUM(facSum) from problem34--40730