There are several problems in your code:
srand(time(0));
is used to seed the pseudo-random number generator. Use it just once in the main()
function otherwise all numbers generated during the same second will be identical.
- To generate a 16 digit random number, the only digit that cannot be zero is the first one, all others can be, unlike what your code does.
10^i
does not compute the i-th power of 10
in C, it evaluates 10
xor i
.
- you do not compute enough digits.
randd
is undefined.
It is easier to compute the digits from the most significant to the least significant. Here is a modified version:
#include <stdlib.h>
void generate_card_number() {
// start with a digit between 1 and 9
long long cardnumber = 1 + rand() % 9;
// add the remaining 15 digits
for (int i = 1; i < 16; i++)
cardnumber = cardnumber * 10 + rand() % 10;
printf("The Card Number: %lld\n", cardnumber);
}
Since RAND_MAX
is guaranteed to be larger than 10000
, you can compute 4 digits at a time:
#include <stdlib.h>
void generate_card_number() {
// start with a number between 1000 and 9999
long long cardnumber = 1000 + rand() % 9000;
cardnumber = cardnumber * 10000 + rand() % 10000; // add 4 digits
cardnumber = cardnumber * 10000 + rand() % 10000; // add 4 digits
cardnumber = cardnumber * 10000 + rand() % 10000; // add the last 4 digits
printf("The Card Number: %lld\n", cardnumber);
}
On most platforms, RAND_MAX
is much larger, so here is alternative to take advantage of this and use fewer calls to generate the number:
#include <stdlib.h>
void generate_card_number() {
#if RAND_MAX >= 100000000
// start with a number between 10000000 and 99999999
long long cardnumber = 10000000 + rand() % 90000000;
cardnumber = cardnumber * 100000000 + rand() % 100000000; // add 8 digits
#else
// start with a number between 1000 and 9999
long long cardnumber = 1000 + rand() % 9000;
cardnumber = cardnumber * 10000 + rand() % 10000; // add 4 digits
cardnumber = cardnumber * 10000 + rand() % 10000; // add 4 digits
cardnumber = cardnumber * 10000 + rand() % 10000; // add the last 4 digits
#endif
printf("The Card Number: %lld\n", cardnumber);
}
Note however that card numbers have extra contraints, such as restricted value ranges and must have a valid Luhn checksum.