views:

380

answers:

3

I'm fairly new to Scheme and am attempting to learn it on my own from scratch. I'm stuck on the syntax of this problem. I know that if I want to find out if a number is a power of 2, in C for instance, I would simply do:

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

which would return true or false. How would I be able to convert this into a couple simple lines in Scheme?

+6  A: 

I'll give you a hint since you're trying to learn the language.

Scheme has a function called (bitwise-and ...) which is equivalent to the & operator in C (there is also (bitwise-xor ...), (bitwise-not ..), etc., which do the expected thing).

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

Given that, would you be able to translate what you've written in your question into Scheme code?

N.B: For a problem like this, you really don't need to resort to bitwise operations when using Scheme. Realistically, you should be writing a (possibly probably tail) recursive function that will compute this for you.

Andrew Song
I see that the code was written out as an answer here after I posted. Oh well.
Andrew Song
I saw this first before I refreshed the page and saw the rest, and it did help, so thanks anyways!
Evan Parker
+1  A: 

Scheme also has biwise operators.

But if you really want to develop your scheme skills, you should write a function that decides if an integer is a power of 2 by recursively dividing it by 2 until you are left with either 2 or with an odd number. This would be very inefficient, but really cool nonetheless.

Dima
Long, but very cool nonetheless
Evan Parker
It would be shorter if I wrote it in Scheme, but that would have deprived you of the joy of coding it yourself.
Dima
+3  A: 

You can do this using a built in bitwise operator.

(define (pow2? x)
  (= (bitwise-and x (- x 1))
     0))
Bill the Lizard
(You should probably name the function `(pow2? ..)` rather than `(pow2 ..)` since they imply different things.
Andrew Song
The name should be pow2? , because it is a predicate.
Dima
@Andrew, @Dima: I'm also fairly new to Scheme, so I wasn't aware of this convention. I fixed my code. Thanks.
Bill the Lizard
This makes sense. Since the bitwise operator is built in, do I not need to import any libraries in order for it to leave me alone about errors?
Evan Parker
@Evan: I don't know if it's built in to every Scheme. I'm using DrScheme with the language set to Module and not getting any errors or warnings.
Bill the Lizard
Depends. Different scheme implementations have very annoying subtle differences. Try it out.
Dima
The math jargon for “power of two” is “impolite number.”
Cirno de Bergerac
sgm, "politeness" refers to the property of a number of being able to be represented by a sum of consecutive integers; it just happens that impolite numbers and powers of two are the same set.
Svante