Haskell程序实现nCr(r组合)


本教程讨论了在Haskell编程语言中编写程序以执行nCr组合。

nCr用于查找从n个项目中选择r个项目的方法数,前提是顺序无关紧要。nCr定义为n!/(r!(n-r)!)。例如,从5个项目中选择3个项目的方法数为5!/(3!(5-3)!),即10种方法。

在本教程中,我们将看到:

  • 查找数字阶乘的程序(查找nCr组合的辅助函数)。
  • 查找nCr组合的程序。

算法步骤

  • 输入或初始化变量n和r。
  • 实现计算nCr组合的逻辑。
  • 打印或显示输出。

示例1

查找数字阶乘的程序。

Open Compiler
-- function declaration factorial :: Int -> Int -- function definition factorial n = product [1..n] main :: IO() main = do -- declaring and initializing variable let n = 5 -- computing factorial of variable n let fact = factorial n -- printing the output print ("The factorial of the number " ++ show n ++ " is:") print(fact)

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

"The factorial of the number 5 is:"
120

在上面的程序中,我们声明了一个名为factorial的函数,它接受一个整数作为参数并返回一个整数。在其函数定义中,接受一个整数参数n。此函数通过调用product函数并传递一个从1到n的整数列表作为参数来计算数字的阶乘。product函数接受一个数字输入列表作为参数,并返回列表中所有元素的乘积。该列表是使用“..”运算符生成的。从a到b创建列表的语法为a..b,其中a必须小于或等于b。连续元素的差值为1。此函数返回计算出的阶乘。在主函数中,我们声明并初始化了一个变量n,该变量需要计算其阶乘。我们调用factorial函数并将n作为参数传递,并将返回的输出加载到变量fact中。最后,使用print函数打印计算出的数字n的阶乘。

注意 - show函数接受一个数字作为参数,并返回该数字的解析字符串。“++”是Haskell中用于连接字符串的运算符。

示例2

查找nCr组合的程序。

Open Compiler
-- function declaration factorial :: Int -> Int -- function definition factorial n = product [1..n] -- function declaration findCombinations :: Int->Int->Int -- function definition findCombinations n r = div (factorial n) ((factorial r) * (factorial (n-r))) main :: IO() main = do -- declaring and initializing variable let n = 5 let r = 3 -- computing the nCr combinations let output = findCombinations n r -- printing the output print ("The number of ways in which " ++ show r ++ " items can be selected from " ++ show n ++ " items is:") print(output)

输出

"The number of ways in which 3 items can be selected from 5 items is:"
10

在上面的程序中,我们声明并定义了一个名为factorial的函数,与前一个程序一样,它是一个辅助函数,用于查找nCr组合。我们声明了一个名为findCombinations的函数,它接受两个整数参数并返回一个整数。在其函数定义中,接受两个整数参数n和r。nCr是使用逻辑n!/(r!(n-r)!)计算的。factorial函数被调用以计算数字的阶乘。并返回计算出的组合。在主函数中,声明并初始化了两个整数参数(n和r)。findCombinations函数被调用,并将n和r作为参数传递。返回的输出被加载到变量output中。最后,使用print函数打印输出。

结论

在本教程中,我们讨论了在Haskell编程语言中实现一个程序以执行nCr组合。

更新于: 2022年12月14日

352次浏览

开启您的职业生涯

通过完成课程获得认证

开始学习
广告