How to reuse a function correctly in C?

Asked

Viewed 129 times

2

I have the following functions :

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

With the function testarDivisibilidade I’ll test all the functions, if they return true or false. But my problem is that I need to reuse the function divisibilidade3 within the function divisibilidade9, because I need to verify whether a number is or is not divisible by 9. But to be divisible by 9, it needs to 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 function divisibilidade9, even not giving error in the compilation, but I want to know how I can do to reuse 2 times the same function within the if to make the check.

NOTE : I am asking several separate questions about the same exercise because if I put everything in the same question, my doubts about the subject will be confused. In case I’m doing something wrong, please tell me.

  • Honestly, this divisiveness function of his 9 mathematically does not make any sense.

  • @Anonimo I know this wrong, the problem is that according to the exercise I have to do this way. I have to reuse the divisibility function3 within the divisibility function9.

1 answer

2


If the divisibility functions need return true and false, so you really can’t return any information that allows you to verify the number by 9. But there’s 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, so you can perfectly well divide it by 3. If that third also is divisible by 3, so the original number is divisible by 9...

  • Again, you helped me, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.