#仿射密码
def encrypt(k1,k2,message):
# *************begin************#
message1 = list(message)
list1=list(map(chr,range(ord('a'),ord('z')+1)))
list2=list(map(chr,range(ord('A'),ord('Z')+1)))
for i in range(len(list1)):
list1.append(list2[i])
y=[]
for i in range(len(message)):
if message1[i]==' ':
y.append(message1[i])
else:
for j in range(52):
if message1[i]==list1[j]:
y.append(list1[(k1*j + k2) % 52])
result = ''.join(y)
return result
# **************end*************#
def decrypt(k1,k2,message):
# *************begin************#
#扩展欧几里得算法求逆元法
# x1, x2, x3 = 1, 0, 52
# y1, y2, y3 = 0, 1, k1
# while True:
# if y3 == 0:
# return 'None'
# break
# elif y3 == 1:
# a_reverse =y2 % 52
# break
# else:
# Q = x3 // y3
# t1, t2, t3 = x1 - Q * y1, x2 - Q * y2, x3 - Q * y3
# x1, x2, x3 = y1, y2, y3
# y1, y2, y3 = t1, t2, t3
#已知模求逆元
for i in range(1,53):
if k1 * i % 52 == 1:
a_reverse = i
message1 = list(message)
list1=list(map(chr,range(ord('a'),ord('z')+1)))
list2=list(map(chr,range(ord('A'),ord('Z')+1)))
for i in range(len(list1)):
list1.append(list2[i])
x=[]
for i in range(len(message1)):
if message1[i]==' ':
x.append(message1[i])
else:
for j in range(52):
if message1[i]==list1[j]:
x.append(list1[(a_reverse * (j-k2) )% 52])
result = ''.join(x)
return result
# **************end*************#
def main():
mode = int(input()) # 1代表加密,0代表解密
message = input() #待加密或解密的消息
key1 = int(input()) # key的范围0~51之间
key2 = int(input()) # key的范围0~51之间
if mode == 1:
translated = encrypt(key1,key2,message)
else:
translated = decrypt(key1,key2,message)
print(translated)
if __name__=='__main__':
main()
|