Improve prime factorization function