python运行代码

给你一个整数n,m,我们定义n的最亲密的数为:重排n的每一数位(首位不为零),假如重排后的数字为m的倍数,则这个数为n最亲密的数,现在问对于整数n和m,n的最亲密的数有多少个。

输入描述:

输入两个整数n(1 <= n <= 10^12)和 m(1 <= m <= 100)
第一行输入n,第二行输入m

import itertools
n=input()  #字符串
m=int(input())  #直接转int
count=0
l=list(n)  #转list
a=itertools.permutations(l,len(n))  #排列组合
for i in a:
    b=''.join(i)  #list重新变回str
    if b!=n and len(str(int(b)))==len(n) and int(b)%m==0:
        count+=1
        #b与n不能一样;b转int再转回str要与之前一样长,排除0开头
print(count)

具体代码实现如下:

# 读入n和m
n = int(input("请输入n:"))
m = int(input("请输入m:"))

# 将n转换为字符串
n_str = str(n)

# 计数器,用来记录最亲密的数的个数
counter = 0

# 枚举每一个数位
for digit in n_str:
  # 将数位转换为整数
  num = int(digit)
  # 判断是否为m的因数
  if num != 0 and n % num == 0:
    # 如果是,计数器加1
    counter += 1

# 输出结果
print(counter)

代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Description: todo
Author: gnn
Date: 2022/12/20
"""
import itertools

n = input('输入n: ')
assert 1 <= int(n) <= 10 ** 12

m = input('输入m: ')
assert 1 <= int(m) <= 100

itr = itertools.permutations([e for e in str(n)], len(str(n)))

# 排除 0 开头
result = [''.join(num) for num in itr if not ''.join(num).startswith('0') and int(''.join(num)) % int(m) == 0]

# 去重
result = list(set(result))
print(result)

print(f'最亲密的数有 {len(result)} 个')

结果:

输入n: 100
输入m: 10
['100']
最亲密的数有 1 个

Process finished with exit code 0

下面是用 Python 实现上述算法的代码:

def solve(n: int, m: int) -> int:
    # 如果n为0,则返回0
    if n == 0:
        return 0
    # 计算n的位数
    digits = 0
    tmp = n
    while tmp > 0:
        digits += 1
        tmp //= 10
    # 初始化答案为0
    ans = 0
    # 从最高位开始枚举每一位的数字
    for i in range(1, digits + 1):
        # 取出最高位的数字
        d = n // (10 ** (i - 1)) % 10
        # 如果最高位为0,则跳过
        if d == 0:
            continue
        # 否则,求n除去最高位的数字之后剩下的数字的最亲密的数的个数
        rem = n - d * (10 ** (i - 1))
        ans += solve(rem, m)
    return ans

def main():
    # 读入n和m
    n, m = map(int, input().split())
    # 调用函数求解
    ans = solve(n, m)
    print(ans)

if __name__ == '__main__':
    main()
n = int(input("请输入n:"))
m = int(input("请输入m:"))

n_str = str(n)

counter = 0

for digit in n_str:
  num = int(digit)
  if num != 0 and n % num == 0:
    counter += 1

print(counter)


from itertools import permutations
n = input()
m = int(input())
listn=list(permutations(n,len(n)))
#print(listn)
beishu=0
for i in listn:
    if i[0]!='0':
        intn=int("".join(i))
        #print(intn)
        if intn%m==0:
            beishu+=1            
print(beishu)

代码:

import itertools

def count_closest_numbers(n: int, m: int) -> int:

    permutations = itertools.permutations(str(n))

    count = 0
    for permutation in permutations:
        rearranged_number = int(''.join(permutation))
        if rearranged_number % m == 0:
            count += 1

    return count


n = 123
m = 4
print(count_closest_numbers(n, m))  # Expected output: 2