# Looking for power of 2 algorithm in ruby? without using any predefined functions

Can anyone suggest me the best code for power of 2 in ruby without using any predefined functions/ methods …

Hello @premila.ande, welcome!
Sorry, actually I didn’t get what you really meant! I mean can you clarify us a bit so we may give your problem a try?

Hi, didn’t get any reply yet.

Anyways, if you want to create a program that check if a number is the power of 2, then:

``````check = ->(n) { Math.log2(n).then { |x| x.to_i == x } }
a === 16    # => true
a === 32    # => true
a === 63    # => false
``````

Getting power of 2’s up to a given range:

``````print('Enter max range: ') || puts((1..STDIN.gets.to_i).map { |n| 2 ** n })
``````

Hello @premila.ande

you can achieve this using `**`, ie
`4 ** 2` (4 to the power of 2)
`= 16`

You can’t do anything in any computer language without using “predefined functions”. Please clarify. A fast and easy way is to check if all bits other than the most significant bit equal zero: `def pow_of_2?(n); return false if n.zero?; (n.bit_length-1).times.all? { |i| n[i].zero? }; end`. `pow_of_2?(1) #=> true; pow_of_2?(2) #=> true; pow_of_2?(3) #=> false; pow_of_2?(4) #=> true; pow_of_2?(5) #=> false; pow_of_2?(6) #=> false` and so on.

Oh I forgot to add you can you bitshift as well. It’s very very faster compared to **.

But if you need to deal with bigger range, using `<<` instead of `**` will give you a huge speed boost. In the end, it should look like this:

``````print('Enter max range: ') || puts((1..STDIN.gets.to_i).map { |n| 1 << n })
``````

## Benchmarking

[Warning: This program generates big numbers, and will use around 1.5 GiB of RAM. You may reduce the range to 1…10_000 or something like that if you don’t have that much available memory].