Luhn algorithm for credit card validation
I came across an interesting article on algorithms in, of all places, The Economist. It briefly describes the Luhn algorithm for credit card validation. So I hacked together the following piece of Ruby code which does just that.
print "Enter card number: "
cc_number = gets.chomp.tr(' -','')
checksum = 0
double = false
cc_number.reverse.each_byte do |digit|
dig = digit.chr.to_i
checksum += (double ? (dig*2)%9 : dig)
double = !double
end
if checksum%10 == 0
puts "valid CC number"
else
puts "Invalid"
end
For more interesting articles on this, see the following:
http://www.darkcoding.net/index.php/credit-card-numbers/
http://www.merriampark.com/anatomycc.htm