Program in Prolog for sum of numbers in interval

前端 未结 4 1237
粉色の甜心
粉色の甜心 2021-01-21 19:30

I\'m trying to create a program in Prolog which takes two numbers - A and B and finds the sum of the numbers from A to B, including them.

To sum up: sum(1, 5, C) should

4条回答
  •  灰色年华
    2021-01-21 20:05

    I suppose you could use brute force to compute the sum of a finite arithmetic sequence, but wouldn't it be easier just to use your maths?

    sum(A,B,X) :-
      A =< B ,
      N is 1+B-A ,
      X is N*(A+B) / 2
      .
    

    Or, more generally, for computing the sum of a finite sequence of n terms, starting with a, with a "step size" (relative difference) of d, you get:

    sum(A,D,N,S) :- S is (N*(2*A+(N-1)*D))/2 .
    

    But if you're going to use brute force, make it tail recursive:

    sum(A,B,S) :- A =< B , sum(A,B,0,S) .
    
    sum(A,B,S,S) :-
      A > B
      .
    sum(A,B,T,S) :-
      A =< B ,
      T1 is T+A ,
      A1 is A+1 ,
      sum(A1,B,T1,S)
      .
    

提交回复
热议问题