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

Discussion in 'Ruby' started by Erik the Red, Jul 29, 2005.

1. ### Erik the RedGuest

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?

Erik the Red, Jul 29, 2005

2. ### Brian SchröderGuest

[email protected]:~/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]
[email protected]:~/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

Regards,

Brian

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

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

Brian Schröder, Jul 29, 2005

3. ### KevinGuest

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

Kevin, Jul 29, 2005
4. ### Brian SchröderGuest

I'd think it was a educative example?

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

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

Brian Schröder, Jul 29, 2005
5. ### Chris PineGuest

Well, if you are interested in another tutorial which is more
up-to-date, try mine out:

http://pine.fm/LearnToProgram

(He used some of my examples in his tutorial, but not that one!)

Chris

Chris Pine, Jul 29, 2005