Prolog阶乘递归

编程入门 行业动态 更新时间:2024-10-22 07:25:45
本文介绍了Prolog阶乘递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我无法理解以下析因程序

I'm having trouble understanding the following factorial program

fact1(0,Result) :- Result is 1. fact1(N,Result) :- N > 0, N1 is N-1, fact1(N1,Result1), Result is Result1*N.

当调用fact1嵌套在第二个fact1中时,这是否表示从不调用最后一行Result is Result1*N.?还是在Prolog中,最后一行是在递归调用之前执行的?

When fact1 is called nested within the second fact1, doesn't that mean that the the last line, Result is Result1*N., is never called? Or in Prolog does the last line get executed before the recursive call?

推荐答案

否,递归调用首先发生!它必须这样做,否则最后一个子句是没有意义的.该算法可分解为:

No, the recursive call happens first! It has to, or else that last clause is meaningless. The algorithm breaks down to:

factorial(0) => 1 factorial(n) => factorial(n-1) * n;

如您所见,您需要在进行乘法运算之前计算递归的结果,以返回正确的值!

As you can see, you need to calculate the result of the recursion before multiplying in order to return a correct value!

您的prolog实现可能具有启用跟踪的方法,这将使您看到整个算法正在运行.这可能会帮助您.

Your prolog implementation probably has a way to enable tracing, which would let you see the whole algorithm running. That might help you out.

更多推荐

Prolog阶乘递归

本文发布于:2023-11-30 03:16:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648541.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   阶乘   Prolog

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!