Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
I was just looking at the about.com Perl site, and it has this article about finding if a number is a valid Luhn number, which, apparently, tells you it's a valid credit card number.

  1. double the value of every other digit, counting backward from the second-last
  2. add all the digits of the resulting numbers together (not the numbers, but the digits of the numbers, so if you've got 16, you add it as one plus six)
  3. add the leftover numbers together
  4. add them to the sum of the other lot of numbers

If what you've got is divisible by ten, it's a valid credit card number.

Their solution is at http://perl.about.com/library/weekly/aa080600h.htm, and of course it's quite long, because it's a teaching exercise.

I got thinking about it and how to do it more compactly, in the spirit of "Regular Expressions -- is there anything they can't do?" and tried to make it as short as I could.

Here's an attempt, but I'd love to see you make it shorter:

$n = '4564123800603607'; # this is not my credit card number ($o = reverse($n)) =~ s/.(.)/($1*2)/ge; # every other number in it, times 2 # (reversed because then it will work # for numbers of different lengths, as # some cards are 13, not 16). ($e = reverse($n)) =~ s/(.)./$1/ge; # the other numbers, not times 2 $o =~ s/(.)/$x+=$1/ge; $e =~ s/(.)/$y+=$1/ge; # add the digits printf("%sValid.",(($x+$y)%10 == 0?'':'Not ')); # print the result

In reply to Luhn Number Golf by Cody Pendant

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2024-03-29 13:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found