卢恩算法的实现 [英] Implementation of Luhn algorithm

查看:561
本文介绍了卢恩算法的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现信用卡号码的简单的验证。我读到关于维基百科的卢恩算法

  
      
  1. 从校验位,这是最右边的计数,和移动   离开,每一个第二位的双重价值。
  2.   
  3. 求和的产品的位数(例如,10:1 + 0 = 1,14:1 + 4 = 5)   从原来的号码的undoubled位数在一起。
  4.   
  5. 如果总模10等于0(如在零总端部)   然后根据卢恩式的数量是有效的;否则它是   无效。
  6.   

在维基百科,卢恩算法的描述是很容易理解的。不过,我也看到罗塞塔code 的卢恩算法和的别处

这些实现工作得很好,但我很困惑,为什么他们可以使用数组来完成工作。他们使用数组似乎与卢恩算法没有关系,我看不出他们是如何实现在维基百科中描述的步骤。

他们为什么使用数组?什么是他们的意义,以及如何使用它们来实现的算法所描述的维基百科?

解决方案

阵列 [0,1,2,3,4,-4,-3,-2,-1,0] 用作查找阵列查找在0-9和一个数之间的差的2倍,其值的位数之和。例如,对于数字8,介于8和差(2 * 8)= 16 - > 1 + 6 = 7是7-8 = -1。

下面是图形presentation,其中{n}的代表n个数字之和

  [{0 * 2} -0,{1 * 2} -1,{2 * 2} -2 {3 * 2} -3,{4 * 2} -4,{5 * 2} -5- {6 * 2} -6,{7 * 2} -7- ....]
   | | | | | | | |
[0,1,2,3,4,-4,-3,-2 ....]
 

该算法你刚刚上市总和所有的数字,并为每个连点位,查找的差异使用数组,并将其应用到总和。

I am trying to implement simple validation of credit card numbers. I read about the Luhn algorithm on Wikipedia:

  1. Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.
  2. Sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5) together with the undoubled digits from the original number.
  3. If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.

On Wikipedia, the description of the Luhn algorithm is very easily understood. However, I have also seen other implementations of the Luhn algorithm on Rosetta Code and elsewhere.

Those implementations work very well, but I am confused about why they can use an array to do the work. The array they use seems to have no relation with Luhn algorithm, and I can't see how they achieve the steps described on Wikipedia.

Why are they using arrays? What is the significance of them, and how are they used to implement the algorithm as described by Wikipedia?

解决方案

the array [0,1,2,3,4,-4,-3,-2,-1,0] is used as a look up array for finding the difference between a number in 0-9 and the digit sum of 2 times its value. For example, for number 8, the difference between 8 and (2*8) = 16 -> 1+6 = 7 is 7-8 = -1.

Here is graphical presentation, where {n} stand for sum of digit of n

[{0*2}-0, {1*2}-1, {2*2}-2, {3*2}-3, {4*2}-4, {5*2}-5, {6*2}-6, {7*2}-7....]
   |       |        |         |        |        |       |         |  
[  0  ,    1    ,   2    ,    3  ,     4   ,   -4  ,   -3   ,    -2  ....] 

The algorithm you listed just sum over all the digit and for each even spot digit, look up the the difference using the array, and apply it to the total sum.

这篇关于卢恩算法的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