Prolog - 获取给定数字的因子不会停止? [英] Prolog - get the factors for a given number doesn't stop?

查看:45
本文介绍了Prolog - 获取给定数字的因子不会停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到给定数字的因数,例如:

I need to find the factors of a given number , e.g :

?- divisors2(40,R).
R = [40,20,10,8,5,4,2,1].

代码:

% get all the numbers between 1-X 
range(I,I,[I]).
range(I,K,[I|L]) :- I < K, I1 is I + 1, range(I1,K,L).
% calc the modulo of each element with the given number :
% any x%y=0 would be considered as part of the answer 
divisors1([],[],_).
divisors1([H|T],S,X):-divisors1(T,W,X),Z is X mod H,Z==0,S=[H|W].
divisors1([_|T],S,X):-divisors1(T,S,X).
divisors2(X,Result) :-range(1,X,Result1),divisors1(Result1,Result,X).

但是当我运行 divisors2(40,RR) 时. 我得到了无限循环并且没有任何东西显示在屏幕上.

But when I run divisors2(40,RR). I get infinite loop and nothing is presented to the screen.

为什么?

问候

推荐答案

你在这里有一个错误

divisors1([H|T],S,X):-
   divisors1(T,W,X),
   Z is X mod H,
   Z==0,S=[H|W]. <=== here

如果 Z 为零,则 S = [H|W] 否则 S = W.

If Z is Zero then S = [H|W] else S = W.

这篇关于Prolog - 获取给定数字的因子不会停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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