开发者

Prolog: Simple program outputting solutions

I've got a predicate taking a single argument. When there is a solution, this single argument should equal some other argument I have (I have a predicate that goes from one argument to three).

I can print the solution easily to see that the algorithm works. However, I just get false/no when the program runs. I think this is something to do with me giving the program a variable and asking it to return the same variable but altered by the program's execution. I've never had this situation before.

Any ideas guys?

If anyone as any suggestions about the code as a whole then I would welcome comments about that too.

Thanks very much and happy new year :).

% Eulers totient function 
phi( M ) :-
    phi( 0, 0, M ).    
phi( Count, Inter, M ) :-
    Count = M,
    print(Inter),
    M is Inter.
phi( Count, Inter, M ) :-
    Count \= M,
    coprime( Count, M ),
    InterNew is Inter + 1,
    CountNew is Count + 1, 
    phi( CountNew, InterNew, M ).
phi( Count, Inter, M ) :-
    Count \= M,
    \+ coprime( Count, M ),
    CountNew is Count + 1,
 开发者_如何学JAVA   phi( CountNew, Inter, M ).

UPDATE: This problem is one of the '99 Prolog problems' at : http://sites.google.com/site/prologsite/prolog-problems/2 and it's question 2.09.

UPDATE: coprime/2 predicate was asked for:

% coprime is defined as two integers having a gcd of 1  
coprime( X, Y ) :-
    gcd( X, Y, 1 ).

which uses gcd predicate:

% calculating the greatest common divisor of two numbers
% recursive version of Euclidian algorithm
gcd( G, 0, G ).
gcd( Lo, Hi, G ) :-
    Hi \= 0,
    Inter is Lo mod Hi,
    gcd( Hi, Inter, G ).


The false/no answer results from the call M is Inter, which tries to establish equality between the totient Inter and the input number M. Since φ(n) is never equal to n except when n = 1, this almost always fails.

You may have intended to assign the value of Inter to M, but this impossible because M is always bound.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