1
votes

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:)

1
It's nt duplication. I don't want to implement List. It should be simplier way to do it, cause I don't know lists yet, and I need to use what I know:)Paweł Poręba

1 Answers

1
votes

Okay, I've managed to solve this, my last edit needed just a little adjustment:

collatz2(1,4).
collatz2(2,2).
collatz2(X,N):-X>2,X mod 2 =:= 0,X1 is X//2,X=\=1,collatz2(X1,R),N is R+1.
collatz2(X,N):-X>2,X mod 2 =\= 0,X1 is 3*X+1,X=\=1,collatz2(X1,R),N is R+1.