I wrote this credit card validation program where the user can enter as many didigts as long as it can be stored in type long, with the following algorithm:
- Take every other digit in the number starting with the rightmost and add them together, num1
- Then take the rest of the digits that were not added and double them, then split the digit and add them up. ex. if we had as one of the digits 9 we would double it to 18, then split it to 1 and 8 and add them 1+8=9 etc., num2
- Then we take num1 and num2 and add them together, and if the resulting number ends in a zero, say 50, then the card is valid, if it ends in anything other then a zero its is invalid
My program works with a number with 1-9 digits but as soon as I try a 10 digit number the algorithm is off, I'm not sure where I'm wrong, can somebody help? Also in the if(ccnum <= 4294967295)
, if I enter a number greater then 4294967295 my program does not execute the else if, what is wrong?
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
unsigned long ccnum;
int num1, num2, even, odd, divisorodd, divisoreven, first, split, check;
double digits;
cout << "Enter your credit card number: ";
cin >> ccnum;
digits = ceil(log10((double)ccnum + 1));
if (ccnum <= 4294967295){
num1 = 0;
num2 = 0;
divisorodd = 100;
divisoreven = 10;
first = ccnum % 10;
for (int i = 0; i <= digits; i++){
odd = ((ccnum / divisorodd) % 10);
num1 = num1 + odd;
divisorodd = divisorodd * 100;
}
num1 = num1 + first;
for (int i = 0; i <= digits; i++){
even = ((ccnum / divisoreven) % 10) * 2;
split = (even % 10) + ((even / 10) % 10);
num2 = num2 + split;
divisoreven = divisoreven * 100;
}
}
else if (ccnum > 4294967295){
cout << "\nIncorrect credit card number.\n";
}
cout << "\nNum1 is: " << num1 << "\n";
cout << "\nNum2 is: " << num2 << "\n";
check = num1 + num2;
cout << "\nThe check number is: " << check << "\n";
if (check % 10 == 0){
cout << "\nThe credit card number is valid! Thank you.\n" << endl;
}
else if (check % 10 != 0){
cout << "\nThe credit card number is invalid! Sorry.\n" << endl;
}
}