c - Validating card credit numbers -
i've been trying create programme can check if credit card number valid or not based on hans peter luhn's algorithm. however, can work inputs.
// loop through every digit in card number ( int = 0; < intlen (num); ++i ) { nextdigit = getdigit (num, i); // if every other number... if ( % 2 ) { nextdigit *= 2; // ...times 2 , add together individual digits total ( int j = 0; j < intlen (nextdigit); ++j ) { total += getdigit (nextdigit, j); } } else { total += nextdigit; } } when utilize amex card number 378282246310005 works fine , tells user it's valid. however, 1 time seek visa card number 4012888888881881 says it's invalid. tried sanity check , manually see if programme wrong deduced same result. these card number taken paypal test credit card numbers page know valid.
so doing wrong?
to clarify details program, if total modulo 10 == 0 card number valid.
functions called:
// function homecoming length (number of digits) of int int intlen (long long n) { int len = 1; // while there more 1 digit... while ( abs (n) > 9 ) { // ...discard leading digits , add together 1 len n /= 10; ++len; } homecoming len; } // function homecoming digit in integer @ specified index short getdigit (long long num, int index) { // calculating position of digit in integer int pos = intlen (num) - index; // discard numbers after selected digit while ( pos > 1 ) { num /= 10; --pos; } // homecoming right-most digit i.e. selected digit homecoming num % 10; }
you'll want alter i % 2 i % 2 == intlen (num) % 2 or similar; should double every sec digit, starting right; i.e. excluding final check digit:
from rightmost digit, check digit, moving left, double value of every sec digit; …
the reason amex number tried validated anyway because it's odd number of digits; same digits doubled regardless of whether skip front end or back.
c luhn
No comments:
Post a Comment