Fixed memory leak.
Smarter calculation of n.