Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding if a number is the power of 2 in Scheme

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?

like image 936
Evan Parker Avatar asked Dec 02 '25 09:12

Evan Parker


1 Answers

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.

like image 176
Andrew Song Avatar answered Dec 04 '25 14:12

Andrew Song



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!