moved k calculation out of loop