Help in Next number problem

Hi All,

I am solving the following problem on stack:

I am getting runtime error (NZEC)

https://www.spoj.com/submit/JNEXT/id=23834147.

Please help me