Updated code added by Robert so it checks all factors