排列数与插入

image
这道题思路其实不难,就是暴力枚举,但是难点是怎么写,主要还是用到了两个库函数itertools和math
写法如下

点击查看代码
import itertools
import math
n=int(input())
best_num=99999999
max_gcd=0
for i in itertools.permutations("12345678",8):
  eight=''.join(i)
  for insert_d in ("12345678"):
      for pos in range(9):
        nine=eight[:pos]+insert_d+eight[pos:]
        num=int(nine)
        current_gcd=math.gcd(n,num)
        if current_gcd>max_gcd:
          best_num=num
          max_gcd=current_gcd
        if current_gcd==max_gcd:
          best_num=min(num,best_num)
print(best_num)
posted @ 2026-05-24 15:41  zidurile  阅读(11)  评论(0)    收藏  举报