ccs50luhn

Sum up digits for Luhns algorithm in c


I'm trying to sum up all of the multiplied digits but I have no idea how to implement it. At the moment it prints 0 1 2 0 1 0 1 0 1 0 1 2 8 0 0 0 0 0 0 0 0.

void get_digit(long credit_num, long n)
{
    int sum = 0;
    credit_num = ((credit_num / n) % 10) * 2;
    while(credit_num > 9) //do till num greater than  0
    {
        //int mod
        int splitDigit = credit_num % 10;
        printf("%d ", sum); //print the digit.
        sum = sum+splitDigit;

        credit_num = credit_num / 10;
    }

    printf("%li ", credit_num);
}

long check_sum(long credit_num, int creditLength)
{
    bool valid = false;
    long n = 10;

    //Gets digit in number
    for (int i = 0; i < creditLength; i++)
    {
        get_digit(credit_num, n);
        n*=100;
    }

    return credit_num;
}

Solution

  • I would store the credit card number in a string instead. If that's not wanted, you can convert it to a string for the purpose of calculating the luhn check digit.

    Example:

    #include <ctype.h>
    #include <stdio.h>
    #include <string.h>
    
    // An example impl. calculating the luhn check digit using a string.
    // Replace with your own if this doesn't appeal to you.
    int luhn(const char *str)
    {
        static const int add[2][10] = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
                                       {0, 2, 4, 6, 8, 1, 3, 5, 7, 9}};
        int sum = 0;
        
        for (unsigned i = strlen(str), a = 1; i-- > 0; a = (a + 1) % 2) {
            if (!isdigit((unsigned char)str[i])) return -1;
            sum += add[a][str[i] - '0'];
        }
        
        return 10 - (sum % 10);
    }
    
    int check_sum(long credit_num)
    {
        // convert credit_num to a string first:
        char buf[20];
        int len = snprintf(buf, sizeof buf, "%ld", credit_num);
        if(len >= sizeof buf) return -1;
    
        return luhn(buf); // and call the luhn function
    }
    
    int main()
    {
        printf("%d\n", check_sum(7992739871)); // prints 3
    }