binary_exponentiation.sf 392 B

1234567891011121314151617181920
  1. #!/usr/bin/ruby
  2. # Generic implementation of the Binary Exponentiation algorithm.
  3. # See also:
  4. # https://en.wikipedia.org/wiki/Exponentiation_by_squaring
  5. func binary_exp(r,x,n,f) {
  6. for bit in (n.as_bin.flip.chars) {
  7. r = f(x, r) if bit
  8. x = f(x, x)
  9. }
  10. return r
  11. }
  12. say binary_exp(1, 3, 42, {|a,b| a * b }) # 3^42
  13. say binary_exp(0, 3, 42, {|a,b| a + b }) # 3*42