this is the fast luhn validation code in go that uses the pre-calculated numeric transformation table, and a toggle-free left-to-right scan i came up with. details are found 
here. [again, i excluded the 
isdigit check]
var ltab = [10]int { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 }
func luhn(s string) bool {
    n := len(s)
    if n < 2 {
        return false /* less than minimum */
    }
    /*
     * if the length is odd, add the value of the
     * first digit and skip
     */
    sum := 0
    i := 0
    if n & 1 == 1 {
        sum = int(s[i]) - int('0')
        i++
    }
    for i < n {
        sum += ltab[int(s[i]) - int('0')]
        sum += int(s[i+1]) - int('0')
        i += 2
    }
    return (sum % 10) == 0
}
 
No comments:
Post a Comment