Separating the products' digits and adding them up is giving me trouble. For example for this credit card number: (1234567), 12, 8, and 4 would be the result of multiplying every other digit by 2. How would you add the digits so that it's in a form of: 1 + 2 + 8 + 4? I'm thinking again in putting the resulting numbers into an array. Although, I don't know how that would access '1' and '2' in the number '12'.
4 Answers
Here's some pseudo code:
int accumulator = 0
for each digit in the card number
{
if the digit is at an odd position (position is not divisible by 2)
{
int factor = multiply the digit x 2
for each digit in factor
{
add factor digit to accumulator
}
}
}
Given your example digits 1234567
, this will do the following:
- initialise accumulator = 0
- loop through all the digits (total 7)
- operate on the digits at position #1: 6
- multiply 6 x 2 = 12
- loop through the digits in 12 (total of 2)
- add 1 to accumulator (accumulator contains 0 + 1 = 1)
- add 2 to accumulator (accumulator contains 1 + 2 = 3)
- operate on the digits at position #3: 4
- multiply 4 x 2 = 8
- loop through the digits in 8 (total of 1)
- add 8 to accumulator (accumulator contains 3 + 8 = 11)
- operate on the digits at position #5: 2
- multiply 2 x 2 = 4
- loop through the digits in 4 (total of 1)
- add 4 to accumulator (accumulator contains 11 + 4 = 15)
The number of digits in 1234567, 12, 8, 4, and so on, can be obtained using the logarithm described in the answer by Cygni_61.
You can use
int number_of_digits = (int)log10(1234567) + 1;
to get the position of the number of digits of your number.
Or use the command
int first_digit = (int)(1234567 / 1000000);
int remaining_digits = 1234567 - 1000000;
and the equivalent, faster one:
int remaining digits = (1234567 % 10000000);
int first_digit = 1234567 - remaining_digits;
:-)
You'll want to iteratively perform a modulo (%
) operation on the credit card number by an integer that will return the 2 right most digits of the credit card number, then divide (/
) the resultant digits by a number that will isolate the left-most digit from the right-most digit and store this in a separate variable, then perform some Luhn magic and then divide the credit card number by an integer that will remove the 2 digits that you just processed.
This will allow you to walk from right to left through the credit card number and isolate the proper integers values that you'll need to perform your iterative Luhn calculations.
You should take individual digits from the end to the start; in your example: 7, 6, 5, 4, 3, 2, 1 Maybe mod (%) can be useful ;)