I'm trying to work on the credit.c assignment by breaking it up into smaller tasks. Right now I'm trying to make a checksum function (eventually used to check the validity of a cc number). This is what I have:

#include <stdio.h>
#include <cs50.h>
#include <math.h>

int checksum(int num);

int main(void)
    int n = get_int("n: ");
    int check = checksum(n);
    printf("checksum: %i\n", check);

int get_count(int num)
    int count = 0;

        count += 1;
        num /= 10;
    while (num != 0);

    return count;

int checksum(int num)
    int sum = 0;
    int digits = get_count(num);
    int n = digits / 2;
    int i;

    for (i = 0; i < n; i++)
        int a = num % ((int) pow(100, 2*i)) / ((int) pow(100, 2*i - 1));
        int double_a = 2*a;

        if (double_a < 10)
            sum += double_a;
            sum += 10 + double_a % 10;

        int b = num % ((int) pow(10, 2*i)) / ((int) pow(10, 2*i - 1));
        sum += b;
    return sum;

The code compiles, but I get weird problems. I tried the number 378282246310005 and it just re-prompted me for a number. Not sure why. Then i tried 1234, and got this:

scratchv4.c:37:45: runtime error: division by zero
==1421==ERROR: UndefinedBehaviorSanitizer: FPE on unknown address 0x000000422659 (pc 0x000000422659 bp 0x7ffe99745e60 sp 0x7ffe99745d90 T1421)
    #0 0x422658  (/root/sandbox/scratchv4+0x422658)
    #1 0x422373  (/root/sandbox/scratchv4+0x422373)
    #2 0x7fc1cebbab96  (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
    #3 0x402b29  (/root/sandbox/scratchv4+0x402b29)

UndefinedBehaviorSanitizer can not provide additional info.

I have no clue what the problem is. Mathematically, there should be no division by zero anywhere in this code as 10^(any number) is nonzero. Can somebody tell me what is wrong and how to correct this so it performs the checksum for Luhn's algorithm? Thank you.


int can't handle that large numbers. I guess that's where things go wrong.

I would prefer using /=100 in a loop rather than pow, and get the last and second-to-last digit each time.

  • The rationale for using pow was that I need to divide by larger and larger numbers each time to get required digits. Do you mean that I should update the number itself each time with /= 100? Mar 16 '20 at 14:21
  • I just tried what I thought you were suggesting and it worked out. Thanks! Mar 16 '20 at 15:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .