Алгоритм Луна
Алгоритм Луна, також відомий як модуль 10 або до 10 алгоритм — це проста формула контрольної суми, яка використовується для перевірки різноманітних ідентифікаційних номерів, таких як номери кредитних карток, номери IMEI, номери канадського соціального страхування. Формула LUHN була створена наприкінці 1960-х років групою математиків. Незабаром після цього його прийняли компанії з кредитних карток. Оскільки алгоритм знаходиться у відкритому доступі, ним може користуватися кожен. Більшість кредитних карток і багато державних ідентифікаційних номерів використовують алгоритм як простий спосіб відрізнити дійсні номери від неправильно введених або іншим чином неправильних чисел. Його розроблено для захисту від випадкових помилок, а не від зловмисних атак.
Етапи алгоритму Луна
Розберемо алгоритм на прикладі:
Розглянемо приклад номера рахунку 79927398713 .
Крок 1 – Починаючи з крайньої правої цифри, подвоїти значення кожної другої цифри,
Крок 2 – Якщо в результаті подвоєння числа виходить двоцифрове число, тобто більше 9 (наприклад, 6 × 2 = 12), то додайте цифри добутку (наприклад, 12: 1 + 2 = 3, 15: 1 + 5 = 6), щоб отримати одноцифрове число.
Крок 3 – А тепер візьміть суму всіх цифр.
Крок 4 – Якщо загальна сума за модулем 10 дорівнює 0 (якщо загальна сума закінчується на нуль), то число дійсне згідно з формулою Луна; інакше це недійсно.
Оскільки сума дорівнює 70, що є кратним 10, номер рахунку, можливо, дійсний.
Ідея проста; проходимо з кінця. Для кожної другої цифри ми подвоюємо її перед додаванням. Складаємо дві цифри отриманого після подвоєння числа.
Реалізація:
C++
// C++ program to implement Luhn algorithm> #include> using> namespace> std;> // Returns true if given card number is valid> bool> checkLuhn(> const> string& cardNo)> {> > int> nDigits = cardNo.length();> > int> nSum = 0, isSecond => false> ;> > for> (> int> i = nDigits - 1; i>= 0; i--) {> > int> d = cardNo[i] -> '0'> ;> > if> (isSecond ==> true> )> > d = d * 2;> > // We add two digits to handle> > // cases that make two digits after> > // doubling> > nSum += d / 10;> > nSum += d % 10;> > isSecond = !isSecond;> > }> > return> (nSum % 10 == 0);> }> // Driver code> int> main()> {> > string cardNo => '79927398713'> ;> > if> (checkLuhn(cardNo))> > printf> (> 'This is a valid card'> );> > else> > printf> (> 'This is not a valid card'> );> > return> 0;> }> |
Java
// Java program to implement> // Luhn algorithm> import> java.io.*;> class> GFG {> > // Returns true if given> // card number is valid> static> boolean> checkLuhn(String cardNo)> {> > int> nDigits = cardNo.length();> > int> nSum => 0> ;> > boolean> isSecond => false> ;> > for> (> int> i = nDigits -> 1> ; i>=> 0> ; i--)> > {> > int> d = cardNo.charAt(i) -> '0'> ;> > if> (isSecond ==> true> )> > d = d *> 2> ;> > // We add two digits to handle> > // cases that make two digits> > // after doubling> > nSum += d /> 10> ;> > nSum += d %> 10> ;> > isSecond = !isSecond;> > }> > return> (nSum %> 10> ==> 0> );> }> > // Driver code> > static> public> void> main (String[] args)> > {> > String cardNo => '79927398713'> ;> > if> (checkLuhn(cardNo))> > System.out.println(> 'This is a valid card'> );> > else> > System.out.println(> 'This is not a valid card'> );> > > }> }> // This Code is contributed by vt_m.> |
Python3
# Python3 program to implement> # Luhn algorithm> # Returns true if given card> # number is valid> def> checkLuhn(cardNo):> > > nDigits> => len> (cardNo)> > nSum> => 0> > isSecond> => False> > > for> i> in> range> (nDigits> -> 1> ,> -> 1> ,> -> 1> ):> > d> => ord> (cardNo[i])> -> ord> (> '0'> )> > > if> (isSecond> => => True> ):> > d> => d> *> 2> > > # We add two digits to handle> > # cases that make two digits after> > # doubling> > nSum> +> => d> /> /> 10> > nSum> +> => d> %> 10> > > isSecond> => not> isSecond> > > if> (nSum> %> 10> => => 0> ):> > return> True> > else> :> > return> False> # Driver code> if> __name__> => => '__main__'> :> > > cardNo> => '79927398713'> > > if> (checkLuhn(cardNo)):> > print> (> 'This is a valid card'> )> > else> :> > print> (> 'This is not a valid card'> )> # This code is contributed by rutvik_56> |
C#
// C# program to implement> // Luhn algorithm> using> System;> class> GFG {> > // Returns true if given> // card number is valid> static> bool> checkLuhn(String cardNo)> {> > int> nDigits = cardNo.Length;> > int> nSum = 0;> > bool> isSecond => false> ;> > for> (> int> i = nDigits - 1; i>= 0; я--)> > {> > int> d = cardNo[i] -> '0'> ;> > if> (isSecond ==> true> )> > d = d * 2;> > // We add two digits to handle> > // cases that make two digits> > // after doubling> > nSum += d / 10;> > nSum += d % 10;> > isSecond = !isSecond;> > }> > return> (nSum % 10 == 0);> }> > // Driver code> > static> public> void> Main()> > {> > String cardNo => '79927398713'> ;> > if> (checkLuhn(cardNo))> > Console.WriteLine(> 'This is a valid card'> );> > else> > Console.WriteLine(> 'This is not a valid card'> );> > > }> }> // This Code is contributed by vt_m.> |
Javascript
> > // Javascript program to implement Luhn algorithm> > > // Returns true if given> > // card number is valid> > function> checkLuhn(cardNo)> > {> > let nDigits = cardNo.length;> > let nSum = 0;> > let isSecond => false> ;> > for> (let i = nDigits - 1; i>= 0; я--)> > {> > let d = cardNo[i].charCodeAt() -> '0'> .charCodeAt();> > if> (isSecond ==> true> )> > d = d * 2;> > // We add two digits to handle> > // cases that make two digits> > // after doubling> > nSum += parseInt(d / 10, 10);> > nSum += d % 10;> > isSecond = !isSecond;> > }> > return> (nSum % 10 == 0);> > }> > > let cardNo => '79927398713'> ;> > if> (checkLuhn(cardNo))> > document.write(> 'This is a valid card'> );> > else> > document.write(> 'This is not a valid card'> );> > > |
Вихід
This is a valid card
Алгоритм Луна виявляє будь-яку однозначну помилку, а також майже всі транспозиції сусідніх цифр.