372.super-pow.go 827 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. func superPow(a int, b []int) int { // Recurse
  2. n := len(b)
  3. if n == 0 {
  4. return 1
  5. }
  6. return modPow(superPow(a, b[:n-1]), 10) * modPow(a, b[n-1]) % 1337
  7. }
  8. func modPow(a, b int) (pow int) {
  9. pow, a = 1, a%1337
  10. for b != 0 {
  11. if b&1 == 1 {
  12. pow = pow * a % 1337
  13. }
  14. b >>= 1
  15. a = a * a % 1337
  16. }
  17. return
  18. }
  19. func superPowFP(a int, b []int) int { // Fast power
  20. pow, n, hi := 1, len(b), 0
  21. a %= 1337
  22. for !eq0(b, hi) {
  23. if b[n-1]&1 == 1 {
  24. pow = pow * a % 1337
  25. }
  26. div2(b, &hi)
  27. a = a * a % 1337
  28. }
  29. return pow
  30. }
  31. func eq0(bn []int, hi int) bool {
  32. for i := len(bn) - 1; hi <= i; i-- {
  33. if bn[i] != 0 {
  34. return false
  35. }
  36. }
  37. return true
  38. }
  39. func div2(bn []int, hi *int) {
  40. i := *hi
  41. if bn[*hi] == 1 {
  42. (*hi)++
  43. }
  44. n := len(bn)
  45. for rem := 0; i < n; i++ {
  46. num := bn[i] + rem*10
  47. bn[i], rem = num>>1, num&1
  48. }
  49. }