How to correctly divide a number up to only one digit in C?

5

I have the following function:

divisibilidade11(int num);

And the following variables:

int dividendo;
int divisor;

When the user enters the variable 11 for the variable divisor the function divisibilidade11 will be called and will check if the variable dividendo is divisible by divisor . And to check whether it is divisible or not, you will have to follow the criteria: If the sum of this odd-order digit (Sp) subtracted from the odd-order sum (Si) results in 0 or a divisible number of 11, it returns true and if not, it returns false .

Example:

  

The user enters the number 2376 for the variable dividendo ;

     

The user enters the number 11 for the variable divisor ;

     

The divisibilidade11 function is called to check whether it is divisible or not;

     

The sum of the odd (Si) = 3 + 6 = 9 is made;

     

The sum of the pairs (Sp) = 2 + 7 = 9 is made;

     

Si - Sp = 0; Therefore, therefore, 2376 is divisible by 11.

     

NOTE: The right-most digit is the first of the odd order.

Example how it would appear to the user:

The function divisibilidade11 has to repeat the process until the result is a one-digit number. If this digit is equal to 0, then the original number is divisible by 11.

    
asked by anonymous 14.05.2017 / 02:37

1 answer

3

Using Strings

Knowing that the maximum value for integers that most computers currently support is up to 19 digits, I'll use a 20-digit string to perform this operation.

#include <string.h>
#include <stdio.h>    

char divisibilidade11(long long int dividendo){
    char array_numerico[20] = "";
    int total_par = 0;
    int total_impar = 0;
    snprintf(array_numerico, 20, "%lld", dividendo);
    for(char iterador = strlen(array_numerico) - 1, par = 0; iterador >= 0; iterador -= 1){
        if(!par){
            total_impar += array_numerico[iterador] - 48;
            par = 1;
        }
        else{
            total_par += array_numerico[iterador] - 48;
            par = 0;
        }
    }
    if((total_par - total_impar) == 0 || ((total_par - total_impar) % 11 == 0)){
        return 1;
    }
    else{
        return 0;
    }
}

Using Decimal Math Operations

char divisibilidade11(long long int dividendo){
    int total_par = 0;
    int total_impar = 0;
    char par = 0;
    while(dividendo != 0){
        if(!par){
            total_impar += (dividendo % 10);
            par = 1;
        }
        else{
            total_par += (dividendo % 10);
            par = 0;
        }
        dividendo /= 10;
    }
    if((total_par - total_impar) == 0 || (total_par - total_impar) % 11 == 0)
        return 1;
    else return 0;
}
    
14.05.2017 / 05:59