My code is supposed to validate credit cards using Luhns algorithm, defined as follows:
Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.
Sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5) together with the undoubled digits from the original number.
If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
There is an issue somewhere in the loop where I assign values to num[], which should be the individual digits of cc. Could also be issues elsewhere, but I'm pretty sure it works. cc%x and cc%y are returning incorrect values. I also tried using pow() instead of my own exp, because I thought that may have been the problem as it returns a different data type, but it was not working either.
My code is as follows:
#include <iostream>
#include <cmath>
using namespace std;
int exp(int , int);
int main()
{
int cc;
int x, y;
int sum = 0;
cout<<"Enter your credit card number\n";
cin>>cc;
int num[16];
int digO[8];
int digE[8];
//Get digits of CC
for (int i = 0; i < 16; i++)
{
x = exp(10, i+1);
y = exp(10, i);
cout<<endl<<"X, Y: "<<x<<", "<<y;
num[i]= (cc%x - cc%y)/exp(10, i);
int check = cc%x;
int check2 = cc%y;
cout<<"\nCheck1: "<<check<<endl<<"Check2: "<<check2;
}
//Get odd digits of CC
for (int i = 0; i < 8; i++)
{
x = 2*(i+1)-1;
digO[i] = num[x];
}
//Luhn algorithm: mult digit by 2
for (int i = 0; i < 8; i++)
{
digO[i] = 2*digO[i];
}
//Add each digit of product
for (int i = 0; i < 8; i++)
{
sum = sum + (digO[i]%100 - digO[i]%10)/10 + digO[i]%10;
}
//Get even digits
for (int i = 0; i < 8; i++)
{
x = (2*i);
digE[i] = num[x];
}
//Add sum + even digits
for (int i = 0; i < 8; i++)
{
sum = sum + digE[i];
}
//Check if last digit of sum is 0
bool checkSum = (sum%10 ==0);
if (checkSum)
{
cout << "Valid credit card number." << endl;
}
else
{
cout << "Invalid credit card number." << endl;
}
return 0;
}
//Exponent function
int exp(int base, int exponent)
{
int result = 1;
for (int i = 0; i < exponent; i++)
{
result *= base;
}
return result;
}
Here is a much simpler way of handling this. Because the repeated mod 10 operations here strip off the digits starting from the right, we can do the summation on the fly. We don't need to hold all of the digits first.