Luhn Checksum Walks Digits In Reverse
Walk digits in reverse, double every second one and fold 16 into 7, then the total must divide by ten for the card number to validate.
Code
// Luhn checksum walks the digits in reverse:validate card numbers 时
// 从最右位开始隔位翻倍,翻倍超过 9 就按位求和(等价于减 9)
fn luhn_check(digits: &str) -> bool {
let sum: u32 = digits
.chars()
.rev()
.enumerate()
.map(|(i, c)| {
let d = c.to_digit(10).expect("only digits");
if i % 2 == 1 {
let doubled = d * 2;
if doubled > 9 { doubled - 9 } else { doubled }
} else {
d
}
})
.sum();
sum % 10 == 0
}
fn main() {
// 经典样本:校验和为 70,能被 10 整除;末位改动一位立即失败
println!("valid: {}", luhn_check("79927398713"));
println!("invalid: {}", luhn_check("79927398714"));
}How it works
Luhn Checksum Walks Digits In Reverse is built around the functions luhn_check and main.
Applying it
The primary signature is fn luhn_check(digits: &str) -> bool
The run prints valid:, invalid: — each prefix names the step that produced it.
The entry point wires luhn_check together — run it once and the whole demo flows.
Statements that matter
.map(|(i, c)| {
let d = c.to_digit(10).expect("only digits");
if i % 2 == 1 {
let doubled = d * 2;
if doubled > 9 { doubled - 9 } else { doubled }
} else {
d
}
})
Interactive Tools for This Topic
Luhn Checksum ValidatorValidate numeric identifiers with the Luhn algorithm and see the checksum sum and suggested final digit on failure.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.IMEI ValidatorValidate 15-digit IMEI numbers with the Luhn checksum, with a full digit-by-digit computation trace and TAC/SNR field breakdown.ISBN ValidatorValidate ISBN-10 and ISBN-13 identifiers with checksum verification, hyphen-tolerant input, and conversion between the two forms.
FAQ
- What does Luhn Checksum Walks Digits In Reverse print when run?
- No setup needed: run the file and look for labeled lines like `valid:`, `invalid:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.