Credit Card Checker Problem

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.7 kB
3
Indexable
#include <iostream> // For cin and cout
#include <cmath> // For power function
using namespace std; // Using standard library

// Prototypes
int len_int(long long n);
int get_index(long long n, int i);

int main()
{
	long long number;

	// Digit Check
	// At the moment, the program assumes the user is inputting numbers only (no characters, symbols, etc.)
	// This program can be improved to handle the case where the user inputs something else, or nothing.
	do
	{
		cout << "Number: ";
		cin >> number;
	} while ((number <= 999999999999 || number >= 10000000000000000) || (number > 9999999999999 && number < 100000000000000));
	// ^^ Also could use the len_int() function I introduced later in the code.

	// Luhn's Algorithm
	// First sum (Multiplying by 2 and adding)
	int first_sum = 0;
	for (int i = (len_int(number) - 2); i > -1; i = i - 2)
	{
		int n = get_index(number, i);
		n = n * 2;
		if (len_int(n) == 2)
		{
			n = get_index(n, 0) + get_index(n, 1);
		}
		first_sum += n;
	}

	// Second sum (Just adding the rest of the digits)
	int second_sum = 0;
	for (int i = (len_int(number) - 1); i > -1; i = i - 2)
	{
		second_sum += get_index(number, i);
	}

	// Final sum and checking for cases
	int final_sum = first_sum + second_sum;
	if ((final_sum % 10) == 0)
	{
		// Since lines are long, it is more readable to put them in nesting 'if' conditions rather than at one line.
		// However, for the sake of avoiding confusion, I put them in the same line.
		// VISA condition
		if ((len_int(number) == 13 || len_int(number) == 16) && (get_index(number, 0) == 4))
		{
			cout << "VISA\n";
		}
		// American Express Condition
		else if ((len_int(number) == 15) && (get_index(number, 0) == 3 && (get_index(number, 1) == 4 || get_index(number, 1) == 7)))
		{
			cout << "AMEX\n";
		}
		// Mastercard Condition
		else if ((len_int(number) == 16) && (get_index(number, 0) == 5 && (get_index(number, 1) > 0 && get_index(number, 1) < 6)))
		{
			cout << "Mastercard\n";
		}
		else
		{
			cout << "INVALID\n";
		}
		return 0;
	}
	else {
		cout << "INVALID\n";
		return 0;
	}


}

// Takes in a 8-byte int (long long) and an index for the int, and returns a single-digit number
// back as if the integer is an array of single-digit numbers. The integer is zero-indexed.
int get_index(long long n, int i)
{
	int power_of_ten = len_int(n) - i - 1;
	n = n / pow(10, power_of_ten);
	n = n % 10;
	int result = n;
	return result;
}

// Returns the length of an int (or long long)
int len_int(long long n)
{
	int length = 0;
	while (n > 0)
	{
		n = n / 10;
		length = length + 1;
	}
	return length;
}