1. 程式人生 > >Luhn演算法(模10演算法)檢驗銀行卡號正確性

Luhn演算法(模10演算法)檢驗銀行卡號正確性

中文描述: 1、從卡號最後一位數字開始,偶數位乘以2,如果乘以2的結果是兩位數,將結果減去9。 2、把所有數字相加,得到總和。

3、如果信用卡號碼是合法的,總和可以被10整除。

英文描述

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.

程式碼

C++: char digit; int oddLengthChecksum=0; int evenLenthChecksum=0; int position =1; cout<<"Enter a number:"; digit=cin.get(); while(digit != 10) { if(position%2==0) { oddLengthChecksum+=doubleDigitValue(digit-'0'); evenLengthChecksum+=digit-'0'; } else { oddLengthChecksum+=digit-'0'; evenLenthChencksum+=doubleDigitValue(digit-'0'); } digit=cin.get(); position++; } int checksum; //對輸入的標識號長度進行奇偶檢查 if((position-1)%2==0) checksum=evenLenthChecksum; //position-1 原因:前段使用cin.get()函式,最後一個字元是表示結束的行末符 else checksum=oddLengthChecksum; cout<<"Checksum is"<<checksum<<".\n"; if(checksum%10==0) { cout<<"Checksum is divisible by 10. Valid.\n"; } else { cout<<"Checksum is not divisible by 10. Invalid. \n"}