0

I am now working on the first part of credit, and is currently checking the validity of the number given. I separated it into two parts, one where I summed the doubled digits, and one where I summed the non-doubled digits. Then I summed these two values.

However, when I tested with the credit card number used as the example on the website (378282246310005), I can't seem to get 60. I've tried to debug this, and the first sum is 27, while the second is 33.

I don't know why but the sum of this two number is apparently 74, can anyone please explain?

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

//Variables
long input;
long mod1 = 100;
long mod2 = 10;
long sum1;
long csum1;
long tsum1 = 0;
long val1;
long val2;
long sum2;
long csum2;
long tsum2;

int main (void)
{
//Prompts user to insert CC number
input = get_long_long ("Credit card number: ");

//Access the digits (needs implementation on how to stop the loop correctly)
for (float limit = input / mod1; limit >= 0.1;)
{
    csum1 = (input % mod1) / (mod1 / 10) * 2;

    //Sum if the doubled number is only a single digit
    if (csum1 / 10 < 1)
    {
        sum1 = csum1 + tsum1;
    }

    //Sum if the doubled number is two digits
    if (csum1 / 10 >= 1)
    {
        val1 = csum1 / 10;
        val2 = csum1 % 10;
        sum1 = val1 + val2 + tsum1;
    }

    //Update the critical values
    tsum1 = sum1;
    limit = limit / 100;
    mod1 = mod1 * 100;
}



for (float limit = input / mod2; limit >= 0.1;)
{
    csum2 = (input % mod2) / (mod2 / 10);

    sum2 = csum2 + tsum2;

    //Update the critical values
    tsum2 = sum2;
    limit = limit / 100;
    mod2 = mod2 * 100;
}
long sum = sum1 + sum2;
printf ("%lo", sum);
}
2

Your algorithm is calculating the correct result. 74 is the octal representation of decimal number 60 (octal uses 8 as base while decimal uses 10). Use ld, not lo to print a long.

7 * 8^1 + 4 * 8^0 = 56 + 4 = 60

| improve this answer | |

You must log in to answer this question.

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