简体   繁体   English

生成通过Luhn算法的16位数字

[英]Generate 16 digit number that passes Luhn algorithm

I'm trying to generate 16 digit number that passes the Luhn algorithm verification.我正在尝试生成通过 Luhn 算法验证的 16 位数字。 For example, If I'm generating 16 digit number for an American Express card which would begin with 37例如,如果我为一张以 37 开头的美国运通卡生成 16 位数字

Something like this像这样的东西

3789 1477 0763 171 (this would pass the Luhn algorithm) 3789 1477 0763 171(这将通过 Luhn 算法)

I able to generate the 16 digit number but it wouldn't pass the Luhn algorithm.我能够生成 16 位数字,但它不会通过 Luhn 算法。

<?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)

?>

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;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM