Determining whether a number is a power of 2 in a pattern

I am new to Scheme and I am trying to learn it myself from scratch. I am stuck in the syntax of this problem. I know that if I want to find out if a number is a power of 2, for example, in C, I would simply do:

return (x & (x - 1)) == 0;

which will return true or false. How could I convert this to a couple of simple lines in a schema?

+3
source share
3 answers

I will give you a hint as you are trying to learn a language.

The circuit has a function called (bitwise-and ...)that is equivalent to an operator &in C (exists as well (bitwise-xor ...), (bitwise-not ..)etc., which does the expected thing).

(Here is the documentation (bitwise-and ...))

, , , ?

N.B: Scheme. , (), .

+6

, .

(define (pow2? x)
  (= (bitwise-and x (- x 1))
     0))
+3

The circuit also has bitwise operators .

But if you really want to develop your skills in the circuit, you should write a function that decides whether the integer is a power of 2, recursively dividing it by 2 until you are left with either 2 or an odd number. That would be very inefficient, but still great.

+1
source

Source: https://habr.com/ru/post/1721897/


All Articles