File: ipow.go

package info (click to toggle)
golang-github-dop251-goja 0.0~git20250630.0.58d95d8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,264 kB
  • sloc: javascript: 454; perl: 184; makefile: 6; sh: 1
file content (98 lines) | stat: -rw-r--r-- 1,428 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package goja

// inspired by https://gist.github.com/orlp/3551590

var overflows = [64]int64{
	9223372036854775807, 9223372036854775807, 3037000499, 2097151,
	55108, 6208, 1448, 511,
	234, 127, 78, 52,
	38, 28, 22, 18,
	15, 13, 11, 9,
	8, 7, 7, 6,
	6, 5, 5, 5,
	4, 4, 4, 4,
	3, 3, 3, 3,
	3, 3, 3, 3,
	2, 2, 2, 2,
	2, 2, 2, 2,
	2, 2, 2, 2,
	2, 2, 2, 2,
	2, 2, 2, 2,
	2, 2, 2, 2,
}

var highestBitSet = [63]byte{
	0, 1, 2, 2, 3, 3, 3, 3,
	4, 4, 4, 4, 4, 4, 4, 4,
	5, 5, 5, 5, 5, 5, 5, 5,
	5, 5, 5, 5, 5, 5, 5, 5,
	6, 6, 6, 6, 6, 6, 6, 6,
	6, 6, 6, 6, 6, 6, 6, 6,
	6, 6, 6, 6, 6, 6, 6, 6,
	6, 6, 6, 6, 6, 6, 6,
}

func ipow(base, exp int64) (result int64) {
	if exp >= 63 {
		if base == 1 {
			return 1
		}

		if base == -1 {
			return 1 - 2*(exp&1)
		}

		return 0
	}

	if base > overflows[exp] || -base > overflows[exp] {
		return 0
	}

	result = 1

	switch highestBitSet[byte(exp)] {
	case 6:
		if exp&1 != 0 {
			result *= base
		}
		exp >>= 1
		base *= base
		fallthrough
	case 5:
		if exp&1 != 0 {
			result *= base
		}
		exp >>= 1
		base *= base
		fallthrough
	case 4:
		if exp&1 != 0 {
			result *= base
		}
		exp >>= 1
		base *= base
		fallthrough
	case 3:
		if exp&1 != 0 {
			result *= base
		}
		exp >>= 1
		base *= base
		fallthrough
	case 2:
		if exp&1 != 0 {
			result *= base
		}
		exp >>= 1
		base *= base
		fallthrough
	case 1:
		if exp&1 != 0 {
			result *= base
		}
		fallthrough
	default:
		return result
	}
}