When you pay for things online, sometimes when you enter your credit card number, the online merchant is able to instantly identify whether the card number you're entering is a valid American Express, Visa, or Mastercard number. After completing this problem, you'll be able to do the same.
Here are the rules for each credit card type:
For American Express:
- The card number begins with either 34 or 37.
- The card number is 15 digits.
For Visa:
- The card number begins with 4.
- The card number is 13, 16, or 19 digits.
For Mastercard:
- The first two digits are 51–55, or the first four digits are 2221–2720.
- The card number is 16 digits.
On top of these requirements, the credit card number must pass what's called a Luhn check, which is a practical implementation of Luhn's algorithm.
Write MATLAB code that determines if a credit card number conforms to American Express's rules, Visa's, Mastercard's, or none of the above. You will simply return one of the following responses:
'American Express'
'Visa'
'Mastercard'
'Invalid'
Your output must match one of these exactly, including spelling and capitalization.
The input ccNum is a character array containing only digits.
EXAMPLE:
Here's an example of a Luhn check on a valid American Express number:
ccNum = '375981264037217'
- The last digit is referred to as the check digit and the rest of the digits are referred to as the payload. Identify the digits that fall into these categories. In this case, 7 is the check digit and 37598126403721 is the payload.
- Counting from the right, with the rightmost payload digit as position 1, double the digits in positions 1, 3, 5, and so on:
[3 14 5 18 8 2 2 12 4 0 3 14 2 2];
3. If any number is greater than 9, subtract 9 from it.
[3 5 5 9 8 2 2 3 4 0 3 5 2 2];
4. Sum the digits in the result, which in this case is 53.
5. Check if this sum + the check digit, 7, is a multiple of 10. Since 53 + 7 = 60, which is a multiple of 10, this combined with the fact that prefix of this credit card number is 37 and the fact that the original credit card number is 15 digits in length confirms that this is an American Express card number. In which case, you will return:
ccType = 'American Express'
If you appreciated this problem, please consider rating its difficulty and liking!
Solution Stats
Solution Comments
Show comments
Loading...
Problem Recent Solvers4
Suggested Problems
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!