Jan 15, 2019 at 11:14am Jan 15, 2019 at 11:14am UTC
for (int div = n-1 ; 0; div -= 1)
In C++ the middle part is the condition.
Here, 0 becomes boolean false.
So the condition is always false.
So the loop never runs.
Probably you meant
for (int div = n-1 ; div > 0; div -= 1 )
Jan 15, 2019 at 11:33am Jan 15, 2019 at 11:33am UTC
1 2 3 4 5 6 7 8 9 10
int findGreatestDivisor(int n) {
if ( n < 0 ) n = -n ; // if negative, make it positive
for (int div = n-1 ; div > 0; div -= 1) {
if ( n % div == 0 ) return div;
}
return 1 ; // if the loop never executed (if n == 0 or n == 1)
}
Last edited on Jan 15, 2019 at 11:33am Jan 15, 2019 at 11:33am UTC
Jan 15, 2019 at 2:19pm Jan 15, 2019 at 2:19pm UTC
some little things to help you along. None of this is 'wrong'
div-- is the same as div -=1 and is preferred shorthand in c++
n = std::abs(n); //c++ has an absolute value in <cmath>
if( n < 0 ) n = -n ; // if negative, make it positive