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

The following examples show how to use java.math.BigInteger#add() . 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: j2objc   File: ObjectIdentifier.java    License: Apache License 2.0 6 votes vote down vote up
private void init(int[] components, int length) {
    int pos = 0;
    byte[] tmp = new byte[length*5+1];  // +1 for empty input

    if (components[1] < Integer.MAX_VALUE - components[0]*40)
        pos += pack7Oid(components[0]*40+components[1], tmp, pos);
    else {
        BigInteger big = BigInteger.valueOf(components[1]);
        big = big.add(BigInteger.valueOf(components[0]*40));
        pos += pack7Oid(big, tmp, pos);
    }

    for (int i=2; i<length; i++) {
        pos += pack7Oid(components[i], tmp, pos);
    }
    encoding = new byte[pos];
    System.arraycopy(tmp, 0, encoding, 0, pos);
}
 
Example 2
Source Project: ghidra   File: AbstractAddressSpace.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Address addNoWrap(GenericAddress addr, BigInteger displacement)
		throws AddressOverflowException {

	if (displacement.equals(BigInteger.ZERO)) {
		return addr;
	}
	testAddressSpace(addr);
	BigInteger addrOff = addr.getOffsetAsBigInteger();
	BigInteger maxOff = maxAddress.getOffsetAsBigInteger();
	BigInteger minOff = minAddress.getOffsetAsBigInteger();
	BigInteger newOffset = addrOff.add(displacement);
	if (newOffset.compareTo(minOff) < 0 || newOffset.compareTo(maxOff) > 0) {
		throw new AddressOverflowException(
			"Address Overflow in add: " + addr + " + " + displacement);
	}

	long resultOffset = NumericUtilities.bigIntegerToUnsignedLong(newOffset);
	return getUncheckedAddress(resultOffset);
}
 
Example 3
Source Project: depotSample   File: CommonUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static BigInteger trans2BigInt(String key_id)
{
	BigInteger b_int = BigInteger.ZERO;
	if(isNotEmpty(key_id))
	{
		int max_index = 32;
		int str_size = key_id.length();
		int for_index = Math.min(max_index, str_size);
		for(int i = 0; i < for_index;++i )
		{
			long c_int = (long)key_id.charAt(i);
			int bytes = (for_index - i - 1) * 8;
			b_int = b_int.add(BigInteger.valueOf(c_int).shiftLeft(bytes));
		}
	}
	return b_int;
}
 
Example 4
public BigInteger calculateFofX(final BigInteger x)
{
    // pick up the 0th term directly:
    BigInteger ret = coefficients[0];

    // for each of the other terms:
    for (int term = 1, n = coefficients.length; term < n; term++)
    {
        // the index of term N is N:
        final int indexOfTerm = term;

        // the exponent of term N is N:
        final int powerOfTerm = term;

        BigInteger base = x;
        BigInteger power = base.pow(powerOfTerm);

        BigInteger add = coefficients[indexOfTerm].multiply(power);
        ret = ret.add(add);
    }
    return ret;
}
 
Example 5
Source Project: Bytecoder   File: ObjectIdentifier.java    License: Apache License 2.0 6 votes vote down vote up
private void init(int[] components, int length) {
    int pos = 0;
    byte[] tmp = new byte[length*5+1];  // +1 for empty input

    if (components[1] < Integer.MAX_VALUE - components[0]*40)
        pos += pack7Oid(components[0]*40+components[1], tmp, pos);
    else {
        BigInteger big = BigInteger.valueOf(components[1]);
        big = big.add(BigInteger.valueOf(components[0]*40));
        pos += pack7Oid(big, tmp, pos);
    }

    for (int i=2; i<length; i++) {
        pos += pack7Oid(components[i], tmp, pos);
    }
    encoding = new byte[pos];
    System.arraycopy(tmp, 0, encoding, 0, pos);
}
 
