Prolog系列的总和(Sum of a series in Prolog)

编程入门 行业动态 更新时间:2024-10-26 07:31:41
Prolog系列的总和(Sum of a series in Prolog)

我想用Prolog程序找到一系列的总和。 为此,我写了以下程序:

pow(N,1,R):- R is N. pow(N,M,R):- X is M-1,pow(N,X,R1),R is R1*N. sum(N,1,R) :- R is N+1 . sum(N,M,R) :- X is M-1, X>1,sum(N,X,R1),pow(N,M,R2), R is (R1+R2).

我想找到以下系列的总和:

1+n+n^2+n^3+..................+n^m

我相信上面的代码是对的。 但是当我运行程序时,它显示输出“否”。 为什么? 我已经尝试了很多,但无法获得预期的输出。

I want to find sum of a series using Prolog program . For this purpose , I have written the following program :

pow(N,1,R):- R is N. pow(N,M,R):- X is M-1,pow(N,X,R1),R is R1*N. sum(N,1,R) :- R is N+1 . sum(N,M,R) :- X is M-1, X>1,sum(N,X,R1),pow(N,M,R2), R is (R1+R2).

I want to find the sum of following series :

1+n+n^2+n^3+..................+n^m

My believe is the above code is right . But when I run the program , it shows output "No" . Why ? I have tried a lot , but could not get expected output .

最满意答案

你错过了X>1的else分支,如果你删除它,你会得到一个结果:

... sum(N,M,R) :- X is M-1, sum(N,X,R1), pow(N,X,R2), R is (R1+R2). ... ?- sum(2,3,X). X = 15 ; ^C

但程序没有终止(^ C用于中断循环)。

我会使用累加器重写,以获得LCO(Last Call Optimization)和内置pow所允许的更高效率:

sum(N,M,R) :- sum(N,M,0,R). sum(N,M,A,R) :- ( M > 0 -> A1 is A + N^M, %% N**M, M1 is M-1, sum(N,M1,A1,R) ; R is A + 1 ).

编辑关于运算符(**)/ 2的SWI-Prolog文档是不正确的:更好地使用(^)/ 2,如@false所述

you miss the else branch of X>1, and if you remove it, you get a result:

... sum(N,M,R) :- X is M-1, sum(N,X,R1), pow(N,X,R2), R is (R1+R2). ... ?- sum(2,3,X). X = 15 ; ^C

but the program doesn't terminate (^C used to interrupt the loop).

I would rewrite using an accumulator, to get the better efficiency allowed by LCO (Last Call Optimization) and the built in pow:

sum(N,M,R) :- sum(N,M,0,R). sum(N,M,A,R) :- ( M > 0 -> A1 is A + N^M, %% N**M, M1 is M-1, sum(N,M1,A1,R) ; R is A + 1 ).

edit SWI-Prolog documentation about operator (**)/2 is incorrect: better to use (^)/2, as remarked by @false

更多推荐

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

发布评论

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

>www.elefans.com

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