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

#1

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

#2

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?

#3

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 })

If it doesn’t answer your question, please comment.

#4

Hello @premila.ande

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