阶乘如何计算? [英] How is factorial computed?

查看:93
本文介绍了阶乘如何计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说有一个函数可以计算阶乘(n)

say there is a function to calculate factorial(n)

阶乘(7)是否为从1到7的n中的每一个创建7个函数对象

Does factorial(7) creates 7 function object for each of n from 1 to 7

并在必要时使用这些值(对于factorial(8)就像factorial(7)* 8一样)

and use those values when ever necessary (for factorial(8) as like factorial(7)*8)

推荐答案

这取决于语言和语言实现.

It depends on the language and the language implementation.

在许多功能语言(例如Haskell)中,保证某个功能什么都不会改变;只返回一个值.由于没有副作用,因此该语言可以记住/缓存或记住"函数调用的结果.

In many functional languages (e.g. Haskell), a function is guaranteed to change nothing; only to return a value. This lack of side effects allows the language to remember/cache, or "memoize", the results of function calls.

在一种不太复杂的语言中,可能会在堆栈上放置7个不同的函数调用框架并弹出.

In a less sophisticated language, 7 distinct function call frames might be placed on the stack and popped off.

在许多功能语言中正确编写的阶乘函数也将是尾递归;在那种情况下,该语言可能选择简单地从函数底部跳转到顶部,以避免创建另一个函数调用.在这种情况下,该语言将递归函数变成免费"循环.

A properly written factorial function in many functional languages would also be tail recursive; in that case the language might choose to simply jump from the bottom of the function to the top to avoid creating another function call. In this case the language is turning the recursive function into a loop "for free".

这篇关于阶乘如何计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