开发者

How to compute the sum of unpaired numbers up to N?

开发者 https://www.devze.com 2023-04-13 09:21 出处:网络
I have some code on prolog, but this code does not work. sum(N,_):-N<0,f开发者_Python百科ail. sum(N,S):-N=0,S=0,!.

I have some code on prolog, but this code does not work.

sum(N,_):-N<0,f开发者_Python百科ail.
sum(N,S):-N=0,S=0,!.
sum(N,S):-N1=N-1,sum(N1,S1),S=S1+N.

?-sum(4,X),write(X).

Correct recursive function on PHP

function sum($n)
    { 
    if($n < 0) return; 
    if($n%2 == 0) return sum($n-1);
     else return ($n+sum($n-2)); 
    } 

I need to convert this function to prolog.

For example, sum(N, Result).

?- sum(6,Result),write(Result).

expected 9


Here a rather direct translation of the PHP code, that incidentally highlights the (IMO) weaker point of Prolog code when applied to numerical problems: the need to explicitly represent expressions intermediate results. Conventionally, we use the last argument to represent the 'return value'.

sum(N, S) :-
    (   N < 0
    ->  S = 0
    ;   (   Q is N mod 2,
            Q == 0
        ->  M is N - 1,
            sum(M, S)
        ;   M is N - 2,
            sum(M, T),
            S is N + T
        )
    ).

Test:

?- sum(6,X).
X = 9.


You might try something like this...

sum(N,X) :-
  sum(N,0,X)
  .
sum( 0 , X , X ).
sum( N , T , X ) :-
  N > 0 ,
  T1 is T+N ,
  N1 is N-1 ,
  sum( N1 , T1 , X )
  .
sum( N , T , X ) :-
  N < 0 ,
  T1 is T+N ,
  N1 is N+1 ,
  sum( N1 , T1 , X )
  .

All you want to do is sum the odd numbers between 0 and N inclusive? I think this should do the trick:

sum(0,0).
sum(N,X) :-
  N > 0 ,
  ( N mod 2 is 0 , N1 is N-1 ; N1 is N ) ,
  sum(N1,0,X)
  .

sum(N,X,X) :- N < 0 .
sum(N,T,X) :-
  N1 is N - 2
  T1 is T+N ,
  sum(N1,T1,X)
  .


This one works

sum(0,0).
sum(-1,0).
sum(N,R) :- N > 0, 0 is N mod 2,!, N1 is N - 1, sum(N1,R).
sum(N,R) :- N > 0, N2 is N - 2, sum(N2,R1), R is N + R1.

However I would write it this way:

sum(N,R) :- sum(N,0,R).
sum(0,A,A) :- !.
sum(N,A,R) :- N1 is N-1, (1 is N mod 2 -> A1 is A + N; A1 = A), sum(N1,A1,R). 

It is equivalent to something like:

int a = 0;
for(int i=N;i>0;i--) { if (i % 2==1) a += i; }
0

精彩评论

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