The while loop for calculating a power of a number less than another number?

E

Erik the Red

http://www.math.umd.edu/~dcarrera/ruby/0.3/chp_02/while.html

The code is as follows:

number = 1
while number < 10_000
number *= 2
end

number /= 2

puts number.to_s + " is the highest " +\ "power of 2 less than 10,000"

I don't quite understand this, especially since:

a. His program output is clearly not correct. 16 384 is greater than 10
000.

b. His comments don't make sense.

What does this code do exactly?
 
B

Brian Schröder

http://www.math.umd.edu/~dcarrera/ruby/0.3/chp_02/while.html
=20
The code is as follows:
=20
number =3D 1
while number < 10_000
number *=3D 2
end
=20
number /=3D 2
=20
puts number.to_s + " is the highest " +\ "power of 2 less than 10,000"
=20
I don't quite understand this, especially since:
=20
a. His program output is clearly not correct. 16 384 is greater than 10
000.
=20
b. His comments don't make sense.
=20
What does this code do exactly?

bschroed@black:~/svn/projekte/ruby-things$ cat power2.rb=20
max =3D 10_000
number =3D 1
while number < max
number *=3D 2
end

number /=3D 2

puts "%i^2 < %i" % [number, max]
bschroed@black:~/svn/projekte/ruby-things$ ruby power2.rb=20
8192^2 < 10000

Are you sure you used the right code? Seems like you forgot the
division by 2 at the end.

Try to print ot the value of number after each step, maybe that will
help your understanding.

Regards,

Brian



--=20
http://ruby.brian-schroeder.de/

Stringed instrument chords: http://chordlist.brian-schroeder.de/
 
K

Kevin

this is odd since you don't need to loop to find the answer

maxnum = 10_000

n = 2 ** (Math.log(maxnum) / Math.log(2)).floor

puts n + " is the largest power of 2 less than " + maxnum
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top