Java Code Examples for java.math.BigInteger#ONE

The following examples show how to use java.math.BigInteger#ONE . 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
/**
 * Evaluates all value expressions of the bitmask type.
 *
 * This method can be called from Expression.evaluate() method if some expression refers to a
 * value before definition of this value. Therefore 'isEvaluated' check is necessary.
 *
 * This method calculates and sets all named values.
 */
void evaluate()
{
    if (!isEvaluated)
    {
        // fill resolved bitmask type
        final ZserioType baseType = typeInstantiation.getBaseType();
        if (!(baseType instanceof IntegerType) || ((IntegerType)baseType).isSigned())
        {
            throw new ParserException(this, "Bitmask '" + this.getName() + "' cannot use " +
                    baseType.getName() + " type! Only unsigned integer types are allowed!");
        }

        // evaluate bitmask values
        BigInteger defaultValue = BigInteger.ONE;
        for (BitmaskValue value : values)
        {
            if (value.getValueExpression() == null)
                value.setValue(defaultValue);

            defaultValue = getNextValue(value.getValue());
        }

        isEvaluated = true;
    }
}
 
Example 2
static BigInteger listProduct(List<BigInteger> nums, int start, int end) {
  switch (end - start) {
    case 0:
      return BigInteger.ONE;
    case 1:
      return nums.get(start);
    case 2:
      return nums.get(start).multiply(nums.get(start + 1));
    case 3:
      return nums.get(start).multiply(nums.get(start + 1)).multiply(nums.get(start + 2));
    default:
      // Otherwise, split the list in half and recursively do this.
      int m = (end + start) >>> 1;
      return listProduct(nums, start, m).multiply(listProduct(nums, m, end));
  }
}
 
Example 3
private static void validateDHPublicKey(BigInteger p,
        BigInteger g, BigInteger y) throws InvalidKeyException {

    // For better interoperability, the interval is limited to [2, p-2].
    BigInteger leftOpen = BigInteger.ONE;
    BigInteger rightOpen = p.subtract(BigInteger.ONE);
    if (y.compareTo(leftOpen) <= 0) {
        throw new InvalidKeyException(
                "Diffie-Hellman public key is too small");
    }
    if (y.compareTo(rightOpen) >= 0) {
        throw new InvalidKeyException(
                "Diffie-Hellman public key is too large");
    }

    // y^q mod p == 1?
    // Unable to perform this check as q is unknown in this circumstance.

    // p is expected to be prime.  However, it is too expensive to check
    // that p is prime.  Instead, in order to mitigate the impact of
    // non-prime values, we check that y is not a factor of p.
    BigInteger r = p.remainder(y);
    if (r.equals(BigInteger.ZERO)) {
        throw new InvalidKeyException("Invalid Diffie-Hellman parameters");
    }
}
 
Example 4
Source Project: client-sdk-java   File: TypeEncoderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDynamicArray() {
    DynamicArray<Uint> array = new DynamicArray<>(
            new Uint(BigInteger.ONE),
            new Uint(BigInteger.valueOf(2)),
            new Uint(BigInteger.valueOf(3))
    );

    assertThat(
            TypeEncoder.encodeDynamicArray(array),
            is("0000000000000000000000000000000000000000000000000000000000000003"
                    + "0000000000000000000000000000000000000000000000000000000000000001"
                    + "0000000000000000000000000000000000000000000000000000000000000002"
                    + "0000000000000000000000000000000000000000000000000000000000000003"
            ));
}
 
Example 5
Source Project: SimFix   File: 1_MathUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger power.
 * @param k number to raise
 * @param e exponent (must be positive or null)
 * @return k<sup>e</sup>
 * @exception IllegalArgumentException if e is negative
 */
public static BigInteger pow(final BigInteger k, BigInteger e)
    throws IllegalArgumentException {

    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            "cannot raise an integral value to a negative power ({0}^{1})",
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;

}
 
Example 6
@Test
void isValidTransactionInBlockEmptyEquals() throws ExecutionException, InterruptedException {

    BigInteger height = BigInteger.ONE;
    String leaf = "ABCD";
    String root = "ABCD";

    BlockInfo blockInfo = Mockito.mock(BlockInfo.class);
    Mockito.when(blockInfo.getBlockTransactionsHash()).thenReturn(root);

    Mockito.when(blockRepositoryMock.getBlockByHeight(height))
        .thenReturn(Observable.just(blockInfo));

    List<MerklePathItem> merklePath = new ArrayList<>();
    MerkleProofInfo merkleProofInfo = new MerkleProofInfo(merklePath);
    Mockito.when(blockRepositoryMock.getMerkleTransaction(height, leaf))
        .thenReturn(Observable.just(merkleProofInfo));

    Assertions.assertTrue(service.isValidTransactionInBlock(height, leaf).toFuture().get());

}
 
