Edited algorithm for calculating n