How to get all the digits of a variable in C?

1

I have to do a function that tests divisibility by 3, return% with% if it is divisible by 3. Otherwise return% with%. Following the rule: A number is divisible by 3 when the sum of its digits is divisible by three.

I have the following variables:

int dividendo;
int divisor;

And I have the following function:

int divisibilidade3(int num);

I need to separate the digits of the true variable, for example, when the user enters the false splitter I will call the dividendo function and check if the final digit ends with 3, 6 or 9.

For example, if the user enters the number 3 , I need to break this number into parts, then: divisibilidade3 , as is 25848 the final result, then it is divisible by 3. p>

The function should repeat the process of summation of digits of the results obtained until the sum is a one-digit number. If this digit is equal to 3, 6, or 9, so the original number is divisible by 3.

I will have to follow all these rules using the divisibility criteria. If anyone can help me, I'm grateful.

    
asked by anonymous 09.05.2017 / 07:37

2 answers

2
#include <stdio.h>

int Divisibilidade( int num )
{
    int res = 0;

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

    if(res > 9)
        return Divisibilidade( res );
    else
        return (res%3);
}


int main()
{
    int n;

    while(1)
    {
        scanf("%d", &n);

        printf("O numero %se divisivel.\n", !Divisibilidade(n) ? "" : "nao ");
    }

    return (0);
}
    
09.05.2017 / 08:59
0

I suspect that your teacher simply imagines that you will transform the number into a string using snprintf() , and then iterate over the sequence:

#include <stdio.h>
#include <stdlib.h>

int
divisivel_por_3(int num) {
    char algs[12];
    char * ptr;

    // Se o número for negativo, troca o sinal (não afeta a divisibilidade)
    if (num < 0) num = -num;
    do {
        // Transforma o número em string
        if (snprintf(algs, sizeof(algs), "%d", num) < 1) {
            fprintf(stderr, "Falha na determinação dos algarismos de %d\n", num);
            exit(EXIT_FAILURE);
        }
        // itera sobre os algarismos de num, substituindo-o
        // pela soma de seus próprios algarismos
        for (num = 0, ptr = algs; *ptr; ptr ++) {
            num += (*ptr) - '0'; // transforma o dígito ASCII '0'-'9' no inteiro 0-9
    } while (num >= 10);

    return (num == 3) || (num == 6) || (num == 9);
}
    
09.05.2017 / 20:01