1

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

Paweł Poręba
  • 1,084
  • 1
  • 14
  • 37
  • Possible duplicate of [collatz-list implementation using Prolog](http://stackoverflow.com/questions/13773994/collatz-list-implementation-using-prolog) – repeat Oct 19 '15 at 21:09
  • 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 Oct 19 '15 at 21:17

1 Answers1

1

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.
Paweł Poręba
  • 1,084
  • 1
  • 14
  • 37
  • why (1,4)? shouldn't it be (1,1)? then (2,2) is redundant and you can have `X>1` in two remaining clauses. in general, it's good to keep your clauses mutually exclusive, as you've discovered. – Will Ness Oct 20 '15 at 08:47
  • If I write(1,1), then it would return N=1 for X=1, and it should return N=4. – Paweł Poręba Oct 20 '15 at 10:44
  • 1 is a special case, it stops immediately, it doesn't go 1->4->2->1 or else the last one wouldn't stop either. right? – Will Ness Oct 20 '15 at 21:33