Help with my (very basic) code

Hello,

I am completely new to C++ (used to Python) and needed some advice on my code. I want to translate the following code (Python) into C++
1
2
3
4
def findGreatestDivisor(n):
  for divisor in range(n-1,0,-1):
      if n%divisor == 0: 
      return divisor


What I have done in C++:

1
2
3
4
5
6
7
int findGreatestDivisor(int n) {
    for (int div = n-1 ; 0; div -= 1) {
        if ( n % div == 0) {
            return div;
        }
    }
}


but I get that "code will never be executed" error at the if-statement. Any help? Thanks in advice!!
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 )
Thanks! I still get the error message "Control may reach end of non-void function" though. This is my code now:

1
2
3
4
5
6
7
int findGreatestDivisor(int n) {
    for (int div = n-1 ; div > 0; div -= 1) {
        if ( n % div == 0) {
            return div;
        }
    }
}
I imagine it is a warning, not an error message.

If it bothers you (or if you ever call it with n=1) then change it to
1
2
3
4
5
6
7
8
int findGreatestDivisor(int n) {
    for (int div = n-1 ; div > 1; div -= 1) {
        if ( n % div == 0) {
            return div;
        }
    }
    return 1;
}


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
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

Topic archived. No new replies allowed.