Skip to content

Instantly share code, notes, and snippets.

@Ran-ying
Created January 31, 2023 19:27
Show Gist options
  • Save Ran-ying/b8625f02d672ce5d8889bb093a779667 to your computer and use it in GitHub Desktop.
Save Ran-ying/b8625f02d672ce5d8889bb093a779667 to your computer and use it in GitHub Desktop.

计算原理

参见 百度百科

  1. 将前面的身份证号码 17 位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
  2. 将这 17 位数字和系数相乘的结果相加;
  3. 用加出来和除以 11,看余数是多少;
  4. 余数只可能有 0 1 2 3 4 5 6 7 8 9 10 这11个数字。其分别对应的最后一位身份证的号码为 1 0 X 9 8 7 6 5 4 3 2

JavaScript

const co = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
const re = [1,0,10,9,8,7,6,5,4,3,2]
const test = (id, sum = 0)=>{
    if(id.length != 18) return false;
    if(id[17].toUpperCase()=="X") id[17]=10;
    for(let i in co) sum += co[i]*id[i];
    if(re[sum%11]!=id[17]) return false;
    else return true;
}

Python

co = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
re = [1,0,10,9,8,7,6,5,4,3,2]
while True:
    id = list(input("ID:"))
    if len(id)!=18:
        print("Error")
        continue
    if id[17].upper()=="X":
        id[17]=10
    id = [int(i) for i in id]
    if re[sum([co[i]*id[i] for i in range(len(co))])%11]!=id[17]:
        print("False")
    else:
        print("True")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment