Prolog, check if term is power of 2

Posted by Riku on Stack Overflow See other posts from Stack Overflow or by Riku
Published on 2013-10-30T07:12:00Z Indexed on 2013/10/30 15:54 UTC
Read the original article Hit count: 144

i have written following code, which should work with my logic, but it does not.

I should check if given term is power of two. For example s(s(s(nul))) should return false, s(s(s(s(nul))) should return true.

substractWhileY(X,0,rezult).
substractWhileY(s(X),Y,rezult):- Y > 0, number is 1,  substractWhileY(X,Y - number, rezult).

degreeOftwo(X):- substractWhileY(X,2,rezult), pagalba(X, 2, rezult).
calculateAnswer(X, currentCounter, currentValue):- currentCounter is currentCounter * 2,
substractWhileY(currentValue, currentCounter , rezult),
rezult\= null,
calculateAnswer(X, currentCounter , rezult).

My idea was to check if given therm is degree of any two and if it is not than it is not the degree of two.

With numbers it should work like this. For example i give number 8.

First time it checks if 8 - 2 = 0.
second time if 8 - 4 = 0.
third time if 8 - 8 = 0.

so the 8 id power of two.

Maybe other solution would work better, so thanks for any help.

© Stack Overflow or respective owner

Related posts about prolog

Related posts about swi-prolog