卢恩公式(算法)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了卢恩公式(算法)相关的知识,希望对你有一定的参考价值。

Test harness for an implementation of the Luhn algorithm that checks the validity of a credit card number.
  1. /**
  2.  * Test harness for an implementation of the Luhn algorithm that checks the
  3.  * validity of a credit card number.
  4.  */
  5. public class Luhn {
  6. /**
  7. * Main entry point for the test harness.
  8. *
  9. * @param args the command line arguments.
  10. */
  11. public static void main(String[] args) {
  12. if (args.length < 1) {
  13. System.err.println("Usage: Luhn number ...");
  14. System.exit(1);
  15. }
  16.  
  17. for (int i = 0; i < args.length; i++) {
  18. System.out.print("Number '" + args[i] + "'" );
  19. if (!args[i].matches("^\d{13,19}$")) {
  20. System.out.println(" is not a valid credit card number (must be 13-19 digits)");
  21. } else if (isValidNumber(args[i])) {
  22. System.out.println(" is a valid credit card number");
  23. } else {
  24. System.out.println(" is not a valid credit card number");
  25. }
  26. }
  27. }
  28.  
  29. /**
  30. * Checks whether a string of digits is a valid credit card number according
  31. * to the Luhn algorithm.
  32. *
  33. * 1. Starting with the second to last digit and moving left, double the
  34. * value of all the alternating digits. For any digits that thus become
  35. * 10 or more, add their digits together. For example, 1111 becomes 2121,
  36. * while 8763 becomes 7733 (from (1+6)7(1+2)3).
  37. *
  38. * 2. Add all these digits together. For example, 1111 becomes 2121, then
  39. * 2+1+2+1 is 6; while 8763 becomes 7733, then 7+7+3+3 is 20.
  40. *
  41. * 3. If the total ends in 0 (put another way, if the total modulus 10 is
  42. * 0), then the number is valid according to the Luhn formula, else it is
  43. * not valid. So, 1111 is not valid (as shown above, it comes out to 6),
  44. * while 8763 is valid (as shown above, it comes out to 20).
  45. *
  46. * @param number the credit card number to validate.
  47. * @return true if the number is valid, false otherwise.
  48. */
  49. private static boolean isValidNumber(String number) {
  50. int sum = 0;
  51.  
  52. boolean alternate = false;
  53. for (int i = number.length() - 1; i >= 0; i--) {
  54. int n = Integer.parseInt(number.substring(i, i + 1));
  55. if (alternate) {
  56. n *= 2;
  57. if (n > 9) {
  58. n = (n % 10) + 1;
  59. }
  60. }
  61. sum += n;
  62. alternate = !alternate;
  63. }
  64.  
  65. return (sum % 10 == 0);
  66. }
  67. }

以上是关于卢恩公式(算法)的主要内容,如果未能解决你的问题,请参考以下文章

信用卡验证(卢恩算法)

iPhone Sdk 中的信用卡验证算法

以下代码片段的算法复杂度

有人可以解释啥是 SVN 平分算法吗?理论上和通过代码片段[重复]

片段(Java) | 机试题+算法思路+考点+代码解析 2023

Halcon—3D测量算法的那点数学公式和代码实现