Program in Prolog for sum of numbers in interval

前端 未结 4 1235
粉色の甜心
粉色の甜心 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 19:55

    In SWI-Prolog, the simplest way to implement it is:

    ?- numlist(1, 5, List), sum_list(List, Sum).
    List = [1, 2, 3, 4, 5],
    Sum = 15.
    

    Your code tries to evaluate C+A but C is not known yet, therefore the error message.

    Btw, you can also calculate this sum directly, without any iteration or list generation, see https://math.stackexchange.com/questions/50485/sum-of-n-consecutive-numbers

提交回复
热议问题