UNPKG

1.02 kBtext/coffeescriptView Raw
1#-----------------------------------------------------------------------------
2#
3# Bignum root
4#
5# Returns null pointer if not perfect root.
6#
7# The sign of the radicand is ignored.
8#
9#-----------------------------------------------------------------------------
10
11
12mroot = (n, index) ->
13 # this doesn't quite work
14 #return n.pow(1/index + 0.0000000000000001)
15
16 # sign of radicand ignored
17 n = n.abs()
18
19 i = 0
20 j = 0
21 k = 0
22
23 if (index == 0)
24 stop("root index is zero")
25
26 # count number of bits
27 k = 0
28 while n.shiftRight(k) > 0
29 k++
30
31 if (k == 0)
32 return mint(0)
33
34 # initial guess
35
36 k = Math.floor((k - 1) / index)
37
38 j = Math.floor(k / 32 + 1)
39 x = bigInt(j)
40
41 for i in [0...j]
42 # zero-out the ith bit
43 x = x.and(bigInt(1).shiftLeft(i).not())
44
45 while (k >= 0)
46 # set the kth bit
47 x = x.or(bigInt(1).shiftLeft(k))
48
49 y = mpow(x, index)
50 switch (mcmp(y, n))
51 when 0
52 return x
53 when 1
54 #mp_clr_bit(x, k)
55 # clear the kth bit
56 x = x.and(bigInt(1).shiftLeft(k).not())
57 k--
58
59 return 0
60
61
62#if SELFTEST
63