Velocity Reviews > Ruby > The while loop for calculating a power of a number less than another number?

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

Erik the Red
Guest
Posts: n/a

 07-29-2005
http://www.math.umd.edu/~dcarrera/ru..._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?

Brian Schröder
Guest
Posts: n/a

 07-29-2005
On 29/07/05, Erik the Red <(E-Mail Removed)> wrote:
> http://www.math.umd.edu/~dcarrera/ru..._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

Regards,

Brian

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

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

Kevin
Guest
Posts: n/a

 07-29-2005
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

Brian Schröder
Guest
Posts: n/a

 07-29-2005
On 29/07/05, Kevin <(E-Mail Removed)> wrote:
> this is odd since you don't need to loop to find the answer
>=20
> maxnum =3D 10_000
>=20
> n =3D 2 ** (Math.log(maxnum) / Math.log(2)).floor
>=20
> puts n + " is the largest power of 2 less than " + maxnum
>=20
>=20
>=20

I'd think it was a educative example?

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

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

Chris Pine
Guest
Posts: n/a

 07-29-2005
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