Example 6
/** Main method */
public static void main(String[] args) {
	// Find the first ten numbers greater than 
	// Long.MAX_VALUE that are divisible by 5 or 6.
	int count = 0;
	BigInteger n = new BigInteger(String.valueOf(Long.MAX_VALUE));
	BigInteger five = new BigInteger("5");
	BigInteger six = new BigInteger("6");
	BigInteger zero = new BigInteger("0");

	// Display results
	System.out.println("\nFirst ten numbers greater than Long.MAX_VALUE" +
		" that are divisible by 5 or 6:");
	while (count < 10) {
		n = n.add(new BigInteger("1"));
		if ((n.remainder(five)).compareTo(zero) == 0 || 
			 (n.remainder(six)).compareTo(zero) == 0) {
			System.out.println(n);
			count++;
		}
	}
}
 
Example 7
Source Project: nuls-v2   File: CoinData.java    License: MIT License 6 votes vote down vote up
/**
 * 计算指定资产手续费
 * @param assetChainId     指定资产链ID
 * @param assetId          指定资产ID
 * @return                 手续费大小
 * */
public BigInteger getFeeByAsset(int assetChainId, int assetId){
    BigInteger fromAmount = BigInteger.ZERO;
    BigInteger toAmount = BigInteger.ZERO;
    for (CoinFrom coinFrom : from) {
        if (coinFrom.getAssetsChainId() == assetChainId && coinFrom.getAssetsId() == assetId) {
            fromAmount = fromAmount.add(coinFrom.getAmount());
        }
    }
    for (CoinTo coinTo : to) {
        if (coinTo.getAssetsChainId() == assetChainId && coinTo.getAssetsId() == assetId) {
            toAmount = toAmount.add(coinTo.getAmount());
        }
    }
    return fromAmount.subtract(toAmount);
}
 
Example 8
Source Project: maven-framework-project   File: XomCreateXML.java    License: MIT License 5 votes vote down vote up
/**
 * Create elements in namespaces
 */
@Test
public void test07() throws Exception{
	BigInteger low  = BigInteger.ONE;
      BigInteger high = BigInteger.ONE;      

      String namespace = "http://www.w3.org/1998/Math/MathML";
      Element root = new Element("mathml:math", namespace);  
      for (int i = 1; i <= 10; i++) {
        Element mrow = new Element("mathml:mrow", namespace);
        Element mi = new Element("mathml:mi", namespace);
        Element mo = new Element("mathml:mo", namespace);
        Element mn = new Element("mathml:mn", namespace);
        mrow.appendChild(mi);
        mrow.appendChild(mo);
        mrow.appendChild(mn);
        root.appendChild(mrow);
        mi.appendChild("f(" + i + ")");
        mo.appendChild("=");
        mn.appendChild(low.toString());
        
        BigInteger temp = high;
        high = high.add(low);
        low = temp;
      }
      Document doc = new Document(root);

      try {
        Serializer serializer = new Serializer(System.out, "ISO-8859-1");
        serializer.setIndent(4);
        serializer.setMaxLength(64);
        serializer.write(doc);  
      }
      catch (IOException ex) {
        System.err.println(ex); 
      }  
	
}
 
Example 9
public static void check(BigInteger val, BigInteger mod, BigInteger inv) {
    BigInteger r = inv.multiply(val).remainder(mod);
    if (r.signum() == -1)
        r = r.add(mod);
    if (!r.equals(BigInteger.ONE))
        throw new RuntimeException("Numerically incorrect modular inverse");
}
 
