Function Loop Issue

Edit: Solved.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
long factor( long number )
{
    if( number < 0 ) return factor( -number ) ;
    else if( 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
}
Thank you!

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.

Thanks again and best wishes, JLBorges.
Topic archived. No new replies allowed.