for large n, use maps instead of arrays for memoization; while(cin>>N) works