Skip to content

Instantly share code, notes, and snippets.

@wx5162839
Created May 27, 2020 02:42
Show Gist options
  • Select an option

  • Save wx5162839/bbed2deb2e3b3be981959961c49679ef to your computer and use it in GitHub Desktop.

Select an option

Save wx5162839/bbed2deb2e3b3be981959961c49679ef to your computer and use it in GitHub Desktop.
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main(void)
{
long long n = 0;
do
{
n = get_long_long("credit card number: ");
}
while(n < 0);
int digit = 0;
{
// if int k = n; it will be Floating point exception, cause An integer in C cannot be bigger than 2147483647 (10 digits).
long long k = n;
while (k > 0)
{
k = k / 10;
digit++;
}
}
int sum_odd = 0;
for (int i = 0; i <= digit; i = i + 2)
{
// pow(a, b)返回的是一个浮点数,不能进行取模运算;所以应加上(int)
sum_odd = sum_odd + (n / (long long)pow(10, i )) % 10;
}
int sum_even = 0;
for (int j = 1; j <= digit; j = j + 2)
{
int a = 2 * ((n / (long long)pow(10, j)) % 10);
sum_even = sum_even + a % 10 + a / 10;
}
int sum = (sum_odd + sum_even) % 10;
int start = n / (long long)pow(10, digit - 2);
if (sum == 0)
{
if (digit == 15 && (start == 34 || start == 37))
{
printf("AMEX\n");
}
else if((start == 51 || start == 52 || start == 53 || start == 54 || start == 55) && digit == 16)
{
printf("MASTERCARD\n");
}
else if ((digit == 13 || digit == 16) && (start / 10 == 4))
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
else
{
printf("INVALID\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment