pastebin - collaborative debugging tool
kpaste.net RSS


Luhn algorithm
Posted by Admin on Fri 11th Feb 2011 02:06
raw | new post
view followups (newest first): Luhn algorithm by Anonymous

  1. <?php
  2. function roundup ($number, $increments) {
  3.         $increments = 1 / $increments;
  4.         return (ceil($number * $increments) / $increments);
  5. }
  6.  
  7. $num = "49927398717";
  8.  
  9. $double = false;
  10. $ret = "";
  11.  
  12. for ($i = strlen($num) - 1; $i >= 0; $i--) {
  13.         $ret .= ($double ? $num[$i] * 2 : $num[$i]);
  14.         $double = !$double;
  15. }
  16. $ret = strrev($ret);
  17. $sum = 0;
  18.  
  19. for ($i = 0; $i < strlen($ret); $i++) {
  20.         $sum += $ret[$i];
  21. }
  22. echo "\$ret = $ret\n";
  23. echo "\$sum = $sum\n";
  24.  
  25. if ($sum % 10) {
  26.         $check_digit = roundup($sum, 10) - $sum;
  27.         echo "Invalid - (Valid with check digit $check_digit)\n";
  28. } else {
  29.         echo "Valid\n";
  30. }
  31. ?>

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with {%HIGHLIGHT}




All content is user-submitted.
The administrators of this site (kpaste.net) are not responsible for their content.
Abuse reports should be emailed to us at