我想用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^mMy 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 ; ^Cbut 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
更多推荐
发布评论