How to reuse a function correctly in C?

2

I have the following functions:

int divisibilidade3(int num);
int divisibilidade9(int num);
int testarDivisibilidade(int dividendo, int divisor);

With the testarDivisibilidade function I'm going to test all functions, whether they return true or false . But my problem is that I need to reuse the divisibilidade3 function inside the divisibilidade9 function, since I need to check whether a number is divisible by 9. But to be divisible by 9, it must be divisible 2 times by 3.

Code:

int divisibilidade3(int num) {

int res = 0;

while( num > 0 )
{
    res += num % 10;
    num /= 10;
}

if(res > 9)
    return divisibilidade3(res);
else
    return ! (res % 3);


}

int divisibilidade9(int num) {
    if(divisibilidade3(num) == 1) {
        return 1;
    }
    else {
        return 0;
    }
}

I'm sure the syntax is wrong inside the if-else of the divisibilidade9 function, even though it does not give the compile error, but I want to know how I can do to reuse 2 times the same function within if do the verification.

OBS: I am asking several separate questions about the same exercise because if you put everything in the same question, my doubts about it will be confusing. If I am doing something wrong, please tell me.

    
asked by anonymous 11.05.2017 / 18:05

1 answer

2

If the divisibility functions need to return true and false, then you really can not return some information that allows you to check the number by 9. But it has a trick:

int
divisibilidade9(int num) {
    // "guard expression": se não for divisível por 3, pare já
    if (! divisibilidade3(num)) return 0;
    // Se chegou aqui, é divisível por 3; então veja se o
    // QUOCIENTE da divisão por 3 também é divisível por 3
    return divisibilidade3(num/3);
}

That is, once you establish (via call to divisibilidade3 that the number is divisible by 3, then you can perfectly divide it by 3. If that third also is divisible by 3, then the original number is divisible by 9 ...

    
11.05.2017 / 20:21