Prolog and Recursion

Tag: recursion , prolog Author: jsmhabc Date: 2013-04-12

I'm new at prolog and recursion in general. Given the size of each cube is represented by the cube number. For example, total_cube_volume(3, T), will have 3 cubes: the first cube will have 1 inch on each side, the second cube will have 2 inches on each side, and the third cube will have 3 inches on each side. Therefore, the total volume for this problem is 36.

This is what I have so far, it compiles but when I ask total(3,T) it replys no. Any suggestions would help. Thanks.

 total(0,T).

 total(N,T):-
     N>0,
     N1 is N-1,
     T1 is N*N*N,
     total(N1,T1),
     T is T+T1.

Best Answer

Your recursion is wrong. You are both calculating T1, and passing it into the recursive next statement. What you probably want to do is compute N*N*N into T1, pass in some variable T2 into the recursive total call, and then sum those two values. Also, your base case is wrong, you want that the total of 0 is 0.

total(0,0).

total(N,T):-
    N > 0,
    N1 is N-1,
    T1 is N*N*N,
    total(N1,T2),
    T is T2+T1.

comments:

ahh thank you so much for explaining