Cleaned up lehmer's implementation