John Jackson
John Jackson

Reputation: 9

How to check if a number is power of 2

I want to create a function that takes a number and checks if this number is power of 2. Like: fn(0) is no, fn(1) is yes, fn(2) is yes, fn(3) is no
etc... I tried to make a power function like power(N,K,R) but this doesn't work if I ask something like power(2,_,8). Any help will be appreciated.

Upvotes: 0

Views: 566

Answers (1)

flawr
flawr

Reputation: 11628

If we use prolog we could do as follows:

pow2(X) :- X > 0 , 0 is X /\ (X-1).

Here /\ is bitwise AND. So if X is a power of two, it looks like 1000...0 in binary, and therefore X-1 is 111...1 and the bitwise AND is therefore 0. It is straightforward to see that this only happens for powers of two.

Try it online!

Upvotes: 5

Related Questions