long factor( long number )
{
if( number < 0 ) return factor( -number ) ;
elseif( number == 0 ) return 0 ; // or throw
// find the largest integer less than or equal to the square root
// note: std::sqrt() is another function, we need everything to be in this one function
long root = 1 ;
while( root*root < number ) ++root ;
if( root*root > number ) --root ;
// start dividing from root downwards; the first divisor that divides evenly
// is the largest factor less than or equal to the square root
for( long divisor = root ; divisor > 1 ; --divisor )
if( number%divisor == 0 ) return divisor ; // largest factor less than or equal to root
return number ; // prime, there are no factors smaller than or equal to its square root
}
This was the final part of a larger project on functions and I couldn't seem to grasp it (factoring and prime stuff is always a toughie). I appreciate that you added in the comments for step-by-step outlining of the process.