Skip to content

Instantly share code, notes, and snippets.

Created June 2, 2015 18:44
Show Gist options
  • Save anonymous/ed4a72fd1b7ebabb1c93 to your computer and use it in GitHub Desktop.
Save anonymous/ed4a72fd1b7ebabb1c93 to your computer and use it in GitHub Desktop.
/*
* CreditCard.cpp
*
* Created on: May 26, 2015
* Author: Zak Taylor
*/
//4388576018410707 - VALID
//4388576018402626 - INVALID
#include <iostream>
#include <cmath>
using namespace std;
static bool isValid(long long number);
static int sumOfDoubleEvenPlace(long long number);
static int sumOfOddPlace(long long number);
static int getDigit(long long number);
static bool prefixMatched(long long number, int d);
static long long getPrefix(long long number, int k);
static int getSize(long d);
static long long number;
int main(){
cout << "Enter a credit card number as a long integer: " << endl;
cin >> number;
cout << number<< " is ";
if(isValid(number))
cout <<"valid" << endl;
else
cout <<"invalid" << endl;
return 0;
}
static bool isValid(long long number){
int numSize = getSize(number);
if((numSize > 16) || (numSize < 13)) return false;
int sum = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
if(sum % 10 != 0) return false;
if(prefixMatched(number, 4)) return true;
if(prefixMatched(number, 5)) return true;
if(prefixMatched(number, 37)) return true;
if(prefixMatched(number, 6)) return true;
else return false;
}
static int sumOfDoubleEvenPlace(long long number){
int sum = 0;
while(number > 0)
{
int digit = ((number % 100) / 10);
number /= 100;
sum += getDigit(2 * digit);
}
return sum;
}
static int sumOfOddPlace(long long number)
{
int sum = 0;
while(number > 0)
{
int digit = (number % 10);
number /= 100;
sum += getDigit(digit);
}
return sum;
}
static int getDigit(long long number)
{
return (number / 10) + (number % 10); // Still works the same if it's a single digit number.
}
static int getSize(long d)
{
int digitCount = 0;
while(d > 0){
d /= 10; // Chop off one digit.
digitCount++;
}
return digitCount;
}
static bool prefixMatched(long long number, int d)
{
return getPrefix(number, getSize(d)) == d;
}
static long long getPrefix(long long number, int k)
{
int numberSize = getSize(number);
int decimalMovements = numberSize - k;
while(decimalMovements-- > 0){
number /= 10;
}
return number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment