Program in Prolog for sum of numbers in interval

前端 未结 4 1205
粉色の甜心
粉色の甜心 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:17

    You can't instantiate C1 as C+A because C is not yet an integer.

    Let's call sum(1, 5, C)

    sum(1, 5, C)
    
    ---> 1 =< 5 ... true
    
    ---> A1 is 1 + 1 ... A1 = 2 (fine)
    
    ---> C1 is C + 2, C = something like _G232, not yet instantiated.
    

    Let's take a look at your logic.

    We would have a base case, when A and B are equal, that will be our 'starting' sum

    sum(X,X,X).
    

    Then we have our general case. each recursive call will give us the sum from k + 1 to n where we call sum(k,n,sum).

    sum(A, B, C):- A =< B, A1 is A + 1, sum(A1,B,C1), C is C1 + A.
    

提交回复
热议问题