Define a function named isDivisor that has two parameters of type int and returns a value of type bool. A call to isDivisor(m,n) should return true if and only if (iff) m divides n. For example isDivisor(6,24) will return true but isDivisor(5,24) will return false . Note that every number other than 0 divides 0. On the other hand, 0 divides no number.

Hint: use the % operator (but only when the second operand is not equal to 0, otherwise you will get a runtime error !)

Here is my solution:

bool isDivisor(int m, int n)
{
    if((m % n) == 0)
    {
        return true;
    }
    return false;
}

I can't seem to figure out what I am doing wrong in this function. Is there something I need to add or change in this solution? I would appreciate any help.

Switch m and n around in the if statement.

24 % 6 == 0
// not 6 % 24 == 6
25 % 6 == 1
// not 6 % 25 == 6

The arguments are backwards according to the way the % operator works.

isDivisor(m,n) == (n % m == 0)

..not the other way around.

Also, only when the second operand is not 0. So you need another check.

if (m == 0) {
    return false;
} else {
    return (n % m == 0)
}

...it also already returns a boolean so putting return true and return false is redundant.

Edited 2 Years Ago by chriswelborn

This question has already been answered. Start a new discussion instead.