# Evil ScienceA whole load of stuff

28Mar/110

## Project Euler Problem 37 Solution in TSQL

This is a solution for Project Euler Problem 37. It makes uses of a temporary table called #atkin which is populated with prime numbers using the TSQL routine that uses the Sieve of Atkin, which is also located on this site.

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?

```/*
process the prime number list
*/

/*
the number we are examining can't be single digits or contain zeros
*/
drop table #candidates
select num
into #candidates
from #atkin
where charindex('0', cast(num as varchar)) = 0

declare @ctr as integer
declare @del as integer

set @ctr = 1
set @del = 0

/*
delete from the candidate list any number that doesn't have a
shorter counterpart in the list of prime numbers, increasing
the string size by 1 with every loop, and bailing out of when
we stop deleting things
*/
while (@del > 0)

begin

delete from #candidates
from #candidates c1
left outer join #atkin a1
on left(c1.num,@ctr) = a1.num
left outer join #atkin a2
on right(c1.num,@ctr) = a2.num
where a1.num is null
or a2.num is not null

set @del = @@rowCount
set @ctr = @ctr + 1

end

/*