I'm stuck with some Prolog exercise. I am to write a predicate collatz2(X,N) which, assuming we know what X is, returns N that is the index (starting from 1) for the result of 1. 'collatz2' is the Collatz function. So assuming I will write collatz2(5,N)
, it should return N=6
, because collatz1(N)
(check below for explanation for this predicate) results in:
5
16
8
4
2
1
true
I've written a predicate giving the consecutive numbers:
collatz1(X):-X>0,X mod 2 =:= 0,write(X),nl,X1 is X//2,X1=\=1,collatz1(X1).
collatz1(X):-X>0,X mod 2 =\= 0,write(X),nl,X1 is 3*X +1,X1=\=1,collatz1(X1).
collatz1(2):-write(1).
Yet, I can't figure out the second predicate. It should be simple, cause it's just my beginnig with Prolog. Can anybody help?
EDIT:
It's not duplicate. I don't know lists yet and I need to use what I already know (which is just real basis). Here is what I have so far:
collatz2(X,1):-X=1.
collatz2(X,N):-X>0,X mod 2 =:= 0,X1 is X//2,collatz2(X1,R),N is R+1.
collatz2(X,N):-X>0,X mod 2 =\= 0,X1 is 3*X+1,collatz2(X1,R),N is R+1.
But I need to stop loop somehow:) Thanks:)