📅  最后修改于: 2023-12-03 15:09:19.468000             🧑  作者: Mango
这是一个可以计算排列组合的程序,可以输入物品总数和选取的个数,输出对应的排列数和组合数。
输入共一行,包括两个整数,分别是物品总数和选取的个数,中间空格隔开。
例如:
23 5
程序将输出以下两行:
排列数: 3369450
组合数: 33649
import math
n, m = map(int, input().split())
permutation = math.factorial(n) // math.factorial(n-m)
combination = math.factorial(n) // (math.factorial(m) * math.factorial(n-m))
print("排列数: {}".format(permutation))
print("组合数: {}".format(combination))
这个程序使用了Python的math库,用到了其中的factorial函数,用以计算阶乘。排列数和组合数的计算方法分别使用了排列组合公式:
排列数(Permutation): A(n,m) = n! / (n-m)!
组合数(Combination): C(n,m) = n! / (m!*(n-m)!)
其中,n为物品总数,m为选取的个数。
因为当物品总数为23时,其阶乘的结果已经超出了Python的整数表示范围,因此需要使用Python的整数除法(//),避免了因小数位舍入而造成的计算误差。