From 0780e4b8ce1e1c6b65f04379253f145e9f557470 Mon Sep 17 00:00:00 2001 From: ridwanfathin Date: Thu, 8 Oct 2020 09:57:02 +0700 Subject: [PATCH] add fast pow: O(log n) exponent --- numerical/fast_pow.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 numerical/fast_pow.go diff --git a/numerical/fast_pow.go b/numerical/fast_pow.go new file mode 100644 index 0000000..1073c42 --- /dev/null +++ b/numerical/fast_pow.go @@ -0,0 +1,16 @@ +package numerical + +//O(log n) function for pow(x, y) +func FastPow(n uint, power uint) uint { + var res uint = 1 + for power > 0 { + + if (power & 1) != 0 { + res = res * n + } + + power = power >> 1 + n = n * n + } + return res +}