Spoj AMR11E code memoization technique trouble

c-plus-plus
memoization
spoj

#1

The question is

My problem is why does the input
1 2
gives output zero?

My code is:

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;


int a[1000]={-1};
int prime[1500];

int lucky(int);
void primes();

int main()
{
	
	int t,n;
	scanf("%d",&t);
	primes();
	
	while(t--)
	{
		scanf("%d",&n);
		a[0]=30;
		printf("%d

",lucky(n));
}

	return 0;
}

int lucky(int n)
{

	int i,j,count,r;
	if(a[n-1]!=-1)
	return a[n-1];
	else
	{	
		if(a[n-2]==-1)
		r=lucky(n-1);
		for(i=a[n-2]+1;i<2665;i++)
		{	
			count=0;
			for(j=0;prime[j]<sqrt(n);j++)
			{
				if(i%prime[j]==0)
				{
					count++;
					if(count>=3)
					break;
				}
			}
			if(count>=3)
			break;
		}
		
		a[n-1]=i;
		return i;
	}
}

void primes()
{	
		int i,j,flag,k=0;;
	 	for(i=1;i<=2665;i++)
              {
                                 
                    flag=1;
                    for(j=2;j<=sqrt(i);j++)
                    {
                                if(i%j==0)
                                {         
                                flag=0;
                                break;     
                                }
                    }
                    if(flag==1)
                    {
                    	prime[k]=i;
                    	k++;
                    }
              }
}

My technique is to first store the primes in an array, then divide the numbers to get the answer.
It would be of great help if anyone can tell me where is the error in my code?