'Generate 16 digit number that passes Luhn algorithm
I'm trying to generate 16 digit number that passes the Luhn algorithm verification. For example, If I'm generating 16 digit number for an American Express card which would begin with 37
Something like this
3789 1477 0763 171 (this would pass the Luhn algorithm)
I able to generate the 16 digit number but it wouldn't pass the Luhn algorithm.
<?php
function generatenumber($limit, $prefix){
$code = '';
for($i = 0; $i < $limit; $i++) {
$code .= mt_rand(0, 9);
}
return $prefix.$code;
}
generatenumber(14,37);
3711414458103430 // This wouldn't pass the Luhn algorithm verification)
?>
Solution 1:[1]
Here is an attempt you can try:
<?php
function generate_numbers($limit, $prefix) {
$digits = substr(str_shuffle(str_repeat('0123456789', $limit)), 0, $limit - 1);
$sum = 0;
foreach (str_split(strrev($digits)) as $i => $digit) {
$sum += ($i % 2 == 0) ? array_sum(str_split($digit * 2)) : $digit;
}
return $prefix . $digits . (10 - ($sum % 10)) % 10;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tim |
