Reputation: 375
#include <stdio.h>
int main(int argc, string argv[])
{
Get input from the user;
Store it in a long long int;
// iterate through the number
for each odd number in the input multiply by 2
if the number is bigger than 9 then
do module of it and add it to the first number;
store it into metasum;
for each even number in the input
add it to the others;
store the result into metasum2;
// is it a valid card?
if (metasum + metasum2)%10 == 0
{
card is valid;
// check which kind of cc is
if the input begins with a 3 then it's an AMEX;
else if the input begins with 4 it is a VISA;
else if the input begins with 5 it is a MASTERCARD;
}
else
{
card is not valid;
}
}
It is actually a sort of pseudocode. I'm attending CS50x and I would like to know if my pseudocode implementation is good enough.
I have another problem though, when I try to implement the code in C I do not know how to iterate through a long long int, so I can't implement Luhn's algorithm.
How can I do this without using a string and then converting each char into an int?
Thanks for your response
Upvotes: 1
Views: 4440
Reputation: 72241
Use modulo and integral division.
The first digit from the right (youngest digit) of a number is number % 10
.
The second is (number/10) % 10
. The third would be (number/100) % 10
. Easy pattern - you can write it as a function. (Just avoid mixing in floats here.)
If you want to iterate over a number's digits, you might want to check how many digits a number has (see: base-10 logarithm) - the easiest way is to do repeatedly divide that number by 10 until it's 0.
Anyway, remember that credit card numbers are quite long! An unsigned 64-bit number can contain like 19 significant digits (max is 2**64-1), so it's enough for credit cards, but that won't work for bank accounts for instance. An approach using strings (some form of) will be more general.
Upvotes: 1
Reputation: 33177
To "iterate" a non-array, you need to separately keep track of your position (to count through all possible digits), using division and modulus to advance and extract the digit, for example:
long long number = 9999999999;
for (int digitPos = 0; digitPos < 16; digitPos++) {
int thisDigit = number % 10;
number = number / 10;
}
As for applicability to your course, I can't vouch for that :)
Upvotes: 2