Example 10
public static void main (String [] args) throws Exception {
	BigInteger [] ans=new BigInteger [1501];
	ans[1]=new BigInteger("0");
	ans[2]=new BigInteger("1");
	ans[3]=new BigInteger("5");
	ans[4]=new BigInteger("9");
	
	BigInteger [] width=new BigInteger [1501];
	width[3]=new BigInteger("2");
	width[4]=new BigInteger("3");
	
	BigInteger counter=new BigInteger("7");
	for (int i=5;i<ans.length;i++) {
		width[i]=width[i-1].add(width[i-2]);
		BigInteger min=counter;
		BigInteger max=counter.add(width[i]).subtract(BigInteger.ONE);
		ans[i]=min.add(max).divide(BigInteger.valueOf(2));
		counter=counter.add(width[i]);
	}
	
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	int t=0;
	while (true) {
		int N=Integer.parseInt(br.readLine());
		if (N==0) break;
		System.out.printf("Set %d:\n%s\n", ++t, ans[N]);
	}
}
 
Example 11
Source Project: symbol-sdk-java   File: MathUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts a 2^8 bit representation to a BigInteger. Value: bytes[0] + 2^8 * bytes[1] + ...
 *
 * @param bytes The 2^8 bit representation.
 * @return The BigInteger.
 */
public static BigInteger toBigInteger(final byte[] bytes) {
    BigInteger b = BigInteger.ZERO;
    for (int i = 0; i < bytes.length; i++) {
        b = b
            .add(BigInteger.ONE.multiply(BigInteger.valueOf(bytes[i] & 0xff)).shiftLeft(i * 8));
    }

    return b;
}
 
Example 12
/**
 * @return The sum of the absolute values of the elements.
 */
public BigInteger absSum() {
	BigInteger sum = I_0;
	for (BigInteger elem : this) {
		sum = sum.add(elem.abs());
	}
	return sum;
}
 
Example 13
Source Project: spring-analysis-note   File: OpPlus.java    License: MIT License 4 votes vote down vote up
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
	SpelNodeImpl leftOp = getLeftOperand();

	if (this.children.length < 2) {  // if only one operand, then this is unary plus
		Object operandOne = leftOp.getValueInternal(state).getValue();
		if (operandOne instanceof Number) {
			if (operandOne instanceof Double) {
				this.exitTypeDescriptor = "D";
			}
			else if (operandOne instanceof Float) {
				this.exitTypeDescriptor = "F";
			}
			else if (operandOne instanceof Long) {
				this.exitTypeDescriptor = "J";
			}
			else if (operandOne instanceof Integer) {
				this.exitTypeDescriptor = "I";
			}
			return new TypedValue(operandOne);
		}
		return state.operate(Operation.ADD, operandOne, null);
	}

	TypedValue operandOneValue = leftOp.getValueInternal(state);
	Object leftOperand = operandOneValue.getValue();
	TypedValue operandTwoValue = getRightOperand().getValueInternal(state);
	Object rightOperand = operandTwoValue.getValue();

	if (leftOperand instanceof Number && rightOperand instanceof Number) {
		Number leftNumber = (Number) leftOperand;
		Number rightNumber = (Number) rightOperand;

		if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) {
			BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
			BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
			return new TypedValue(leftBigDecimal.add(rightBigDecimal));
		}
		else if (leftNumber instanceof Double || rightNumber instanceof Double) {
			this.exitTypeDescriptor = "D";
			return new TypedValue(leftNumber.doubleValue() + rightNumber.doubleValue());
		}
		else if (leftNumber instanceof Float || rightNumber instanceof Float) {
			this.exitTypeDescriptor = "F";
			return new TypedValue(leftNumber.floatValue() + rightNumber.floatValue());
		}
		else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger) {
			BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
			BigInteger rightBigInteger = NumberUtils.convertNumberToTargetClass(rightNumber, BigInteger.class);
			return new TypedValue(leftBigInteger.add(rightBigInteger));
		}
		else if (leftNumber instanceof Long || rightNumber instanceof Long) {
			this.exitTypeDescriptor = "J";
			return new TypedValue(leftNumber.longValue() + rightNumber.longValue());
		}
		else if (CodeFlow.isIntegerForNumericOp(leftNumber) || CodeFlow.isIntegerForNumericOp(rightNumber)) {
			this.exitTypeDescriptor = "I";
			return new TypedValue(leftNumber.intValue() + rightNumber.intValue());
		}
		else {
			// Unknown Number subtypes -> best guess is double addition
			return new TypedValue(leftNumber.doubleValue() + rightNumber.doubleValue());
		}
	}

	if (leftOperand instanceof String && rightOperand instanceof String) {
		this.exitTypeDescriptor = "Ljava/lang/String";
		return new TypedValue((String) leftOperand + rightOperand);
	}

	if (leftOperand instanceof String) {
		return new TypedValue(
				leftOperand + (rightOperand == null ? "null" : convertTypedValueToString(operandTwoValue, state)));
	}

	if (rightOperand instanceof String) {
		return new TypedValue(
				(leftOperand == null ? "null" : convertTypedValueToString(operandOneValue, state)) + rightOperand);
	}

	return state.operate(Operation.ADD, leftOperand, rightOperand);
}
 
Example 14
@Override
protected Object outOfScopeValue() {
    BigInteger I = BigInteger.valueOf(Long.MAX_VALUE);
    I = I.add(BigInteger.ONE);
    return I;
}
 
Example 15
public static BigInteger branchingFactor(GameState gs, int player) throws Exception {
    BigInteger n = BigInteger.valueOf(0);
    PlayerActionGenerator pag = new PlayerActionGenerator(gs, player);
    while(pag.getNextAction(-1)!=null) n = n.add(BigInteger.ONE);
    return n;
}
 
Example 16
/**
 * Convert a list of Numeric Compacted codewords from Base 900 to Base 10.
 *
 * @param codewords The array of codewords
 * @param count     The number of codewords
 * @return The decoded string representing the Numeric data.
 */
/*
   EXAMPLE
   Encode the fifteen digit numeric string 000213298174000
   Prefix the numeric string with a 1 and set the initial value of
   t = 1 000 213 298 174 000
   Calculate codeword 0
   d0 = 1 000 213 298 174 000 mod 900 = 200

   t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082
   Calculate codeword 1
   d1 = 1 111 348 109 082 mod 900 = 282

   t = 1 111 348 109 082 div 900 = 1 234 831 232
   Calculate codeword 2
   d2 = 1 234 831 232 mod 900 = 632

   t = 1 234 831 232 div 900 = 1 372 034
   Calculate codeword 3
   d3 = 1 372 034 mod 900 = 434

   t = 1 372 034 div 900 = 1 524
   Calculate codeword 4
   d4 = 1 524 mod 900 = 624

   t = 1 524 div 900 = 1
   Calculate codeword 5
   d5 = 1 mod 900 = 1
   t = 1 div 900 = 0
   Codeword sequence is: 1, 624, 434, 632, 282, 200

   Decode the above codewords involves
     1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 +
   632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000

   Remove leading 1 =>  Result is 000213298174000
 */
private static String decodeBase900toBase10(int[] codewords, int count) throws FormatException {
  BigInteger result = BigInteger.ZERO;
  for (int i = 0; i < count; i++) {
    result = result.add(EXP900[count - i - 1].multiply(BigInteger.valueOf(codewords[i])));
  }
  String resultString = result.toString();
  if (resultString.charAt(0) != '1') {
    throw FormatException.getFormatInstance();
  }
  return resultString.substring(1);
}
 
Example 17
Source Project: bistoury   File: OpPlus.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
    SpelNodeImpl leftOp = getLeftOperand();
    SpelNodeImpl rightOp = getRightOperand();

    if (rightOp == null) {  // if only one operand, then this is unary plus
        Object operandOne = leftOp.getValueInternal(state).getValue();
        if (operandOne instanceof Number) {
            if (operandOne instanceof Double) {
                this.exitTypeDescriptor = "D";
            } else if (operandOne instanceof Float) {
                this.exitTypeDescriptor = "F";
            } else if (operandOne instanceof Long) {
                this.exitTypeDescriptor = "J";
            } else if (operandOne instanceof Integer) {
                this.exitTypeDescriptor = "I";
            }
            return new TypedValue(operandOne);
        }
        return state.operate(Operation.ADD, operandOne, null);
    }

    TypedValue operandOneValue = leftOp.getValueInternal(state);
    Object leftOperand = operandOneValue.getValue();
    TypedValue operandTwoValue = rightOp.getValueInternal(state);
    Object rightOperand = operandTwoValue.getValue();

    if (leftOperand instanceof Number && rightOperand instanceof Number) {
        Number leftNumber = (Number) leftOperand;
        Number rightNumber = (Number) rightOperand;

        if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) {
            BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
            BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
            return new TypedValue(leftBigDecimal.add(rightBigDecimal));
        } else if (leftNumber instanceof Double || rightNumber instanceof Double) {
            this.exitTypeDescriptor = "D";
            return new TypedValue(leftNumber.doubleValue() + rightNumber.doubleValue());
        } else if (leftNumber instanceof Float || rightNumber instanceof Float) {
            this.exitTypeDescriptor = "F";
            return new TypedValue(leftNumber.floatValue() + rightNumber.floatValue());
        } else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger) {
            BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
            BigInteger rightBigInteger = NumberUtils.convertNumberToTargetClass(rightNumber, BigInteger.class);
            return new TypedValue(leftBigInteger.add(rightBigInteger));
        } else if (leftNumber instanceof Long || rightNumber instanceof Long) {
            this.exitTypeDescriptor = "J";
            return new TypedValue(leftNumber.longValue() + rightNumber.longValue());
        } else if (CodeFlow.isIntegerForNumericOp(leftNumber) || CodeFlow.isIntegerForNumericOp(rightNumber)) {
            this.exitTypeDescriptor = "I";
            return new TypedValue(leftNumber.intValue() + rightNumber.intValue());
        } else {
            // Unknown Number subtypes -> best guess is double addition
            return new TypedValue(leftNumber.doubleValue() + rightNumber.doubleValue());
        }
    }

    if (leftOperand instanceof String && rightOperand instanceof String) {
        this.exitTypeDescriptor = "Ljava/lang/String";
        return new TypedValue((String) leftOperand + rightOperand);
    }

    if (leftOperand instanceof String) {
        return new TypedValue(
                leftOperand + (rightOperand == null ? "null" : convertTypedValueToString(operandTwoValue, state)));
    }

    if (rightOperand instanceof String) {
        return new TypedValue(
                (leftOperand == null ? "null" : convertTypedValueToString(operandOneValue, state)) + rightOperand);
    }

    return state.operate(Operation.ADD, leftOperand, rightOperand);
}
 
Example 18
Source Project: tddl5   File: ArithmeticAddExpression.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public BigInteger calculate(BigInteger bigint1, BigInteger bigint2) {
    if (bigint1 == null || bigint2 == null) return null;
    return bigint1.add(bigint2);
}
 
Example 19
Source Project: nuls-v2   File: AccountStateCmd.java    License: MIT License 4 votes vote down vote up
/**
 * 获取账户资产余额
 * get user account balance
 *
 * @param params
 * @return
 */
@CmdAnnotation(cmd = CmdConstant.CMD_GET_BALANCE, version = 1.0,
        description = "获取账户资产(已入区块)")
