Java Code Examples for java.math.BigInteger#getLowestSetBit()

The following examples show how to use java.math.BigInteger#getLowestSetBit() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jdk-1.7-annotated   File: ECFieldF2m.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates an elliptic curve characteristic 2 finite
 * field which has 2^<code>m</code> elements with
 * polynomial basis.
 * The reduction polynomial for this field is based
 * on <code>rp</code> whose i-th bit correspondes to
 * the i-th coefficient of the reduction polynomial.<p>
 * Note: A valid reduction polynomial is either a
 * trinomial (X^<code>m</code> + X^<code>k</code> + 1
 * with <code>m</code> > <code>k</code> >= 1) or a
 * pentanomial (X^<code>m</code> + X^<code>k3</code>
 * + X^<code>k2</code> + X^<code>k1</code> + 1 with
 * <code>m</code> > <code>k3</code> > <code>k2</code>
 * > <code>k1</code> >= 1).
 * @param m with 2^<code>m</code> being the number of elements.
 * @param rp the BigInteger whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.
 * @exception NullPointerException if <code>rp</code> is null.
 * @exception IllegalArgumentException if <code>m</code>
 * is not positive, or <code>rp</code> does not represent
 * a valid reduction polynomial.
 */
public ECFieldF2m(int m, BigInteger rp) {
    // check m and rp
    this.m = m;
    this.rp = rp;
    if (m <= 0) {
        throw new IllegalArgumentException("m is not positive");
    }
    int bitCount = this.rp.bitCount();
    if (!this.rp.testBit(0) || !this.rp.testBit(m) ||
        ((bitCount != 3) && (bitCount != 5))) {
        throw new IllegalArgumentException
            ("rp does not represent a valid reduction polynomial");
    }
    // convert rp into ks
    BigInteger temp = this.rp.clearBit(0).clearBit(m);
    this.ks = new int[bitCount-2];
    for (int i = this.ks.length-1; i >= 0; i--) {
        int index = temp.getLowestSetBit();
        this.ks[i] = index;
        temp = temp.clearBit(index);
    }
}
 
Example 2
/**
 * Creates an elliptic curve characteristic 2 finite
 * field which has 2^{@code m} elements with
 * polynomial basis.
 * The reduction polynomial for this field is based
 * on {@code rp} whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.<p>
 * Note: A valid reduction polynomial is either a
 * trinomial (X^{@code m} + X^{@code k} + 1
 * with {@code m} &gt; {@code k} &gt;= 1) or a
 * pentanomial (X^{@code m} + X^{@code k3}
 * + X^{@code k2} + X^{@code k1} + 1 with
 * {@code m} &gt; {@code k3} &gt; {@code k2}
 * &gt; {@code k1} &gt;= 1).
 * @param m with 2^{@code m} being the number of elements.
 * @param rp the BigInteger whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.
 * @exception NullPointerException if {@code rp} is null.
 * @exception IllegalArgumentException if {@code m}
 * is not positive, or {@code rp} does not represent
 * a valid reduction polynomial.
 */
public ECFieldF2m(int m, BigInteger rp) {
    // check m and rp
    this.m = m;
    this.rp = rp;
    if (m <= 0) {
        throw new IllegalArgumentException("m is not positive");
    }
    int bitCount = this.rp.bitCount();
    if (!this.rp.testBit(0) || !this.rp.testBit(m) ||
        ((bitCount != 3) && (bitCount != 5))) {
        throw new IllegalArgumentException
            ("rp does not represent a valid reduction polynomial");
    }
    // convert rp into ks
    BigInteger temp = this.rp.clearBit(0).clearBit(m);
    this.ks = new int[bitCount-2];
    for (int i = this.ks.length-1; i >= 0; i--) {
        int index = temp.getLowestSetBit();
        this.ks[i] = index;
        temp = temp.clearBit(index);
    }
}
 
Example 3
/**
 * Creates an elliptic curve characteristic 2 finite
 * field which has 2^{@code m} elements with
 * polynomial basis.
 * The reduction polynomial for this field is based
 * on {@code rp} whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.<p>
 * Note: A valid reduction polynomial is either a
 * trinomial (X^{@code m} + X^{@code k} + 1
 * with {@code m} &gt; {@code k} &gt;= 1) or a
 * pentanomial (X^{@code m} + X^{@code k3}
 * + X^{@code k2} + X^{@code k1} + 1 with
 * {@code m} &gt; {@code k3} &gt; {@code k2}
 * &gt; {@code k1} &gt;= 1).
 * @param m with 2^{@code m} being the number of elements.
 * @param rp the BigInteger whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.
 * @exception NullPointerException if {@code rp} is null.
 * @exception IllegalArgumentException if {@code m}
 * is not positive, or {@code rp} does not represent
 * a valid reduction polynomial.
 */
public ECFieldF2m(int m, BigInteger rp) {
    // check m and rp
    this.m = m;
    this.rp = rp;
    if (m <= 0) {
        throw new IllegalArgumentException("m is not positive");
    }
    int bitCount = this.rp.bitCount();
    if (!this.rp.testBit(0) || !this.rp.testBit(m) ||
        ((bitCount != 3) && (bitCount != 5))) {
        throw new IllegalArgumentException
            ("rp does not represent a valid reduction polynomial");
    }
    // convert rp into ks
    BigInteger temp = this.rp.clearBit(0).clearBit(m);
    this.ks = new int[bitCount-2];
    for (int i = this.ks.length-1; i >= 0; i--) {
        int index = temp.getLowestSetBit();
        this.ks[i] = index;
        temp = temp.clearBit(index);
    }
}
 
Example 4
Source Project: hottub   File: ECFieldF2m.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an elliptic curve characteristic 2 finite
 * field which has 2^{@code m} elements with
 * polynomial basis.
 * The reduction polynomial for this field is based
 * on {@code rp} whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.<p>
 * Note: A valid reduction polynomial is either a
 * trinomial (X^{@code m} + X^{@code k} + 1
 * with {@code m} &gt; {@code k} &gt;= 1) or a
 * pentanomial (X^{@code m} + X^{@code k3}
 * + X^{@code k2} + X^{@code k1} + 1 with
 * {@code m} &gt; {@code k3} &gt; {@code k2}
 * &gt; {@code k1} &gt;= 1).
 * @param m with 2^{@code m} being the number of elements.
 * @param rp the BigInteger whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.
 * @exception NullPointerException if {@code rp} is null.
 * @exception IllegalArgumentException if {@code m}
 * is not positive, or {@code rp} does not represent
 * a valid reduction polynomial.
 */
public ECFieldF2m(int m, BigInteger rp) {
    // check m and rp
    this.m = m;
    this.rp = rp;
    if (m <= 0) {
        throw new IllegalArgumentException("m is not positive");
    }
    int bitCount = this.rp.bitCount();
    if (!this.rp.testBit(0) || !this.rp.testBit(m) ||
        ((bitCount != 3) && (bitCount != 5))) {
        throw new IllegalArgumentException
            ("rp does not represent a valid reduction polynomial");
    }
    // convert rp into ks
    BigInteger temp = this.rp.clearBit(0).clearBit(m);
    this.ks = new int[bitCount-2];
    for (int i = this.ks.length-1; i >= 0; i--) {
        int index = temp.getLowestSetBit();
        this.ks[i] = index;
        temp = temp.clearBit(index);
    }
}
 
Example 5
/**
 * Creates an elliptic curve characteristic 2 finite
 * field which has 2^{@code m} elements with
 * polynomial basis.
 * The reduction polynomial for this field is based
 * on {@code rp} whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.<p>
 * Note: A valid reduction polynomial is either a
 * trinomial (X^{@code m} + X^{@code k} + 1
 * with {@code m} &gt; {@code k} &gt;= 1) or a
 * pentanomial (X^{@code m} + X^{@code k3}
 * + X^{@code k2} + X^{@code k1} + 1 with
 * {@code m} &gt; {@code k3} &gt; {@code k2}
 * &gt; {@code k1} &gt;= 1).
 * @param m with 2^{@code m} being the number of elements.
 * @param rp the BigInteger whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.
 * @exception NullPointerException if {@code rp} is null.
 * @exception IllegalArgumentException if {@code m}
 * is not positive, or {@code rp} does not represent
 * a valid reduction polynomial.
 */
public ECFieldF2m(int m, BigInteger rp) {
    // check m and rp
    this.m = m;
    this.rp = rp;
    if (m <= 0) {
        throw new IllegalArgumentException("m is not positive");
    }
    int bitCount = this.rp.bitCount();
    if (!this.rp.testBit(0) || !this.rp.testBit(m) ||
        ((bitCount != 3) && (bitCount != 5))) {
        throw new IllegalArgumentException
            ("rp does not represent a valid reduction polynomial");
    }
    // convert rp into ks
    BigInteger temp = this.rp.clearBit(0).clearBit(m);
    this.ks = new int[bitCount-2];
    for (int i = this.ks.length-1; i >= 0; i--) {
        int index = temp.getLowestSetBit();
        this.ks[i] = index;
        temp = temp.clearBit(index);
    }
}
 
Example 6
/**
 * Creates an elliptic curve characteristic 2 finite
 * field which has 2^{@code m} elements with
 * polynomial basis.
 * The reduction polynomial for this field is based
 * on {@code rp} whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.<p>
 * Note: A valid reduction polynomial is either a
 * trinomial (X^{@code m} + X^{@code k} + 1
 * with {@code m} &gt; {@code k} &gt;= 1) or a
 * pentanomial (X^{@code m} + X^{@code k3}
 * + X^{@code k2} + X^{@code k1} + 1 with
 * {@code m} &gt; {@code k3} &gt; {@code k2}
 * &gt; {@code k1} &gt;= 1).
 * @param m with 2^{@code m} being the number of elements.
 * @param rp the BigInteger whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.
 * @exception NullPointerException if {@code rp} is null.
 * @exception IllegalArgumentException if {@code m}
 * is not positive, or {@code rp} does not represent
 * a valid reduction polynomial.
 */
public ECFieldF2m(int m, BigInteger rp) {
    // check m and rp
    this.m = m;
    this.rp = rp;
    if (m <= 0) {
        throw new IllegalArgumentException("m is not positive");
    }
    int bitCount = this.rp.bitCount();
    if (!this.rp.testBit(0) || !this.rp.testBit(m) ||
        ((bitCount != 3) && (bitCount != 5))) {
        throw new IllegalArgumentException
            ("rp does not represent a valid reduction polynomial");
    }
    // convert rp into ks
    BigInteger temp = this.rp.clearBit(0).clearBit(m);
    this.ks = new int[bitCount-2];
    for (int i = this.ks.length-1; i >= 0; i--) {
        int index = temp.getLowestSetBit();
        this.ks[i] = index;
        temp = temp.clearBit(index);
    }
}
 
Example 7
/**
 * Creates an elliptic curve characteristic 2 finite
 * field which has 2^{@code m} elements with
 * polynomial basis.
 * The reduction polynomial for this field is based
 * on {@code rp} whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.<p>
 * Note: A valid reduction polynomial is either a
 * trinomial (X^{@code m} + X^{@code k} + 1
 * with {@code m} &gt; {@code k} &gt;= 1) or a
 * pentanomial (X^{@code m} + X^{@code k3}
 * + X^{@code k2} + X^{@code k1} + 1 with
 * {@code m} &gt; {@code k3} &gt; {@code k2}
 * &gt; {@code k1} &gt;= 1).
 * @param m with 2^{@code m} being the number of elements.
 * @param rp the BigInteger whose i-th bit corresponds to
 * the i-th coefficient of the reduction polynomial.
 * @exception NullPointerException if {@code rp} is null.
 * @exception IllegalArgumentException if {@code m}
 * is not positive, or {@code rp} does not represent
 * a valid reduction polynomial.
 */
public ECFieldF2m(int m, BigInteger rp) {
    // check m and rp
    this.m = m;
    this.rp = rp;
    if (m <= 0) {
        throw new IllegalArgumentException("m is not positive");
    }
    int bitCount = this.rp.bitCount();
    if (!this.rp.testBit(0) || !this.rp.testBit(m) ||
        ((bitCount != 3) && (bitCount != 5))) {
        throw new IllegalArgumentException
            ("rp does not represent a valid reduction polynomial");
    }
    // convert rp into ks
    BigInteger temp = this.rp.clearBit(0).clearBit(m);
    this.ks = new int[bitCount-2];
    for (int i = this.ks.length-1; i >= 0; i--) {
        int index = temp.getLowestSetBit();
        this.ks[i] = index;
        temp = temp.clearBit(index);
    }
}
 
Example 8
/**
 * Slightly faster binary gcd adapted from OpenJdk's MutableBigInteger.binaryGcd(int, int).
 * The BigInteger.gcd() implementation is still much faster.
 * 
 * @param a
 * @param b
 * @return gcd(a, b)
 */
public BigInteger gcd/*_binary2*/(BigInteger a, BigInteger b) {
	a = a.abs();
	if (b.equals(I_0)) return a;
	b = b.abs();
	if (a.equals(I_0)) return b;

	// Right shift a & b till their last bits equal to 1.
	final int aZeros = a.getLowestSetBit();
	final int bZeros = b.getLowestSetBit();
	a = a.shiftRight(aZeros);
	b = b.shiftRight(bZeros);

	final int t = (aZeros < bZeros ? aZeros : bZeros);

	int cmp;
	while ((cmp = a.compareTo(b)) != 0) {
		if (cmp > 0) {
			a = a.subtract(b);
			a = a.shiftRight(a.getLowestSetBit());
		} else {
			b = b.subtract(a);
			b = b.shiftRight(b.getLowestSetBit());
		}
	}
	return a.shiftLeft(t);
}
 
Example 9
private static BigInteger[] lucasSequence(BigInteger p, BigInteger P, BigInteger Q, BigInteger k) {
   int n = k.bitLength();
   int s = k.getLowestSetBit();

   BigInteger Uh = BigInteger.ONE;
   BigInteger Vl = TWO;
   BigInteger Vh = P;
   BigInteger Ql = BigInteger.ONE;
   BigInteger Qh = BigInteger.ONE;

   for (int j = n - 1; j >= s + 1; --j) {
      Ql = Ql.multiply(Qh).mod(p);

      if (k.testBit(j)) {
         Qh = Ql.multiply(Q).mod(p);
         Uh = Uh.multiply(Vh).mod(p);
         Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
         Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p);
      } else {
         Qh = Ql;
         Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
         Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
         Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
      }
   }

   Ql = Ql.multiply(Qh).mod(p);
   Qh = Ql.multiply(Q).mod(p);
   Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
   Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
   Ql = Ql.multiply(Qh).mod(p);

   for (int j = 1; j <= s; ++j) {
      Uh = Uh.multiply(Vl).mod(p);
      Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
      Ql = Ql.multiply(Ql).mod(p);
   }

   return new BigInteger[] { Uh, Vl };
}
 
Example 10
Source Project: alpha-wallet-android   File: SignaturePair.java    License: MIT License 5 votes vote down vote up
/**
 * The reverse of generateSelection - used in scanning the QR code.
 */
public static List<Integer> buildIndexList(String selection) {
    List<Integer> intList = new ArrayList<>();
    final int NIBBLE = 4;
    //one: convert to bigint
    String lengthStr = selection.substring(0, SELECTION_DESIGNATOR_SIZE);
    int selectionLength = Integer.parseInt(lengthStr);
    String trailingZerosStr = selection.substring(SELECTION_DESIGNATOR_SIZE, SELECTION_DESIGNATOR_SIZE + TRAILING_ZEROES_SIZE);
    int trailingZeros = Integer.parseInt(trailingZerosStr);
    int correctionFactor = trailingZeros * NIBBLE;

    String selectionStr = selection.substring(SELECTION_DESIGNATOR_SIZE + TRAILING_ZEROES_SIZE,
                                              SELECTION_DESIGNATOR_SIZE + TRAILING_ZEROES_SIZE + selectionLength);
    BigInteger bitField = new BigInteger(selectionStr, 10);

    int radix = bitField.getLowestSetBit();
    while (!bitField.equals(BigInteger.ZERO))
    {
        if (bitField.testBit(radix))
        {
            intList.add(radix + correctionFactor); //because we need to encode index zero as the first bit
            bitField = bitField.clearBit(radix);
        }
        radix++;
    }

    return intList;
}
 
Example 11
Source Project: batfish   File: Ip6Wildcard.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isPrefix() {
  BigInteger w = _wildcardMask.asBigInteger();
  BigInteger wp = w.add(BigInteger.ONE);
  int numTrailingZeros = wp.getLowestSetBit();
  BigInteger check = BigInteger.ONE.shiftLeft(numTrailingZeros);
  return wp.equals(check);
}
 
Example 12
Source Project: wallet-eos   File: FieldElement.java    License: Apache License 2.0 5 votes vote down vote up
private static BigInteger[] lucasSequence(BigInteger p, BigInteger P, BigInteger Q, BigInteger k) {
    int n = k.bitLength();
    int s = k.getLowestSetBit();
    BigInteger Uh = BigInteger.ONE;
    BigInteger Vl = TWO;
    BigInteger Vh = P;
    BigInteger Ql = BigInteger.ONE;
    BigInteger Qh = BigInteger.ONE;
    for (int j = n - 1; j >= s + 1; --j) {
        Ql = Ql.multiply(Qh).mod(p);
        if (k.testBit(j)) {
            Qh = Ql.multiply(Q).mod(p);
            Uh = Uh.multiply(Vh).mod(p);
            Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
            Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p);
        } else {
            Qh = Ql;
            Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
            Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
            Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
        }
    }
    Ql = Ql.multiply(Qh).mod(p);
    Qh = Ql.multiply(Q).mod(p);
    Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
    Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
    Ql = Ql.multiply(Qh).mod(p);
    for (int j = 1; j <= s; ++j) {
        Uh = Uh.multiply(Vl).mod(p);
        Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
        Ql = Ql.multiply(Ql).mod(p);
    }
    return new BigInteger[]{Uh, Vl};
}
 
Example 13
Source Project: bitshares_wallet   File: FieldElement.java    License: MIT License 5 votes vote down vote up
private static BigInteger[] lucasSequence(BigInteger p, BigInteger P, BigInteger Q, BigInteger k) {
   int n = k.bitLength();
   int s = k.getLowestSetBit();

   BigInteger Uh = BigInteger.ONE;
   BigInteger Vl = TWO;
   BigInteger Vh = P;
   BigInteger Ql = BigInteger.ONE;
   BigInteger Qh = BigInteger.ONE;

   for (int j = n - 1; j >= s + 1; --j) {
      Ql = Ql.multiply(Qh).mod(p);

      if (k.testBit(j)) {
         Qh = Ql.multiply(Q).mod(p);
         Uh = Uh.multiply(Vh).mod(p);
         Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
         Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p);
      } else {
         Qh = Ql;
         Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
         Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
         Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
      }
   }

   Ql = Ql.multiply(Qh).mod(p);
   Qh = Ql.multiply(Q).mod(p);
   Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
   Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
   Ql = Ql.multiply(Qh).mod(p);

   for (int j = 1; j <= s; ++j) {
      Uh = Uh.multiply(Vl).mod(p);
      Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
      Ql = Ql.multiply(Ql).mod(p);
   }

   return new BigInteger[] { Uh, Vl };
}
 
Example 14
/**
 * Binary gcd implementation.
 * @param m
 * @param n
 * @return gcd(m, n)
 */
public BigInteger gcd_binary1(BigInteger m, BigInteger n) {
	m = m.abs();
	n = n.abs();
	int mCmp1 = m.compareTo(I_1);
	int nCmp1 = n.compareTo(I_1);
	if (mCmp1>0 && nCmp1>0) {
		int m_lsb = m.getLowestSetBit();
		int n_lsb = n.getLowestSetBit();
		int shifts = Math.min(m_lsb, n_lsb);
		m = m.shiftRight(m_lsb);
		n = n.shiftRight(n_lsb);
		// now m and n are odd
		//LOG.debug("m=" + m + ", n=" + n + ", g=" + g);
		while (m.signum() > 0) {
	    	BigInteger t = m.subtract(n).shiftRight(1);
	        if (t.signum()<0) {
	        	t = t.negate();
	        	n = t.shiftRight(t.getLowestSetBit());
	        } else {
	        	m = t.shiftRight(t.getLowestSetBit());
	        }
			//LOG.debug("m=" + m + ", n=" + n);
		}
		BigInteger gcd = n.shiftLeft(shifts);
		//LOG.debug("gcd=" + gcd);
		return gcd;
	}
	if (mCmp1<0) return n;
	if (nCmp1<0) return m;
	// else one argument is 1
	return I_1;
}
 
Example 15
/**
 * Jacobi symbol J(a|m), with m odd.
 * 
 * First optimization. (still slow)
 * 
 * @param a
 * @param m
 * @return
 */
/* not public */ int jacobiSymbol_v02(BigInteger a, BigInteger m) {
   	int aCmpZero = a.compareTo(I_0);
       if (aCmpZero == 0) return 0;

      // make a positive
	int t=1, mMod8;
       if (aCmpZero < 0) {
           a = a.negate();
           mMod8 = m.intValue() & 7; // for m%8 we need only the lowest 3 bits
           if (mMod8==3 || mMod8==7) t = -t;
       }

	a = a.mod(m);
	
	// reduction loops
       int lsb, mMod4, aMod4;
	boolean hasOddPowerOf2;
	BigInteger tmp;
	while(!a.equals(I_0)) {
		// make a odd
		lsb = a.getLowestSetBit();
		hasOddPowerOf2 = (lsb&1)==1; // e.g. lsb==1 -> a has one 2
		if (lsb > 1) {
			// powers of 4 do not change t -> remove them in one go
			a = a.shiftRight(hasOddPowerOf2 ? lsb-1 : lsb);
		}
		if (hasOddPowerOf2) {
			a = a.shiftRight(1);
			mMod8 = m.intValue() & 7; // for m%8 we need only the lowest 3 bits
			if (mMod8==3 || mMod8==5) t = -t; // m == 3, 5 (mod 8) -> negate t
		}
		// swap variables
		tmp = a; a = m; m = tmp;
		// quadratic reciprocity
		aMod4 = a.intValue() & 3; // get lowest 2 bit
		mMod4 = m.intValue() & 3;
		if (aMod4==3 && mMod4==3) t = -t; // a == m == 3 (mod 4)
		a = a.mod(m);
	}
	if (m.equals(I_1)) return t;
	return 0;
}
 
Example 16
/**
	 * Tonelli-Shanks algorithm for modular sqrt R^2 == n (mod p),
	 * following <link>en.wikipedia.org/wiki/Tonelli-Shanks_algorithm</link>.
	 * 
	 * This algorithm works for odd primes <code>p</code> and <code>n</code> with <code>Legendre(n|p)=1</code>,
	 * but usually it is applied only to p with p==1 (mod 8), because for p == 3, 5, 7 (mod 8) there are simpler and faster formulas.
	 * 
	 * @param n a positive integer having Jacobi(n|p) = 1
	 * @param p odd prime
	 * @return the modular sqrt t
	 */
	private BigInteger Tonelli_Shanks(BigInteger n, BigInteger p) {
		// factor out powers of 2 from p-1, defining Q and S as p-1 = Q*2^S with Q odd.
		BigInteger pm1 = p.subtract(I_1);
		int S = pm1.getLowestSetBit(); // lowest set bit (0 if pm1 were odd which is impossible because p is odd)
//		if (DEBUG) {
//			LOG.debug("n=" + n + ", p=" + p);
//			assertEquals(1, jacobiEngine.jacobiSymbol(n, p));
//			assertTrue(S > 1); // S=1 is the Lagrange case p == 3 (mod 4), but we check it nonetheless.
//		}
		BigInteger Q = pm1.shiftRight(S);
		// find some z with Legendre(z|p)==-1, i.e. z being a quadratic non-residue (mod p)
		int z;
		for (z=2; ; z++) {
			if (jacobiEngine.jacobiSymbol(z, p) == -1) break;
		}
		// now z is found -> set c == z^Q
		BigInteger c = mpe.modPow(BigInteger.valueOf(z), Q, p); // TODO: implement modPow(int, BigInteger, BigInteger)
		BigInteger R = mpe.modPow(n, Q.add(I_1).shiftRight(1), p);
		BigInteger t = mpe.modPow(n, Q, p);
		int M = S;
		while (t.compareTo(I_1) != 0) { // if t=1 then R is the result
			// find the smallest i, 0<i<M, such that t^(2^i) == 1 (mod p)
//			if (DEBUG) {
//				LOG.debug("Find i < M=" + M + " with t=" + t);
//				// test invariants from <link>https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm#Proof</link>:
//				assertEquals(pm1, mpe.modPow(c, I_1.shiftLeft(M-1), p)); //  -1 == c^(2^(M-1)) (mod p)
//				assertEquals(1, mpe.modPow(t, I_1.shiftLeft(M-1), p));   //   1 == t^(2^(M-1)) (mod p)
//				BigInteger nModP = n.mod(p);
//				assertEquals(R.multiply(R).mod(p), t.multiply(nModP).mod(p));  // R^2 == t*n (mod p)
//			}
			boolean foundI = false;
			int i;
			for (i=1; i<M; i++) {
				if (mpe.modPow(t, I_1.shiftLeft(i), p).equals(I_1)) { // t^(2^i) == 1 (mod p) ?
					foundI = true;
					break;
				}
			}
			if (foundI==false) throw new IllegalStateException("Tonelli-Shanks did not find an 'i' < M=" + M);
			
			BigInteger b = mpe.modPow(c, I_1.shiftLeft(M-i-1), p); // c^(2^(M-i-1))
			R = R.multiply(b).mod(p);
			c = b.multiply(b).mod(p);
			t = t.multiply(c).mod(p);
			M = i;
		}
//		if (DEBUG) assertEquals(R.pow(2).mod(p), n.mod(p));
		// return the smaller sqrt
		return (R.compareTo(p.shiftRight(1)) <= 0) ? R : p.subtract(R);
	}
 
Example 17
/**
 * Decomposes the argument N into prime factors.
 * The result is a multiset of BigIntegers, sorted bottom-up.
 * @param N Number to factor.
 * @return The prime factorization of N
 */
public SortedMultiset<BigInteger> factor(BigInteger N) {
	SortedMultiset<BigInteger> primeFactors = new SortedMultiset_BottomUp<BigInteger>();
	// first get rid of case |N|<=1:
	if (N.abs().compareTo(I_1)<=0) {
		// https://oeis.org/wiki/Empty_product#Prime_factorization_of_1:
		// "the set of prime factors of 1 is the empty set"
		if (!N.equals(I_1)) {
			primeFactors.add(N);
		}
		return primeFactors;
	}
	// make N positive:
	if (N.signum()<0) {
		primeFactors.add(I_MINUS_1);
		N = N.abs();
	}
	// Remove multiples of 2:
	int lsb = N.getLowestSetBit();
	if (lsb > 0) {
		primeFactors.add(I_2, lsb);
		N = N.shiftRight(lsb);
	}
	if (N.equals(I_1)) {
		// N was a power of 2
		return primeFactors;
	}

	int Nbits = N.bitLength();
	if (Nbits > 62) {
		// "Small" algorithms like trial division, Lehman or Pollard-Rho are very good themselves
		// at finding small factors, but for larger N we do some trial division.
		// This will help "big" algorithms to factor smooth numbers much faster.
		int actualTdivLimit;
		if (tdivLimit != null) {
			// use "dictated" limit
			actualTdivLimit = tdivLimit.intValue();
		} else {
			// adjust tdivLimit=2^e by experimental results
			final double e = 10 + (Nbits-45)*0.07407407407; // constant 0.07.. = 10/135
			actualTdivLimit = (int) Math.min(1<<20, Math.pow(2, e)); // upper bound 2^20
		}

		N = tdiv.findSmallOddFactors(N, actualTdivLimit, primeFactors);
		// TODO add tdiv duration to final report
		
		if (N.equals(I_1)) {
			// N was "easy"
			return primeFactors;
		}
	}
	
	// N contains larger factors...
	ArrayList<BigInteger> untestedFactors = new ArrayList<BigInteger>(); // faster than SortedMultiset
	untestedFactors.add(N);
	while (untestedFactors.size()>0) {
		N = untestedFactors.remove(untestedFactors.size()-1);
		if (bpsw.isProbablePrime(N)) { // TODO exploit tdiv done so far
			// N is probable prime. In exceptional cases this prediction may be wrong and N composite
			// -> then we would falsely predict N to be prime. BPSW is known to be exact for N <= 64 bit.
			//LOG.debug(N + " is probable prime.");
			primeFactors.add(N);
			continue;
		}
		BigInteger factor1 = findSingleFactor(N);
		if (factor1.compareTo(I_1) > 0 && factor1.compareTo(N) < 0) {
			// found factor
			untestedFactors.add(factor1);
			untestedFactors.add(N.divide(factor1));
		} else {
			// findSingleFactor() failed to find a factor of the composite N
			if (DEBUG) LOG.error("Factor algorithm " + getName() + " failed to find a factor of composite " + N);
			primeFactors.add(N);
		}

	}
	//LOG.debug(this.factorAlg + ": => all factors = " + primeFactors);
	return primeFactors;
}
 
Example 18
static double bigToDouble(BigInteger x) {
    // This is an extremely fast implementation of BigInteger.doubleValue(). JDK patch pending.
    BigInteger absX = x.abs();
    int exponent = absX.bitLength() - 1;
    // exponent == floor(log2(abs(x)))
    if (exponent < Long.SIZE - 1) {
      return x.longValue();
    } else if (exponent > MAX_EXPONENT) {
      return x.signum() * POSITIVE_INFINITY;
    }

    /*
     * We need the top SIGNIFICAND_BITS + 1 bits, including the "implicit" one bit. To make rounding
     * easier, we pick out the top SIGNIFICAND_BITS + 2 bits, so we have one to help us round up or
     * down. twiceSignifFloor will contain the top SIGNIFICAND_BITS + 2 bits, and signifFloor the
     * top SIGNIFICAND_BITS + 1.
     *
     * It helps to consider the real number signif = absX * 2^(SIGNIFICAND_BITS - exponent).
     */
    int shift = exponent - SIGNIFICAND_BITS - 1;
    long twiceSignifFloor = absX.shiftRight(shift).longValue();
    long signifFloor = twiceSignifFloor >> 1;
    signifFloor &= SIGNIFICAND_MASK; // remove the implied bit

    /*
     * We round up if either the fractional part of signif is strictly greater than 0.5 (which is
     * true if the 0.5 bit is set and any lower bit is set), or if the fractional part of signif is
     * >= 0.5 and signifFloor is odd (which is true if both the 0.5 bit and the 1 bit are set).
     */
    boolean increment = (twiceSignifFloor & 1) != 0
&& ((signifFloor & 1) != 0 || absX.getLowestSetBit() < shift);
    long signifRounded = increment? signifFloor + 1 : signifFloor;
    long bits = (long) ((exponent + EXPONENT_BIAS)) << SIGNIFICAND_BITS;
    bits += signifRounded;
    /*
     * If signifRounded == 2^53, we'd need to set all of the significand bits to zero and add 1 to
     * the exponent. This is exactly the behavior we get from just adding signifRounded to bits
     * directly. If the exponent is MAX_DOUBLE_EXPONENT, we round up (correctly) to
     * Double.POSITIVE_INFINITY.
     */
    bits |= x.signum() & SIGN_MASK;
    return longBitsToDouble(bits);
  }
 
Example 19
Source Project: RipplePower   File: ECFieldElement.java    License: Apache License 2.0 4 votes vote down vote up
private BigInteger[] lucasSequence(
    BigInteger  P,
    BigInteger  Q,
    BigInteger  k)
{
    // TODO Research and apply "common-multiplicand multiplication here"

    int n = k.bitLength();
    int s = k.getLowestSetBit();

    // assert k.testBit(s);

    BigInteger Uh = ECConstants.ONE;
    BigInteger Vl = ECConstants.TWO;
    BigInteger Vh = P;
    BigInteger Ql = ECConstants.ONE;
    BigInteger Qh = ECConstants.ONE;

    for (int j = n - 1; j >= s + 1; --j)
    {
        Ql = modMult(Ql, Qh);

        if (k.testBit(j))
        {
            Qh = modMult(Ql, Q);
            Uh = modMult(Uh, Vh);
            Vl = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
            Vh = modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1)));
        }
        else
        {
            Qh = Ql;
            Uh = modReduce(Uh.multiply(Vl).subtract(Ql));
            Vh = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
            Vl = modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
        }
    }

    Ql = modMult(Ql, Qh);
    Qh = modMult(Ql, Q);
    Uh = modReduce(Uh.multiply(Vl).subtract(Ql));
    Vl = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
    Ql = modMult(Ql, Qh);

    for (int j = 1; j <= s; ++j)
    {
        Uh = modMult(Uh, Vl);
        Vl = modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
        Ql = modMult(Ql, Ql);
    }

    return new BigInteger[]{ Uh, Vl };
}
 
Example 20
/**
 * Returns {@code true} if {@code x} represents a power of two.
 */


public static boolean isPowerOfTwo(BigInteger x) {
  checkNotNull(x);
  return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1;
}