Example 7
public static void main(String[] args) throws IOException {
	BigInteger [] fac=new BigInteger [10001];
	fac[0]=BigInteger.ONE;
	for (int i=1;i<fac.length;i++) {
		fac[i]=fac[i-1].multiply(BigInteger.valueOf(i));
		while (fac[i].mod(BigInteger.TEN).equals(BigInteger.ZERO)) {
			fac[i]=fac[i].divide(BigInteger.TEN);
		}
	}
	String blank="     ";
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	String s;
	while ((s=br.readLine())!=null) {
		int n=Integer.parseInt(s);
		String ns=n+"";
		ns=blank.substring(0,5-ns.length())+ns;
		
		StringBuilder sb=new StringBuilder(ns);
		sb.append(" -> ");
		String facS=fac[n].toString();
		sb.append(facS.substring(facS.length()-1, facS.length()));
		System.out.println(sb.toString());
	}
}
 
Example 8
@Test
public void testEthGetTransactionByBlockNumberAndIndex() throws Exception {
    BigInteger index = BigInteger.ONE;

    EthTransaction ethTransaction = web3j.ethGetTransactionByBlockNumberAndIndex(
            DefaultBlockParameter.valueOf(config.validBlock()), index).send();
    assertTrue(ethTransaction.getTransaction().isPresent());
    Transaction transaction = ethTransaction.getTransaction().get();
    assertThat(transaction.getBlockHash(), is(config.validBlockHash()));
    assertThat(transaction.getTransactionIndex(), equalTo(index));
}
 
Example 9
Source Project: protect   File: Polynomials.java    License: MIT License 5 votes vote down vote up
/**
 * Computes n!
 * 
 * @param n
 * @return
 */
public static BigInteger factorial(BigInteger n) {
	BigInteger result = BigInteger.ONE;

	while (!n.equals(BigInteger.ZERO)) {
		result = result.multiply(n);
		n = n.subtract(BigInteger.ONE);
	}

	return result;
}
 
Example 10
/**
 * main method of the Application
 *
 * @param args
 */
public static void main(String[] args) {
    try {
        // Initialize the RestaurantService
        RestaurantService restaurantService = new RestaurantService(new InMemRestaurantRepository());

        // Data Creation for Restaurants
        Table table1 = new Table("Table 1", BigInteger.ONE, 6);
        Table table2 = new Table("Table 2", BigInteger.valueOf(2), 4);
        Table table3 = new Table("Table 3", BigInteger.valueOf(3), 2);
        List<Table> tableList = new ArrayList();
        tableList.add(table1);
        tableList.add(table2);
        tableList.add(table3);
        Restaurant restaurant1 = new Restaurant("Big-O Restaurant", "1", tableList);

        // Adding the created restaurant using Service
        restaurantService.add(restaurant1);

        // Note: To raise an exception give Same restaurant name to one of the below restaurant
        Restaurant restaurant2 = new Restaurant("Pizza Shops", "2", null);
        restaurantService.add(restaurant2);

        Restaurant restaurant3 = new Restaurant("La Pasta", "3", null);
        restaurantService.add(restaurant3);

        // Retrieving all restaurants using Service
        Collection<Restaurant> restaurants = restaurantService.getAll();

        // Print the retrieved restaurants on console
        System.out.println("Restaurants List:");
        restaurants.stream().forEach((restaurant) -> {
            System.out.println("Restaurant: " + restaurant);
        });
    } catch (Exception ex) {
        System.out.println("Exception: " + ex.getMessage());
        // Exception Handling Code
    }
}
 
Example 11
/**
 * Test for <code>getPrivateExponent()</code> method<br>
 * Assertion: returns private exponent
 */
public final void testGetPrivateExponent() {
    RSAMultiPrimePrivateCrtKeySpec ks =
        new RSAMultiPrimePrivateCrtKeySpec(
                BigInteger.ONE,
                BigInteger.ONE,
                BigInteger.ONE,
                BigInteger.ONE,
                BigInteger.ONE,
                BigInteger.ONE,
                BigInteger.ONE,
                BigInteger.ONE,
                opi);
    assertTrue(BigInteger.ONE.equals(ks.getPrivateExponent()));
}
 
Example 12
Source Project: IPAddress   File: AddressDivisionSeries.java    License: Apache License 2.0 5 votes vote down vote up
@Override
default BigInteger getCount() {
	BigInteger result = BigInteger.ONE;
	int count = getDivisionCount();
	if(count > 0) {
		for(int i = 0; i < count; i++) {
			AddressGenericDivision div = getDivision(i);
			if(div.isMultiple()) {
				BigInteger divCount = getDivision(i).getCount();
				result = result.multiply(divCount);
			}
		}
	}
	return result;
}
 
