Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

recursion question

Status
Not open for further replies.

yuriythebest2

Programmer
Oct 18, 2009
6
UA
hi! I need to find the sum of all positive numbers up to N, with the step of D, for instance id D=3 and N=11 then 11+8+5+2=26. Currently my way is like so:

sum(N, D, Res) :- D<N, N1 is N - D, sum(N1, D, Res1), Res is Res1+N1.

however this yields the answer 17 which is incorrect please help!
 
well, the assigment said that if the inputs where D>=N then Res should equal N


so my full code looks like so

sum(N, D, Res) :- D<N, N1 is N - D, sum(N1, D, Res1), Res is Res1+N1.
sum(N, D, Res) :- D >= N, Res = N.

 
Sorry, the line
Code:
sum(N, D, Res) :-  D<N, N1 is N - D, sum(N1, D, Res1), Res is Res1+N1.
 
Did you try your code "at hand" as we would say in French ?
 
sorry I don't quite understand that expression (I think it's only in french)- do you mean did I try to change it in some way to make it work? yeah.

I've tried changing the code like so

sum(N, D, Res) :- D<N, N1 is N - D,Res is Res1+N1, sum(N1, D, Res1).

but that only made it worse
 
Code:
sum(N, D, N) :-
	D >= N.

sum(N, D, Res) :-
	D < N,
	N1 is N-D,
	sum(N1, D, Res1),
	Res is Res1 + N1.


sum(11, 3, Res) :-			Res = 17
	3 < 11,
	N1 is 8,
	sum(8, 3, Res1),		recursion Res1 is 9
	Res is Res + 8.			Res is 9 + 8

sum(8, 3, Res) :-			Res is 9
	3 < 8,
	N1 is 5,
	sum(5, 3, Res1),		recursion Res1 is 4
	Res is Res + 5.			Res is 4 + 5.

sum(5, 3, Res) :-			Res = 4
	3 < 5,
	N1 is 2,
	sum(5, 3, Res1),		recursion Res1 is 2
	Res is Res + 2.			Res is 2 + 2.

sum(2, 3, 2) :-
	3 >= 2.
Now, do you see where is your mistake ?
 
no sir I do not. Ok, in my attempt to understand prolog recursion I picked up a nice pdf book about prolog, which had this example

printN(0).
printN(N) :- N > 0, M is N - 1, printN(M), writeln(N).


?- printN(3).
1
2
3
Yes


What I don't understand is, if initially M is N, and then we begin to substract 1's, Why isn't the result


?- printN(3).
3
2
1
Yes

Or indeed, since we already substracted the 1 in the first step, why isn't it

?- printN(3).
2
1
Yes


 
You want to do 11+8+5+2=26
And what do you do ? 2 + 2 + 5 + 8 = 17
There is a shift in the numbers you add.

 
yeah I am too inexperienced for that- can you explain the simpler one first

printN(N) :- N > 0, M is N - 1, printN(M), writeln(N).

why is it 1 2 3 and not 3 2 1 I don't understand
 
Write the same thing as I did to explain your result of 17 rather than 26.
It's exactly the same problem.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top