Skip to content

Instantly share code, notes, and snippets.

@wofockham
Created February 23, 2015 22:06
Show Gist options
  • Save wofockham/53232592840ff0b712cd to your computer and use it in GitHub Desktop.
Save wofockham/53232592840ff0b712cd to your computer and use it in GitHub Desktop.

Luhn Formula

Write a program that can take a number and determine whether or not it is valid per the Luhn formula.

The Luhn formula is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers and Canadian Social Insurance Numbers.

The formula verifies a number against its included check digit, which is usually appended to a partial number to generate the full number. This number must pass the following test:

Counting from rightmost digit (which is the check digit) and moving left, double the value of every second digit.

For any digits that thus become 10 or more, subtract 9 from the result.

E.g., 1111 becomes 2121, while 8763 becomes 7733 (from 2×6=12 → 12-9=3 and 2×8=16 → 16-9=7).

Add all these digits together. For example, if 1111 becomes 2121, then 2+1+2+1 is 6; and 8763 becomes 7733, so 7+7+3+3 is 20.

If the total ends in 0 (put another way, if the total modulus 10 is congruent to 0), then the number is valid according to the Luhn formula; else it is not valid. So, 1111 is not valid (as shown above, it comes out to 6), while 8763 is valid (as shown above, it comes out to 20).

Write a program that, given a number

a) can check if it is valid per the Luhn formula. b) can add a check digit to make the number valid per the Luhn formula.

Luhn.new(2323_2005_7766_3554).valid?
# => true
require 'minitest/autorun'
require 'minitest/pride'
require_relative 'luhn'
class LuhnTest < MiniTest::Unit::TestCase
def test_check_digit
luhn = Luhn.new(34567)
assert_equal 7, luhn.check_digit
end
def test_check_digit_again
skip
luhn = Luhn.new(91370)
assert_equal 0, luhn.check_digit
end
def test_addends
skip
luhn = Luhn.new(12121)
assert_equal [1, 4, 1, 4, 1], luhn.addends
end
def test_too_large_addend
skip
luhn = Luhn.new(8631)
assert_equal [7, 6, 6, 1], luhn.addends
end
def test_checksum
skip
luhn = Luhn.new(4913)
assert_equal 22, luhn.checksum
end
def test_checksum_again
skip
luhn = Luhn.new(201773)
assert_equal 21, luhn.checksum
end
def test_invalid_number
skip
luhn = Luhn.new(738)
assert !luhn.valid?
end
def test_valid_number
skip
luhn = Luhn.new(8739567)
assert luhn.valid?
end
def test_create_valid_number
skip
number = Luhn.create(123)
assert_equal 1230, number
end
def test_create_other_valid_number
skip
number = Luhn.create(873956)
assert_equal 8739567, number
end
def test_create_yet_another_valid_number
skip
number = Luhn.create(837263756)
assert_equal 8372637564, number
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment