Reputation: 45
I'm trying to create a method that takes a number and then puts every number between that and 0 as an exponent to the number 2.
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
This is as far as I've gotten. . .
def powers_of_two(n)
n.map { |x| 2 ** (0..x) }
end
I believe I'm not far off in my attempt.
Upvotes: 1
Views: 144
Reputation: 110725
As we are dealing with powers of 2
, try this bit-shifting method. (I assume the given number n
is non-negative.)
def po2(n)
(0..n).each { |i| puts 1 << i }
end
po2(7)
1
2
4
8
16
32
64
128
See Integer#<< and possibly this tutorial.
One could alternatively create a proc.
po2 = Proc.new { |n| (0..n).each { |i| puts 1 << i } }
#=> #<Proc:0x00007f91a5222bb0 <main>:0>
po2(7)
1
2
4
8
16
32
64
128
Upvotes: 3
Reputation: 114208
You can build an enumerator that generates the numbers via Enumerator.produce
:
powers = Enumerator.produce(1) { |i| i * 2 }
powers.take(5)
#=>[1, 2, 4, 8, 16]
The block generates each number based on the previous one, starting at 1
.
The same works for bit-shifting:
powers = Enumerator.produce(1) { |i| i << 1 }
powers.take(5)
#=>[1, 2, 4, 8, 16]
Upvotes: 4
Reputation: 106972
For example, like this:
def power_of_two(n) = (0..n).each { puts 2 ** _1 }
power_of_two(4)
#=> 1
2
4
8
16
Upvotes: 4