Skip to content

Instantly share code, notes, and snippets.

@aprescott
Created May 7, 2011 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aprescott/960903 to your computer and use it in GitHub Desktop.
Save aprescott/960903 to your computer and use it in GitHub Desktop.
Find the lowest multiple of some number greater than or equal to some other number.
def foo(n, m)
return n if n % m == 0
n + m - (n % m)
end
foo(25, 7) #=> 28
foo(28, 7) #=> 28
foo(29, 7) #=> 35
# No branching.
def bar(n, m)
n + (m - n % m) % m
end
bar(25, 7) #=> 28
bar(28, 7) #=> 28
bar(29, 7) #=> 35
require "benchmark"
# ruby 1.9.2p180 (2011-02-18 revision 30909) [i686-linux]
Benchmark.realtime { 1_000_000.times { foo(25, 7) } } #=> 0.4824531078338623
Benchmark.realtime { 1_000_000.times { bar(25, 7) } } #=> 0.42949914932250977
Benchmark.realtime { 1_000_000.times { foo(28, 7) } } #=> 0.3901078701019287
Benchmark.realtime { 1_000_000.times { bar(28, 7) } } #=> 0.43618083000183105
Benchmark.realtime { 1_000_000.times { foo(29, 7) } } #=> 0.4811720848083496
Benchmark.realtime { 1_000_000.times { bar(29, 7) } } #=> 0.43199920654296875
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment