Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog Find the sum of integers between two integers

Tags:

prolog

I am using GNU-Prolog trying to write a program that accepts N and M positive integers and sums all numbers between N and M , including N and M.

my code is:

findnum(N, N, M).    
findnum(N, M, Res) :- N1 is N+1, N1 < M, findnum(N1, M, Res), Res is N1 + M.

Execution only returns "no" with no answer, any idea what's the problem?

like image 565
xyro Avatar asked Dec 13 '25 14:12

xyro


1 Answers

Try with

findnum(N, N, N).    

findnum(N, M, Res) :-
   N1 is N+1,
   N < M,
   findnum(N1, M, R0),
   Res is R0 + N.

Your first clause

findnum(N, N, M).

is wrong because you have to set (to unify) M to a value; and if you want sum numbers from N to N, the sum is N, so

findnum(N, N, N).

The idea for the second clause is to sum N to the sum from N+1 to M; I see three errors in your implementation:

1) you have to call the terminal clause (findnum(N, N, N)) so is wrong the guard N1 < M because you have to call the terminal clause when N1 is equal to M; the correct guard is N < M or N1 <= M

2) if your recursive call to findnum/3 use, for the third argument, the same variable (Res), you can't add N, so you have to call with another variable: R0 in my example

3) Res is N1 + M is wrong; the correct version is Res is R0 + N; the current number (N) plus the sum from N+1 to M.

like image 199
max66 Avatar answered Dec 15 '25 10:12

max66