@Parameters(value = {
        @Parameter(parameterName = "chainId", requestType = @TypeDescriptor(value = int.class), parameterValidRange = "[1-65535]", parameterDes = "运行链Id,取值区间[1-65535]"),
        @Parameter(parameterName = "assetChainId", requestType = @TypeDescriptor(value = int.class), parameterValidRange = "[1-65535]", parameterDes = "资产链Id,取值区间[1-65535]"),
        @Parameter(parameterName = "assetId", requestType = @TypeDescriptor(value = int.class), parameterValidRange = "[1-65535]", parameterDes = "资产Id,取值区间[1-65535]"),
        @Parameter(parameterName = "address", requestType = @TypeDescriptor(value = String.class), parameterDes = "资产所在地址")
})
@ResponseData(name = "返回值", description = "返回一个Map对象",
        responseType = @TypeDescriptor(value = Map.class, mapKeys = {
                @Key(name = "total", valueType = BigInteger.class, description = "总金额"),
                @Key(name = "freeze", valueType = BigInteger.class, description = "冻结金额"),
                @Key(name = "available", valueType = String.class, description = "可用金额")
        })
)
public Response getBalance(Map params) {
    Integer chainId = (Integer) params.get("chainId");
    Integer assetChainId = (Integer) params.get("assetChainId");
    String address = LedgerUtil.getRealAddressStr((String) params.get("address"));
    Integer assetId = (Integer) params.get("assetId");
    if (!chainHanlder(chainId)) {
        return failed(LedgerErrorCode.CHAIN_INIT_FAIL);
    }
    LoggerUtil.logger(chainId).debug("chainId={},assetChainId={},address={},assetId={}", chainId, assetChainId, address, assetId);
    AccountState accountState = accountStateService.getAccountStateReCal(address, chainId, assetChainId, assetId);
    Map<String, Object> rtMap = new HashMap<>(5);
    rtMap.put("freeze", accountState.getFreezeTotal());
    rtMap.put("total", accountState.getTotalAmount());
    rtMap.put("available", accountState.getAvailableAmount());
    BigInteger permanentLocked = BigInteger.ZERO;
    BigInteger timeHeightLocked = BigInteger.ZERO;
    for (FreezeLockTimeState freezeLockTimeState : accountState.getFreezeLockTimeStates()) {
        if (LedgerUtil.isPermanentLock(freezeLockTimeState.getLockTime())) {
            permanentLocked = permanentLocked.add(freezeLockTimeState.getAmount());
        } else {
            timeHeightLocked = timeHeightLocked.add(freezeLockTimeState.getAmount());
        }
    }
    for (FreezeHeightState freezeHeightState : accountState.getFreezeHeightStates()) {
        timeHeightLocked = timeHeightLocked.add(freezeHeightState.getAmount());
    }
    rtMap.put("permanentLocked", permanentLocked);
    rtMap.put("timeHeightLocked", timeHeightLocked);
    Response response = success(rtMap);
    return response;
}
 
Example 20
Source Project: RipplePower   File: SimpleBigDecimal.java    License: Apache License 2.0 4 votes vote down vote up
public String toString()
{
    if (scale == 0)
    {
        return bigInt.toString();
    }

    BigInteger floorBigInt = floor();
    
    BigInteger fract = bigInt.subtract(floorBigInt.shiftLeft(scale));
    if (bigInt.signum() == -1)
    {
        fract = ECConstants.ONE.shiftLeft(scale).subtract(fract);
    }

    if ((floorBigInt.signum() == -1) && (!(fract.equals(ECConstants.ZERO))))
    {
        floorBigInt = floorBigInt.add(ECConstants.ONE);
    }
    String leftOfPoint = floorBigInt.toString();

    char[] fractCharArr = new char[scale];
    String fractStr = fract.toString(2);
    int fractLen = fractStr.length();
    int zeroes = scale - fractLen;
    for (int i = 0; i < zeroes; i++)
    {
        fractCharArr[i] = '0';
    }
    for (int j = 0; j < fractLen; j++)
    {
        fractCharArr[zeroes + j] = fractStr.charAt(j);
    }
    String rightOfPoint = new String(fractCharArr);

    StringBuffer sb = new StringBuffer(leftOfPoint);
    sb.append(".");
    sb.append(rightOfPoint);

    return sb.toString();
}