1

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)

?>
  • 1
    Well, if any randomly generated number worked, the Luhn check would be pointless, wouldn't it? So the last digit cannot be picked at random, it must be calculated so that the whole number passes the test. (Of course, you could also generate numbers until one passes the test. Or generate the number and then try all possible last digits so that the Luhn test is satisfied.) – M Oehm Jun 22 '21 at 06:12
  • Yeah! That's why I said it wouldn't pass the Luhn verification. I was just showing what I have done till now. – shakti goyal Jun 22 '21 at 06:18
  • But it's obvious that the generated number will not pass the test most of the time. What you have shown doesn't have anything to do with your problem, it's just "preparation". – M Oehm Jun 22 '21 at 06:22
  • So you are saying out that after generating the random number, I would have to check all the single digits (1,2,3....) against the last digit until it passes the Luhn verification, Am I getting it right? – shakti goyal Jun 22 '21 at 06:26
  • a 16 digit number you say? The 1st example cited that is supposed to work is 15 digits – Professor Abronsius Jun 22 '21 at 06:28
  • You probably already have a function that does the Luhn test, right? Create a 15-digit number X, then test X0, X1, X2, X3 and so on until the Luhn test passes. I think that should work, because the Luhn test is more or less a checksum. – M Oehm Jun 22 '21 at 06:31
  • Oops! I just realized the American express card has 15 digits compared to others (Visa, Mastercard) @ProfessorAbronsius – shakti goyal Jun 22 '21 at 06:33
  • Got it! Thank you @MOehm – shakti goyal Jun 22 '21 at 06:34
  • Read about Luhn's coding, and you will easily find how to make a Luhn's number. – Jean-Baptiste Yunès Jun 22 '21 at 07:25

1 Answers1

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;
  }
tim
  • 2,530
  • 3
  • 26
  • 45