Example 13
public static X509Certificate generateCertificate(OutputStream output) throws NoSuchAlgorithmException, OperatorCreationException, CertificateException, KeyStoreException, NoSuchProviderException, IOException {
	BouncyCastleProvider provider = new BouncyCastleProvider(); // Use SpongyCastle provider, supports creating X509 certs
	KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
	generator.initialize(2048, new SecureRandom());
	
	KeyPair keyPair = generator.generateKeyPair();
	
	SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
	ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(provider).build(keyPair.getPrivate());
	
	Date startDate = new Date();
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(startDate);
	calendar.add(Calendar.YEAR, YEARS_VALID);
    Date endDate = calendar.getTime();
	
	X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(new X500Name(ISSUER),
			BigInteger.ONE, 
			startDate, endDate, new X500Name(ISSUER),
			publicKeyInfo);

	X509CertificateHolder certificateHolder = certBuilder.build(signer);
	
	X509Certificate certificate = new JcaX509CertificateConverter().setProvider(provider).getCertificate(certificateHolder);
	
	KeyStore keyStore = KeyStore.getInstance("PKCS12", provider);
	keyStore.load(null, null);
	keyStore.setKeyEntry("Jumble Key", keyPair.getPrivate(), null, new X509Certificate[] { certificate });
	
	keyStore.store(output, "".toCharArray());
	
	return certificate;
}
 
Example 14
Source Project: eos4j   File: FieldElement.java    License: GNU General Public License v3.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 15
@Test
public void testEmptyRandomWallet() throws Exception {
    // Add a random set of outputs
    StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1);
    Random rng = new Random();
    for (int i = 0; i < rng.nextInt(100) + 1; i++) {
        Transaction tx = createFakeTx(PARAMS, Coin.valueOf(rng.nextInt((int) COIN.value)), myAddress);
        wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, i);
    }
    SendRequest request = SendRequest.emptyWallet(OTHER_ADDRESS);
    wallet.completeTx(request);
    wallet.commitTx(request.tx);
    assertEquals(ZERO, wallet.getBalance());
}
 
Example 16
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 17
/**
 * Simple constructor.
 * Build a null rational number
 */
public RationalNumber() {
  p = BigInteger.ZERO;
  q = BigInteger.ONE;
}
 
Example 18
/**
 * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
 * {@code k}, that is, {@code n! / (k! (n - k)!)}.
 *
 * <p><b>Warning:</b> the result can take as much as <i>O(k log n)</i> space.
 *
 * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
 */
public static BigInteger binomial(int n, int k) {
  checkNonNegative("n", n);
  checkNonNegative("k", k);
  checkArgument(k <= n, "k (%s) > n (%s)", k, n);
  if (k > (n >> 1)) {
    k = n - k;
  }
  if (k < LongMath.biggestBinomials.length && n <= LongMath.biggestBinomials[k]) {
    return BigInteger.valueOf(LongMath.binomial(n, k));
  }

  BigInteger accum = BigInteger.ONE;

  long numeratorAccum = n;
  long denominatorAccum = 1;

  int bits = LongMath.log2(n, RoundingMode.CEILING);

  int numeratorBits = bits;

  for (int i = 1; i < k; i++) {
    int p = n - i;
    int q = i + 1;

    // log2(p) >= bits - 1, because p >= n/2

    if (numeratorBits + bits >= Long.SIZE - 1) {
      // The numerator is as big as it can get without risking overflow.
      // Multiply numeratorAccum / denominatorAccum into accum.
      accum =
          accum
              .multiply(BigInteger.valueOf(numeratorAccum))
              .divide(BigInteger.valueOf(denominatorAccum));
      numeratorAccum = p;
      denominatorAccum = q;
      numeratorBits = bits;
    } else {
      // We can definitely multiply into the long accumulators without overflowing them.
      numeratorAccum *= p;
      denominatorAccum *= q;
      numeratorBits += bits;
    }
  }
  return accum
      .multiply(BigInteger.valueOf(numeratorAccum))
      .divide(BigInteger.valueOf(denominatorAccum));
}
 
Example 19
Source Project: deeplearning4j   File: Rational.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Default ctor, which represents the zero.
 */
public Rational() {
    a = BigInteger.ZERO;
    b = BigInteger.ONE;
}
 
Example 20
Source Project: astor   File: BigFraction.java    License: GNU General Public License v2.0 2 votes vote down vote up
/**
 * <p>
 * Create a {@link BigFraction} equivalent to the passed long, ie "num / 1".
 * </p>
 *
 * @param num
 *            the numerator.
 */
public BigFraction(final long num) {
    this(BigInteger.valueOf(num), BigInteger.ONE);
}