/// <summary> /// Number of surjective functions from N to K where |N|=n and |K|=k, k!{n k}. /// </summary> public static BigInteger Stirling2KF(BigInteger n, BigInteger k) { if (n > int.MaxValue) { throw new OverflowException(); } if (n < 0 || k < 0) { return(0); } if (k > n) { return(0); } int smallN = (int)n; BigInteger sum = 0; for (BigInteger j = 0; j <= k; j++) { sum += AlternateSign(Binomial(k, j).Top *BigInteger.Pow(j, smallN), k - j); } return(sum); }
public byte[] BlindData(Dictionary <string, object> blindKey, Dictionary <string, object> signKey, byte[] data) { var r = BigInt.Parse(blindKey.GetString("r")); var e = BigInt.Parse(signKey.GetString("e")); var n = BigInt.Parse(signKey.GetString("n")); var multiplier = BigInt.Pow(r, (int)e); var m = new BigInt(data); var result = BigInt.ModPow(m * multiplier, 1, n); return(result.ToByteArray()); }
public async Task <string> CheckTransactionAndFindHackerContractAddr(string transaction, string contractAddr, decimal flagSumEth) { var trace = await TransactionTracer.TraceTransactionAsync(transaction, parityRpcUrl); if (trace == null) { log.Info($"Refused addr {contractAddr} hacking transaction candidate {transaction}: transaction trace returned zero result"); return(null); } var moneyTransfersDict = trace .Select(item => item.action) .Select(action => new { fromAddr = action.fromAddr?.ToLowerInvariant(), toAddr = action.toAddr?.ToLowerInvariant(), sum = BigInteger.Parse("0" + (action.value?.Substring(2) ?? "0"), NumberStyles.AllowHexSpecifier) }) .Where(mt => mt.fromAddr == contractAddr && mt.sum > 0) .GroupBy(mt => mt.toAddr) .ToDictionary(grouping => grouping.Key, grouping => grouping); if (moneyTransfersDict.Count != 1) { log.Info($"Refused addr {contractAddr} hacking transaction candidate {transaction}: has {moneyTransfersDict.Count} money recepients, but expected 1"); return(null); } var hacker = moneyTransfersDict.First(); var hackerAddr = hacker.Key; BigInteger receivedSumInWei = 0; foreach (var mt in hacker.Value) { receivedSumInWei += mt.sum; } var ten = new BigInteger(10); var weisInEth = BigInteger.Pow(ten, 18); var flagSumWei = new BigInteger(flagSumEth) * weisInEth; if (receivedSumInWei < flagSumWei) { log.Info($"Refused addr {contractAddr} hacking transaction candidate {transaction}: hacker contract address {hackerAddr} received {receivedSumInWei} wei < expected {flagSumEth} eth"); return(null); } return(hackerAddr); }
public static BigInt Power(this BigInt self, long exp) { if (exp < 0) { throw ExceptionUtils.MakeArgumentOutOfRangeException(nameof(exp), exp, "Must be at least 0"); } // redirection possible? if (exp <= int.MaxValue) { return(BigInt.Pow(self, (int)exp)); } // manual implementation if (self.IsOne) { return(BigInt.One); } else if (self.IsZero) { return(BigInt.Zero); } else if (self == BigInt.MinusOne) { if (exp % 2 == 0) { return(BigInt.One); } else { return(BigInt.MinusOne); } } BigInt result = BigInt.One; while (exp != 0) { if (exp % 2 != 0) { result *= self; } exp >>= 1; self *= self; } return(result); }
/// <summary> /// Returns phi(n), the totient function. /// </summary> public static BigInteger Totient(BigInteger n) { BigInteger result = 1; if (n <= 0) { return(0); } foreach (var factor in PrimeFactors(n)) { result *= BigInteger.Pow(factor.First, factor.Second - 1) * (factor.First - 1); } return(result); }
public String ToDecimalString(int maxDigits) { string s = this.mantissa.ToString(); int digits = (this.mantissa >= 0) ? s.Length : s.Length - 1; BIM max = BIM.Pow(10, maxDigits); BIM min = -max; if (this.exponent >= 0) { if (maxDigits < digits || maxDigits - digits < this.exponent) { return(String.Format("{0}.0", (this.mantissa >= 0) ? max.ToString() : min.ToString())); } else { return(String.Format("{0}{1}.0", s, new string('0', this.exponent))); } } else { int exp = -this.exponent; if (exp < digits) { int intDigits = digits - exp; if (maxDigits < intDigits) { return(String.Format("{0}.0", (this.mantissa >= 0) ? max.ToString() : min.ToString())); } else { int fracDigits = Math.Min(maxDigits, digits - intDigits); return(String.Format("{0}.{1}", s.Substring(0, intDigits), s.Substring(intDigits, fracDigits))); } } else { int fracDigits = Math.Min(maxDigits, digits); return(String.Format("0.{0}{1}", new string('0', exp - fracDigits), s.Substring(0, fracDigits))); } } }
public static BigInteger Eulerian(BigInteger n, BigInteger k) { if (n > int.MaxValue) { throw new OverflowException(); } if (k > n) { return(0); } int smallN = (int)n; BigInteger sum = 0; for (BigInteger j = 0; j <= k; j++) { sum += AlternateSign(Binomial(n + 1, j).Top *BigInteger.Pow(k + 1 - j, smallN), j); } return(sum); }
public BigInteger Power(int exp) { return(new BigInteger(BigInt.Pow(Value, exp))); }
public static BigInt Power(this BigInt self, int exp) { return(BigInt.Pow(self, exp)); }
public static BigFloat FromString(String s) { /* * String must be either of the format [-]0x^.^e*f*e* * or of the special value formats: 0NaN*e* 0nan*e* 0+oo*e* 0-oo*e* * Where ^ indicates a hexadecimal value and * indicates an integer value */ int posLastE = s.LastIndexOf('e'); int expSize = int.Parse(s.Substring(posLastE + 1)); if (expSize <= 1) { throw new FormatException("Exponent size must be greater than 1"); } int posLastF = s.LastIndexOf('f'); int posSig = posLastF + 1; if (posLastF == -1) { //NaN, +oo, -oo posSig = 4; } int sigSize = int.Parse(s.Substring(posSig, posLastE - posSig)); if (sigSize <= 1) { throw new FormatException("Significand size must be greater than 1"); } if (posLastF == -1) { //NaN, +oo, -oo return(new BigFloat(s.Substring(1, 3), sigSize, expSize)); } bool isSignBitSet = s[0] == '-'; int posX = s.IndexOf('x'); int posSecondLastE = s.LastIndexOf('e', posLastE - 1); string hexSig = s.Substring(posX + 1, posSecondLastE - (posX + 1)); BIM oldExp = BIM.Parse(s.Substring(posSecondLastE + 1, posLastF - (posSecondLastE + 1))); string binSig = string.Join(string.Empty, hexSig.Select( c => (c == '.' ? "." : Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0')) ) ); int posDec = binSig.IndexOf('.'); binSig = binSig.Remove(posDec, 1); int posFirstOne = binSig.IndexOf('1'); int posLastOne = binSig.LastIndexOf('1'); if (posFirstOne == -1) { return(new BigFloat(isSignBitSet, 0, 0, sigSize, expSize)); } binSig = binSig.Substring(posFirstOne, posLastOne - posFirstOne + 1); BIM bias = BIM.Pow(2, expSize - 1) - 1; BIM upperBound = 2 * bias + 1; BIM newExp = 4 * oldExp + bias + (posDec - posFirstOne - 1); if (newExp <= 0) { if (-newExp <= (sigSize - 1) - binSig.Length) { binSig = new string('0', (int)-newExp) + binSig; newExp = 0; } } else { binSig = binSig.Substring(1); } if (newExp < 0 || newExp >= upperBound) { throw new FormatException("The given exponent cannot fit in the bit size " + expSize); } binSig = binSig.PadRight(sigSize - 1, '0'); if (binSig.Length > sigSize - 1) { throw new FormatException("The given significand cannot fit in the bit size " + (sigSize - 1)); } BIM newSig = 0; foreach (char b in binSig) { if (b != '.') { newSig <<= 1; newSig += b - '0'; } } return(new BigFloat(isSignBitSet, newSig, newExp, sigSize, expSize)); }
public static BigFloat operator *(BigFloat x, BigFloat y) { Contract.Requires(x.exponentSize == y.exponentSize); Contract.Requires(x.significandSize == y.significandSize); if (x.value == "NaN" || y.value == "NaN" || (x.value == "+oo" || x.value == "-oo") && y.IsZero || (y.value == "+oo" || y.value == "-oo") && x.IsZero) { return(new BigFloat("NaN", x.significandSize, x.exponentSize)); } if (x.value != "" || y.value != "") { bool xSignBitSet = x.value == "" ? x.isSignBitSet : x.value[0] == '-'; bool ySignBitSet = y.value == "" ? y.isSignBitSet : y.value[0] == '-'; return(new BigFloat((xSignBitSet ^ ySignBitSet ? "-" : "+") + "oo", x.significandSize, x.exponentSize)); } BIM xsig = x.significand, ysig = y.significand; BIM xexp = x.exponent, yexp = y.exponent; BIM hiddenBitPow = BIM.Pow(2, x.significandSize - 1); if (xexp > 0) { xsig += hiddenBitPow; } else { ++xexp; } if (yexp > 0) { ysig += hiddenBitPow; } else { ++yexp; } ysig *= xsig; yexp += xexp - (BIM.Pow(2, x.exponentSize - 1) - 1) - (x.significandSize - 1); while (ysig >= hiddenBitPow * 2 || yexp <= 0) { ysig >>= 1; ++yexp; } while (ysig < hiddenBitPow && yexp > 1) { ysig <<= 1; --yexp; } if (ysig < hiddenBitPow) { yexp = 0; } else { ysig -= hiddenBitPow; } if (yexp >= BIM.Pow(2, x.exponentSize) - 1) { return(new BigFloat(x.isSignBitSet ^ y.isSignBitSet ? "-oo" : "+oo", x.significandSize, x.exponentSize)); } return(new BigFloat(x.isSignBitSet ^ y.isSignBitSet, ysig, yexp, x.significandSize, x.exponentSize)); }
public static BigFloat operator +(BigFloat x, BigFloat y) { Contract.Requires(x.exponentSize == y.exponentSize); Contract.Requires(x.significandSize == y.significandSize); if (x.value != "" || y.value != "") { if (x.value == "NaN" || y.value == "NaN" || x.value == "+oo" && y.value == "-oo" || x.value == "-oo" && y.value == "+oo") { return(new BigFloat("NaN", x.significandSize, x.exponentSize)); } if (x.value != "") { return(new BigFloat(x.value, x.significandSize, x.exponentSize)); } return(new BigFloat(y.value, y.significandSize, y.exponentSize)); } if (x.exponent > y.exponent) { BigFloat temp = x; x = y; y = temp; } BIM xsig = x.significand, ysig = y.significand; BIM xexp = x.exponent, yexp = y.exponent; if (yexp - xexp > x.significandSize) //One of the numbers is relatively insignificant { return(new BigFloat(y.isSignBitSet, y.significand, y.exponent, y.significandSize, y.exponentSize)); } BIM hiddenBitPow = BIM.Pow(2, x.significandSize - 1); if (xexp > 0) { xsig += hiddenBitPow; } else { ++xexp; } if (yexp > 0) { ysig += hiddenBitPow; } else { ++yexp; } if (x.isSignBitSet) { xsig = -xsig; } if (y.isSignBitSet) { ysig = -ysig; } xsig >>= (int)(yexp - xexp); //Guaranteed to fit in a 32-bit integer ysig += xsig; bool isNeg = ysig < 0; ysig = BIM.Abs(ysig); if (ysig == 0) { return(new BigFloat(x.isSignBitSet && y.isSignBitSet, 0, 0, x.significandSize, x.exponentSize)); } if (ysig >= hiddenBitPow * 2) { ysig >>= 1; ++yexp; } while (ysig < hiddenBitPow && yexp > 1) { ysig <<= 1; --yexp; } if (ysig < hiddenBitPow) { yexp = 0; } else { ysig -= hiddenBitPow; } if (yexp >= BIM.Pow(2, x.exponentSize) - 1) { return(new BigFloat(y.isSignBitSet ? "-oo" : "+oo", x.significandSize, x.exponentSize)); } return(new BigFloat(isNeg, ysig, yexp, x.significandSize, x.exponentSize)); }
//////////////////////////////////////////////////////////////////////////// // Conversion operations // ``floor`` rounds towards negative infinity (like SMT-LIBv2's to_int). /// <summary> /// Computes the floor and ceiling of this BigFloat. Note the choice of rounding towards negative /// infinity rather than zero for floor is because SMT-LIBv2's to_int function floors this way. /// </summary> /// <param name="floor">Floor (rounded towards negative infinity)</param> /// <param name="ceiling">Ceiling (rounded towards positive infinity)</param> public void FloorCeiling(out BIM floor, out BIM ceiling) { Contract.Requires(value == ""); BIM sig = significand; BIM exp = exponent; BIM hiddenBitPow = BIM.Pow(2, significandSize - 1); if (exponent > 0) { sig += hiddenBitPow; } else { ++exp; } exp -= (BIM.Pow(2, exponentSize - 1) - 1) + (significandSize - 1); if (exp >= BIM.Zero) { while (exp >= int.MaxValue) { sig <<= int.MaxValue; exp -= int.MaxValue; } sig <<= (int)exp; floor = ceiling = (isSignBitSet ? -sig : sig); } else { exp = -exp; if (exp > significandSize) { if (sig == 0) { floor = ceiling = 0; } else { ceiling = isSignBitSet ? 0 : 1; floor = ceiling - 1; } } else { BIM frac = sig & ((BIM.One << (int)exp) - 1); sig >>= (int)exp; //Guaranteed to fit in a 32-bit integer if (frac == 0) { floor = ceiling = (isSignBitSet ? -sig : sig); } else { ceiling = isSignBitSet ? -sig : sig + 1; floor = ceiling - 1; } } } }
public override string /*!*/ ToString() { Contract.Ensures(Contract.Result <string>() != null); if (value == "") { byte[] sigBytes = significand.ToByteArray(); StringBuilder binSig = new StringBuilder(); if (exponent == 0) { binSig.Append('0'); } else { binSig.Append('1'); //hidden bit } for (int i = significandSize - 2; i >= 0; --i) { //little endian if (i / 8 < sigBytes.Length) { binSig.Append((char)('0' + ((sigBytes[i / 8] >> (i % 8)) & 1))); } else { binSig.Append('0'); } } BIM bias = BIM.Pow(2, exponentSize - 1) - 1; if (exponent == 0) { --bias; } int moveDec = ((int)((exponent - bias) % 4) + 4) % 4; BIM finalExp = (exponent - bias - moveDec) / 4; string leftBinSig = binSig.ToString().Substring(0, moveDec + 1); string rightBinSig = binSig.ToString().Substring(moveDec + 1); leftBinSig = new string('0', 4 - leftBinSig.Length % 4) + leftBinSig; rightBinSig = rightBinSig + new string('0', 4 - rightBinSig.Length % 4); StringBuilder leftHexSig = new StringBuilder(); StringBuilder rightHexSig = new StringBuilder(); for (int i = 0; i < leftBinSig.Length / 4; ++i) { leftHexSig.AppendFormat("{0:X}", Convert.ToByte(leftBinSig.Substring(i * 4, 4), 2)); } for (int i = 0; i < rightBinSig.Length / 4; ++i) { rightHexSig.AppendFormat("{0:X}", Convert.ToByte(rightBinSig.Substring(i * 4, 4), 2)); } return(String.Format("{0}0x{1}.{2}e{3}f{4}e{5}", isSignBitSet ? "-" : "", leftHexSig, rightHexSig, finalExp, significandSize, exponentSize)); } return(String.Format("0{0}{1}e{2}", value, significandSize, exponentSize)); }