# Sieve exercise: Why does my solution cause errors?

Hi there,

I wrote a solution to the sieve exercise in Fortran.

I rather expected it to work , since I compiled a version of this on my own computer (together with a minimal main program which calles prime() for the argument values used in the test) which works fine.
However I keep getting "An error occurred while running your tests. " and I can’t figure out what’s going wrong.

Best Regards,
Eric

Here’s the code:

``````module sieve
implicit none

contains

function primes(limit) result(array)
integer, intent(in) :: limit
integer, allocatable :: array(:)
integer :: k
integer, allocatable:: numbers(:)
integer :: sqrt_limit
integer :: n = 2
if (limit > 1) then
allocate(numbers, source=[(k,k=1,limit)])
sqrt_limit = int(sqrt(real(limit)))
do while (n<= sqrt_limit)
do k=n*n,limit,n
numbers(k) = 0
end do
n = n+1
do while (n==0)
n= n+1
end do
end do
array = pack(numbers, numbers>1)
else
allocate(array(0))
end if
end function primes

end module sieve

``````

How quickly does your code pass the tests when running locally?

There are two separate issues, one in your solution and the other in the test module:

1. Initialising `integer :: n = 2` implies that `n` has the `save` attribute, which means that it maintains state across invocations of the `primes` function. That causes test 4 to fail: `n` is 4 (greater than √ 13) when test 4 starts, so `primes(13)` returns all integers from 2 to 13.

2. When a test fails, the test module attempts to write out a message comparing the incorrect result to the expected result. In this case, the arrays are too long for that message. Of course, that shouldn’t cause an error! Thanks for highlighting this — it probably hasn’t come up before because there weren’t any exercises whose expected result is an array of more than a few elements.

Thanks a lot for your answer. After separating the initialization of n from the definition, I was successfully able to submit the solution.

@ErikSchierboom I submitted a PR that should solve this: