The shift operator comes in handy and can save a lot of time. These are equivalent operations: >time ruby -e '1_000_000.times { || 2**31 }' real 0m33.225s user 0m32.452s sys 0m0.015s >time ruby -e '1_000_000.times { || 1<<31 }' real 0m3.469s user 0m3.421s sys 0m0.000s >time ruby -e '1_000_000.times { || 2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2 }' real 0m13.839s user 0m13.656s sys 0m0.015s Kero wrote: >>Tristan's solution makes use of bit operations, because they tend to be faster >>than multiplication and division. All you need to know about these is that n << >>1 == n * 2 and n >> 1 == n / 2. > > > Are they really faster? Ruby bits are not directly in CPU registers. > > My rule of thumb is that every method call in Ruby takes a huge amount of > time, whether it is a bitshift or a multiplication (or even a regexp check). > For the record, I did a quick test: > > kero@pc67140460:~/tmp$ time ruby -e '1_000_000.times { |i| i << 1 }' > real 0m2.683s > user 0m1.970s > sys 0m0.710s > kero@pc67140460:~/tmp$ time ruby -e '1_000_000.times { |i| i << 1 }' > real 0m2.687s > user 0m1.880s > sys 0m0.810s > kero@pc67140460:~/tmp$ time ruby -e '1_000_000.times { |i| i * 2 }' > real 0m2.684s > user 0m2.080s > sys 0m0.600s > kero@pc67140460:~/tmp$ time ruby -e '1_000_000.times { |i| i * 2 }' > real 0m2.689s > user 0m2.060s > sys 0m0.640s > > No significant differences whatsoever. > > Bye, > Kero. > > PS: fun quiz, but that should be clear with all my postings :)