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"}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值