Exemplo n.º 1
0
// ProbablyPrimeBigInt returns true if n is prime or n is a pseudoprime to base
// a. It implements the Miller-Rabin primality test for one specific value of
// 'a' and k == 1.  See also ProbablyPrimeUint32.
func ProbablyPrimeBigInt(n, a *big.Int) bool {
	var d big.Int
	d.Set(n)
	d.Sub(&d, _1) // d <- n-1
	s := 0
	for ; d.Bit(s) == 0; s++ {
	}
	nMinus1 := big.NewInt(0).Set(&d)
	d.Rsh(&d, uint(s))

	x := ModPowBigInt(a, &d, n)
	if x.Cmp(_1) == 0 || x.Cmp(nMinus1) == 0 {
		return true
	}

	for ; s > 1; s-- {
		if x = x.Mod(x.Mul(x, x), n); x.Cmp(_1) == 0 {
			return false
		}

		if x.Cmp(nMinus1) == 0 {
			return true
		}
	}
	return false
}
func factor(n *big.Int) (pf []pExp) {
	var e int64
	for ; n.Bit(int(e)) == 0; e++ {
	}
	if e > 0 {
		n.Rsh(n, uint(e))
		pf = []pExp{{big.NewInt(2), e}}
	}
	s := sqrt(n)
	q, r := new(big.Int), new(big.Int)
	for d := big.NewInt(3); n.Cmp(one) > 0; d.Add(d, two) {
		if d.Cmp(s) > 0 {
			d.Set(n)
		}
		for e = 0; ; e++ {
			q.QuoRem(n, d, r)
			if r.BitLen() > 0 {
				break
			}
			n.Set(q)
		}
		if e > 0 {
			pf = append(pf, pExp{new(big.Int).Set(d), e})
			s = sqrt(n)
		}
	}
	return
}
Exemplo n.º 3
0
func (c *Curve) add(p1x, p1y, p2x, p2y *big.Int) {
	if p1x.Cmp(p2x) == 0 && p1y.Cmp(p2y) == 0 {
		// double
		c.t.Mul(p1x, p1x)
		c.t.Mul(c.t, bigInt3)
		c.t.Add(c.t, c.A)
		c.tx.Mul(bigInt2, p1y)
		c.tx.ModInverse(c.tx, c.P)
		c.t.Mul(c.t, c.tx)
		c.t.Mod(c.t, c.P)
	} else {
		c.tx.Sub(p2x, p1x)
		c.tx.Mod(c.tx, c.P)
		c.pos(c.tx)
		c.ty.Sub(p2y, p1y)
		c.ty.Mod(c.ty, c.P)
		c.pos(c.ty)
		c.t.ModInverse(c.tx, c.P)
		c.t.Mul(c.t, c.ty)
		c.t.Mod(c.t, c.P)
	}
	c.tx.Mul(c.t, c.t)
	c.tx.Sub(c.tx, p1x)
	c.tx.Sub(c.tx, p2x)
	c.tx.Mod(c.tx, c.P)
	c.pos(c.tx)
	c.ty.Sub(p1x, c.tx)
	c.ty.Mul(c.ty, c.t)
	c.ty.Sub(c.ty, p1y)
	c.ty.Mod(c.ty, c.P)
	c.pos(c.ty)
	p1x.Set(c.tx)
	p1y.Set(c.ty)
}
Exemplo n.º 4
0
func calcDifficultyFrontier(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
	diff := new(big.Int)
	adjust := new(big.Int).Div(parentDiff, params.DifficultyBoundDivisor)
	bigTime := new(big.Int)
	bigParentTime := new(big.Int)

	bigTime.SetUint64(time)
	bigParentTime.SetUint64(parentTime)

	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
		diff.Add(parentDiff, adjust)
	} else {
		diff.Sub(parentDiff, adjust)
	}
	if diff.Cmp(params.MinimumDifficulty) < 0 {
		diff.Set(params.MinimumDifficulty)
	}

	periodCount := new(big.Int).Add(parentNumber, common.Big1)
	periodCount.Div(periodCount, ExpDiffPeriod)
	if periodCount.Cmp(common.Big1) > 0 {
		// diff = diff + 2^(periodCount - 2)
		expDiff := periodCount.Sub(periodCount, common.Big2)
		expDiff.Exp(common.Big2, expDiff, nil)
		diff.Add(diff, expDiff)
		diff = common.BigMax(diff, params.MinimumDifficulty)
	}

	return diff
}
Exemplo n.º 5
0
// ToBase produces n in base b. For example
//
// 	ToBase(2047, 22) -> [1, 5, 4]
//
//	1 * 22^0           1
//	5 * 22^1         110
//	4 * 22^2        1936
//	                ----
//	                2047
//
// ToBase panics for bases < 2.
func ToBase(n *big.Int, b int) []int {
	var nn big.Int
	nn.Set(n)
	if b < 2 {
		panic("invalid base")
	}

	k := 1
	switch nn.Sign() {
	case -1:
		nn.Neg(&nn)
		k = -1
	case 0:
		return []int{0}
	}

	bb := big.NewInt(int64(b))
	var r []int
	rem := big.NewInt(0)
	for nn.Sign() != 0 {
		nn.QuoRem(&nn, bb, rem)
		r = append(r, k*int(rem.Int64()))
	}
	return r
}
Exemplo n.º 6
0
Arquivo: graph.go Projeto: rsc/tmp
func ratProb(mode int) func(*big.Rat) *big.Rat {
	return func(x *big.Rat) *big.Rat {
		lo := big.NewInt(0)
		hi := new(big.Int).Set(big2p63)
		n := 0
		for lo.Cmp(hi) != 0 {
			m := new(big.Int).Add(lo, hi)
			m = m.Rsh(m, 1)
			if n++; n > 100 {
				fmt.Printf("??? %v %v %v\n", lo, hi, m)
				break
			}
			v := new(big.Rat).SetFrac(m, big2p63)
			f, _ := v.Float64()
			v.SetFloat64(f)
			if v.Cmp(x) < 0 {
				lo.Add(m, bigOne)
			} else {
				hi.Set(m)
			}
		}
		switch mode {
		default: // case 0
			return new(big.Rat).SetFrac(lo, big2p63)
		case 1:
			if lo.Cmp(big.NewInt(cutoff1)) <= 0 {
				lo.Add(lo, big.NewInt(1<<63-cutoff1))
			}
			return new(big.Rat).SetFrac(lo, big2p63)
		case 2:
			return new(big.Rat).SetFrac(lo, big.NewInt(cutoff1))
		}
	}
}
Exemplo n.º 7
0
// String returns a float string representation of a Decimal
func (d Decimal) String() string {
	// Retrieve a copy of the Decimal's internal big.Rat denominator
	denom := new(big.Int)
	denom.Set(d.rational.Denom())
	// Discover the precision of the denominator and use it to fix
	// the precision of the string conversion
	var precision = 0
	one := big.NewInt(1)
	ten := big.NewInt(10)
	for denom.Cmp(one) > 0 {
		denom = denom.Div(denom, ten)
		precision++
	}

	if !d.finite {
		if d.rational.Sign() == 1 {
			return "Infinity"
		} else if d.rational.Sign() == -1 {
			return "-Infinity"
		} else {
			return "NaN"
		}
	}

	return d.rational.FloatString(precision)
}
Exemplo n.º 8
0
// CalcGasLimit computes the gas limit of the next block after parent.
// The result may be modified by the caller.
// This is miner strategy, not consensus protocol.
func CalcGasLimit(parent *types.Block) *big.Int {
	// contrib = (parentGasUsed * 3 / 2) / 1024
	contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
	contrib = contrib.Div(contrib, big.NewInt(2))
	contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)

	// decay = parentGasLimit / 1024 -1
	decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
	decay.Sub(decay, big.NewInt(1))

	/*
		strategy: gasLimit of block-to-mine is set based on parent's
		gasUsed value.  if parentGasUsed > parentGasLimit * (2/3) then we
		increase it, otherwise lower it (or leave it unchanged if it's right
		at that usage) the amount increased/decreased depends on how far away
		from parentGasLimit * (2/3) parentGasUsed is.
	*/
	gl := new(big.Int).Sub(parent.GasLimit(), decay)
	gl = gl.Add(gl, contrib)
	gl.Set(common.BigMax(gl, params.MinGasLimit))

	// however, if we're now below the target (TargetGasLimit) we increase the
	// limit as much as we can (parentGasLimit / 1024 -1)
	if gl.Cmp(params.TargetGasLimit) < 0 {
		gl.Add(parent.GasLimit(), decay)
		gl.Set(common.BigMin(gl, params.TargetGasLimit))
	}
	return gl
}
Exemplo n.º 9
0
func (i BigInt) floatString(verb byte, prec int) string {
	switch verb {
	case 'f', 'F':
		str := fmt.Sprintf("%d", i.Int)
		if prec > 0 {
			str += "." + zeros(prec)
		}
		return str
	case 'e', 'E':
		// The exponent will alway be >= 0.
		sign := ""
		var x big.Int
		x.Set(i.Int)
		if x.Sign() < 0 {
			sign = "-"
			x.Neg(&x)
		}
		return eFormat(verb, prec, sign, x.String(), eExponent(&x))
	case 'g', 'G':
		// Exponent is always positive so it's easy.
		var x big.Int
		x.Set(i.Int)
		if eExponent(&x) >= prec {
			// Use e format.
			verb -= 2 // g becomes e.
			return trimEZeros(verb, i.floatString(verb, prec-1))
		}
		// Use f format, but this is just an integer.
		return fmt.Sprintf("%d", i.Int)
	default:
		Errorf("can't handle verb %c for big int", verb)
	}
	return ""
}
Exemplo n.º 10
0
func split(number *big.Int, available, needed int) []Share {
	coef := make([]*big.Int, 0)
	shares := make([]Share, 0)

	coef = append(coef, number)

	rand.Seed(time.Now().Unix())
	for i := 1; i < needed; i++ {

		c := big.NewInt(rand.Int63())
		coef = append(coef, c)
	}

	for x := 1; x <= available; x++ {
		accum := new(big.Int)
		accum.Set(coef[0])
		for exp := 1; exp < needed; exp++ {
			p := math.Pow(float64(x), float64(exp))
			w := big.NewInt(int64(p))

			r := new(big.Int)
			r.Mul(coef[exp], w)

			accum.Add(accum, r)
		}

		s := new(big.Int)
		s.Set(accum)
		share := Share{Part: s, ID: int64(x)}
		shares = append(shares, share)
	}

	return shares
}
Exemplo n.º 11
0
/* calcDiff returns a bool given two block headers.  This bool is
true if the correct dificulty adjustment is seen in the "next" header.
Only feed it headers n-2016 and n-1, otherwise it will calculate a difficulty
when no adjustment should take place, and return false.
Note that the epoch is actually 2015 blocks long, which is confusing. */
func calcDiffAdjust(start, end wire.BlockHeader, p *chaincfg.Params) uint32 {
	duration := end.Timestamp.UnixNano() - start.Timestamp.UnixNano()
	if duration < minRetargetTimespan {
		log.Printf("whoa there, block %s off-scale high 4X diff adjustment!",
			end.BlockSha().String())
		duration = minRetargetTimespan
	} else if duration > maxRetargetTimespan {
		log.Printf("Uh-oh! block %s off-scale low 0.25X diff adjustment!\n",
			end.BlockSha().String())
		duration = maxRetargetTimespan
	}

	// calculation of new 32-byte difficulty target
	// first turn the previous target into a big int
	prevTarget := blockchain.CompactToBig(start.Bits)
	// new target is old * duration...
	newTarget := new(big.Int).Mul(prevTarget, big.NewInt(duration))
	// divided by 2 weeks
	newTarget.Div(newTarget, big.NewInt(int64(targetTimespan)))

	// clip again if above minimum target (too easy)
	if newTarget.Cmp(p.PowLimit) > 0 {
		newTarget.Set(p.PowLimit)
	}

	// calculate and return 4-byte 'bits' difficulty from 32-byte target
	return blockchain.BigToCompact(newTarget)
}
Exemplo n.º 12
0
// Ported to math/big.Int from github.com/dustin/go-humanize
func Comma(v *big.Int) string {
	{
		var copy big.Int
		copy.Set(v)
		v = &copy
	}
	sign := ""
	if v.Sign() < 0 {
		sign = "-"
		v.Abs(v)
	}

	tmp := &big.Int{}
	herman := big.NewInt(999)
	thousand := big.NewInt(1000)
	var parts []string

	for v.Cmp(herman) > 0 {
		part := tmp.Mod(v, thousand).String()
		switch len(part) {
		case 2:
			part = "0" + part
		case 1:
			part = "00" + part
		}
		v.Div(v, thousand)
		parts = append(parts, part)
	}
	parts = append(parts, v.String())
	for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
		parts[i], parts[j] = parts[j], parts[i]
	}
	return sign + strings.Join(parts, ",")
}
Exemplo n.º 13
0
// doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and
// returns its double, also in Jacobian form.
func (curve *CurveParams) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) {
	// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
	delta := new(big.Int).Mul(z, z)
	delta.Mod(delta, curve.P)
	gamma := new(big.Int).Mul(y, y)
	gamma.Mod(gamma, curve.P)
	alpha := new(big.Int).Sub(x, delta)
	if alpha.Sign() == -1 {
		alpha.Add(alpha, curve.P)
	}
	alpha2 := new(big.Int).Add(x, delta)
	alpha.Mul(alpha, alpha2)
	alpha2.Set(alpha)
	alpha.Lsh(alpha, 1)
	alpha.Add(alpha, alpha2)

	beta := alpha2.Mul(x, gamma)

	x3 := new(big.Int).Mul(alpha, alpha)
	beta8 := new(big.Int).Lsh(beta, 3)
	x3.Sub(x3, beta8)
	for x3.Sign() == -1 {
		x3.Add(x3, curve.P)
	}
	x3.Mod(x3, curve.P)

	z3 := new(big.Int).Add(y, z)
	z3.Mul(z3, z3)
	z3.Sub(z3, gamma)
	if z3.Sign() == -1 {
		z3.Add(z3, curve.P)
	}
	z3.Sub(z3, delta)
	if z3.Sign() == -1 {
		z3.Add(z3, curve.P)
	}
	z3.Mod(z3, curve.P)

	beta.Lsh(beta, 2)
	beta.Sub(beta, x3)
	if beta.Sign() == -1 {
		beta.Add(beta, curve.P)
	}
	y3 := alpha.Mul(alpha, beta)

	gamma.Mul(gamma, gamma)
	gamma.Lsh(gamma, 3)
	gamma.Mod(gamma, curve.P)

	y3.Sub(y3, gamma)
	if y3.Sign() == -1 {
		y3.Add(y3, curve.P)
	}
	y3.Mod(y3, curve.P)

	return x3, y3, z3
}
Exemplo n.º 14
0
func times(z *big.Int, x *big.Int, y *big.Int) *big.Int {
	var lim, x1, y1 big.Int
	lim.Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
	x1.Set(x)
	y1.Set(y)
	z.Mul(x, y)
	z.Mod(z, &lim)
	return z
}
Exemplo n.º 15
0
// JacobiSymbol returns the jacobi symbol ( N / D ) of
// N (numerator) over D (denominator).
// See http://en.wikipedia.org/wiki/Jacobi_symbol
func JacobiSymbol(N *big.Int, D *big.Int) int {
	//Step 0: parse input / easy cases
	if D.Sign() <= 0 || D.Bit(0) == 0 {
		// we will assume D is positive
		// wolfram is ok with negative denominator
		// im not sure what is standard though
		panic("JacobiSymbol defined for positive odd denominator only")
	}
	var n, d, tmp big.Int
	n.Set(N)
	d.Set(D)
	j := 1
	for {
		// Step 1: Reduce the numerator mod the denominator
		n.Mod(&n, &d)
		if n.Sign() == 0 {
			// if n,d not relatively prime
			return 0
		}
		if len(n.Bits()) >= len(d.Bits())-1 {
			// n > d/2 so swap n with d-n
			// and multiply j by JacobiSymbol(-1 / d)
			n.Sub(&d, &n)
			if d.Bits()[0]&3 == 3 {
				// if d = 3 mod 4
				j = -1 * j
			}
		}

		// Step 2: extract factors of 2
		s := trailingZeroBits(&n)
		n.Rsh(&n, s)
		if s&1 == 1 {
			switch d.Bits()[0] & 7 {
			case 3, 5: // d = 3,5 mod 8
				j = -1 * j
			}
		}

		// Step 3: check numerator
		if len(n.Bits()) == 1 && n.Bits()[0] == 1 {
			// if n = 1 were done
			return j
		}

		// Step 4: flip and go back to step 1
		if n.Bits()[0]&3 != 1 { // n = 3 mod 4
			if d.Bits()[0]&3 != 1 { // d = 3 mod 4
				j = -1 * j
			}
		}
		tmp.Set(&n)
		n.Set(&d)
		d.Set(&tmp)
	}
}
Exemplo n.º 16
0
// Set z to one of the square roots of a modulo p if a square root exists.
// The modulus p must be an odd prime.
// Returns true on success, false if input a is not a square modulo p.
func Sqrt(z *big.Int, a *big.Int, p *big.Int) bool {

	if a.Sign() == 0 {
		z.SetInt64(0) // sqrt(0) = 0
		return true
	}
	if Jacobi(a, p) != 1 {
		return false // a is not a square mod M
	}

	// Break p-1 into s*2^e such that s is odd.
	var s big.Int
	var e int
	s.Sub(p, one)
	for s.Bit(0) == 0 {
		s.Div(&s, two)
		e++
	}

	// Find some non-square n
	var n big.Int
	n.SetInt64(2)
	for Jacobi(&n, p) != -1 {
		n.Add(&n, one)
	}

	// Heart of the Tonelli-Shanks algorithm.
	// Follows the description in
	// "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra Brown.
	var x, b, g, t big.Int
	x.Add(&s, one).Div(&x, two).Exp(a, &x, p)
	b.Exp(a, &s, p)
	g.Exp(&n, &s, p)
	r := e
	for {
		// Find the least m such that ord_p(b) = 2^m
		var m int
		t.Set(&b)
		for t.Cmp(one) != 0 {
			t.Exp(&t, two, p)
			m++
		}

		if m == 0 {
			z.Set(&x)
			return true
		}

		t.SetInt64(0).SetBit(&t, r-m-1, 1).Exp(&g, &t, p)
		// t = g^(2^(r-m-1)) mod p
		g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p
		x.Mul(&x, &t).Mod(&x, p)
		b.Mul(&b, &g).Mod(&b, p)
		r = m
	}
}
Exemplo n.º 17
0
func BigFibonacci(term int) *big.Int {
	n := new(big.Int).SetInt64(int64(1))
	n_1 := new(big.Int).SetInt64(int64(1))
	n_2 := new(big.Int).SetInt64(int64(1))
	for i := 3; i <= term; i++ {
		n.Add(n_1, n_2)
		n_2.Set(n_1)
		n_1.Set(n)
	}
	return n_1
}
func sqrt(n *big.Int) *big.Int {
	a := new(big.Int)
	for b := new(big.Int).Set(n); ; {
		a.Set(b)
		b.Rsh(b.Add(b.Quo(n, a), a), 1)
		if b.Cmp(a) >= 0 {
			return a
		}
	}
	return a.SetInt64(0)
}
Exemplo n.º 19
0
// PowerizeBigInt returns (e, p) such that e is the smallest number for which p
// == b^e is greater or equal n. For n < 0 or b < 2 (0, nil) is returned.
//
// NOTE: Run time for large values of n (above about 2^1e6 ~= 1e300000) can be
// significant and/or unacceptabe.  For any smaller values of n the function
// typically performs in sub second time.  For "small" values of n (cca bellow
// 2^1e3 ~= 1e300) the same can be easily below 10 µs.
//
// A special (and trivial) case of b == 2 is handled separately and performs
// much faster.
func PowerizeBigInt(b, n *big.Int) (e uint32, p *big.Int) {
	switch {
	case b.Cmp(_2) < 0 || n.Sign() < 0:
		return
	case n.Sign() == 0 || n.Cmp(_1) == 0:
		return 0, big.NewInt(1)
	case b.Cmp(_2) == 0: //TODO actually all powers of 2 should use the short path
		p = big.NewInt(0)
		e = uint32(n.BitLen() - 1)
		p.SetBit(p, int(e), 1)
		if p.Cmp(n) < 0 {
			p.Mul(p, _2)
			e++
		}
		return
	}

	bw := b.BitLen()
	nw := n.BitLen()
	p = big.NewInt(1)
	var bb, r big.Int
	for {
		switch p.Cmp(n) {
		case -1:
			x := uint32((nw - p.BitLen()) / bw)
			if x == 0 {
				x = 1
			}
			e += x
			switch x {
			case 1:
				p.Mul(p, b)
			default:
				r.Set(_1)
				bb.Set(b)
				e := x
				for {
					if e&1 != 0 {
						r.Mul(&r, &bb)
					}
					if e >>= 1; e == 0 {
						break
					}

					bb.Mul(&bb, &bb)
				}
				p.Mul(p, &r)
			}
		case 0, 1:
			return
		}
	}
	panic("unreachable")
}
Exemplo n.º 20
0
func makeFibGen() fibGen {
	a := big.NewInt(0)
	b := big.NewInt(1)
	var c big.Int

	return func() *big.Int {
		c.Set(b)
		b.Add(a, b)
		return a.Set(&c)
	}
}
Exemplo n.º 21
0
Arquivo: const.go Projeto: spate/llgo
func unaryIntOp(x *big.Int, op token.Token) interface{} {
	var z big.Int
	switch op {
	case token.ADD:
		return z.Set(x)
	case token.SUB:
		return z.Neg(x)
	case token.XOR:
		return z.Not(x)
	}
	panic("unreachable")
}
Exemplo n.º 22
0
// Set z to x, but with the bit-field from bit i
// up or down to bit j filled with bit value b.
func BitFill(z, x *big.Int, i, j int, b uint) {
	if z != x {
		z.Set(x)
	}
	inc := 1
	if i > j {
		inc = -1
	}
	for ; i != j; i += inc {
		z.SetBit(z, i, b)
	}
}
Exemplo n.º 23
0
func spawner(pos_prime, sqrt *big.Int, tf chan bool) {
	base := new(big.Int)
	increment := new(big.Int)
	increment.SetInt64(2)

	for base.SetInt64(3); base.Cmp(sqrt) < 0; base.Add(base, increment) {
		temp := new(big.Int)
		temp.Set(base)

		go isPrime(pos_prime, temp, tf)
	}
}
Exemplo n.º 24
0
// TODO: Pass in result, so it can be reused.
func reverse(n *big.Int) (result *big.Int) {
	result = big.NewInt(0)
	var work big.Int
	work.Set(n)
	tmp := big.NewInt(0)

	for work.Cmp(zero) != 0 {
		work.DivMod(&work, ten, tmp)
		result.Mul(result, ten)
		result.Add(result, tmp)
	}
	return
}
Exemplo n.º 25
0
// CmpAddress follows the Cmp() standard protocol and returns:
//
// - -1 If the receiver should sort first because its address is lower than arg
// - 0 if the SockAddr arg equal to the receiving IPv6Addr or the argument is of a
//   different type.
// - 1 If the argument should sort first.
func (ipv6 IPv6Addr) CmpAddress(sa SockAddr) int {
	ipv6b, ok := sa.(IPv6Addr)
	if !ok {
		return sortDeferDecision
	}

	ipv6aBigInt := new(big.Int)
	ipv6aBigInt.Set(ipv6.Address)
	ipv6bBigInt := new(big.Int)
	ipv6bBigInt.Set(ipv6b.Address)

	return ipv6aBigInt.Cmp(ipv6bBigInt)
}
Exemplo n.º 26
0
//intToBase64 makes string from int.
func intToBase64(n *big.Int) string {
	var result string
	and := big.NewInt(0x3f)
	var tmp, nn big.Int
	nn.Set(n)

	for nn.Cmp(big.NewInt(0)) > 0 {
		bit := tmp.And(&nn, and).Uint64()
		result += string(base64en[bit])
		nn.Rsh(&nn, 6)
	}
	return result + string(base64en[0]*byte(86-len(result)))
}
Exemplo n.º 27
0
// IsSquare returns true if N = m^2
// for some positive integer m.
// It uses newtons method and other checks.
func IsSquare(N *big.Int) bool {
	// Step -1: check inputs
	if N.Sign() <= 0 {
		// 0 is a square
		if N.Sign() == 0 {
			return true
		}
		// negative numbers are not
		return false
	}

	// Step 0: Easy case
	if N.BitLen() < 62 { // need padding, 63 is too close to limit
		n := N.Int64()
		a := int64(math.Sqrt(float64(n)))
		if a*a == n {
			return true
		}
		return false
	}

	// Step 1.1: check if it is a square mod small power of 2
	if _, ok := squaresMod128[uint8(N.Uint64())]; !ok {
		return false
	}

	// Setp 1.2: check if it is a square mod a small number
	_z := uint16(new(big.Int).Mod(N, smallSquareMod).Uint64())
	if _, ok := smallSquares[_z]; !ok {
		return false
	}

	// Step 2: run newtons method, see
	// Cohen's book computational alg. number theory
	// Ch. 1, algorithm 1.7.1
	z := new(big.Int)
	x := new(big.Int).Lsh(one, uint(N.BitLen()+2)>>1)
	y := new(big.Int)
	for {
		// Set y = [(x + [N/x])/2]
		y := y.Rsh(z.Add(x, z.Div(N, x)), 1)
		// if y < x, set x to y
		// else return x
		if y.Cmp(x) == -1 {
			x.Set(y)
		} else {
			return z.Mul(x, x).Cmp(N) == 0
		}
	}
}
func Primes(n *big.Int) []*big.Int {
	res := []*big.Int{}
	mod, div := new(big.Int), new(big.Int)
	for i := big.NewInt(2); i.Cmp(n) != 1; {
		div.DivMod(n, i, mod)
		for mod.Cmp(ZERO) == 0 {
			res = append(res, new(big.Int).Set(i))
			n.Set(div)
			div.DivMod(n, i, mod)
		}
		i.Add(i, ONE)
	}
	return res
}
Exemplo n.º 29
0
func digitSum(num *big.Int) (sum int) {
	zero := big.NewInt(0)
	ten := big.NewInt(10)

	var work big.Int
	work.Set(num)

	tmp := big.NewInt(0)

	for work.Cmp(zero) > 0 {
		work.DivMod(&work, ten, tmp)
		sum += int(tmp.Int64())
	}
	return
}
Exemplo n.º 30
0
// SuggestPrice returns the recommended gas price.
func (self *GasPriceOracle) SuggestPrice() *big.Int {
	self.init()
	self.lastBaseMutex.Lock()
	price := new(big.Int).Set(self.lastBase)
	self.lastBaseMutex.Unlock()

	price.Mul(price, big.NewInt(int64(self.eth.GpobaseCorrectionFactor)))
	price.Div(price, big.NewInt(100))
	if price.Cmp(self.minPrice) < 0 {
		price.Set(self.minPrice)
	} else if self.eth.GpoMaxGasPrice != nil && price.Cmp(self.eth.GpoMaxGasPrice) > 0 {
		price.Set(self.eth.GpoMaxGasPrice)
	}
	return price
}