27Mar/110
Project Euler Problem 61 Solution in TSQL
/* generate the number range */ create table #polygonalnumbers ( ctr int , val bigint , poltype varchar(3) ) declare @ctr as integer set @ctr = 1 while (@ctr < 1000) begin insert into #polygonalnumbers select @ctr,(@ctr*(@ctr+1))/2,'tri' insert into #polygonalnumbers select @ctr,@ctr * @ctr *@ctr,'sqr' insert into #polygonalnumbers select @ctr,(@ctr*((3*@ctr)-1))/2 ,'pnt' insert into #polygonalnumbers select @ctr,(@ctr*((2*@ctr)-1)) ,'hex' insert into #polygonalnumbers select @ctr,(@ctr*((5*@ctr)-3))/2 ,'hep' insert into #polygonalnumbers select @ctr,(@ctr*((3*@ctr)-2)) ,'oct' set @ctr = @ctr + 1 end /* disregard */ delete from #polygonalnumbers where LEN(val) <> 4 /* output the answer */ select distinct num1.val + num2.val + num3.val + num4.val + num5.val + num6.val from #polygonalnumbers num1 inner join #polygonalnumbers num2 on RIGHT (num1.val,2) = LEFT(num2.val,1) and num2.poltype <> num1.poltype inner join #polygonalnumbers num3 on RIGHT (num2.val,2) = LEFT(num3.val,2) and num3.poltype <> num2.poltype and num3.poltype <> num1.poltype inner join #polygonalnumbers num4 on RIGHT (num3.val,2) = LEFT(num4.val,2) and num4.poltype <> num3.poltype and num4.poltype <> num2.poltype and num4.poltype <> num1.poltype inner join #polygonalnumbers num5 on RIGHT (num4.val,2) = LEFT(num5.val,2) and num5.poltype <> num4.poltype and num5.poltype <> num3.poltype and num5.poltype <> num2.poltype and num5.poltype <> num1.poltype inner join #polygonalnumbers num6 on RIGHT (num5.val,2) = LEFT(num6.val,2) and num6.poltype <> num5.poltype and num6.poltype <> num4.poltype and num6.poltype <> num3.poltype and num6.poltype <> num2.poltype and num6.poltype <> num1.poltype and RIGHT (num6.val,2) = LEFT(num1.val,2)
Easy! There are, however, a couple of deliberate errors, that can be easily located with some patience. I don't want to make things to easy for you little scamps, do I?
Leave a comment