public AsymmetricCipherKeyPair GenerateKeyPair() { SecureRandom random = param.Random; Gost3410Parameters gost3410Params = param.Parameters; BigInteger q = gost3410Params.Q; BigInteger x; do { x = new BigInteger(256, random); } while (x.Sign < 1 || x.CompareTo(q) >= 0); BigInteger p = gost3410Params.P; BigInteger a = gost3410Params.A; // calculate the public key. BigInteger y = a.ModPow(x, p); if (param.PublicKeyParamSet != null) { return new AsymmetricCipherKeyPair( new Gost3410PublicKeyParameters(y, param.PublicKeyParamSet), new Gost3410PrivateKeyParameters(x, param.PublicKeyParamSet)); } return new AsymmetricCipherKeyPair( new Gost3410PublicKeyParameters(y, gost3410Params), new Gost3410PrivateKeyParameters(x, gost3410Params)); }
static void Main() { string[] inputSequence = Console.ReadLine().Split(' '); BigInteger[] numbers = new BigInteger[200]; for (int i = 0; i < inputSequence.Length; i++) { numbers[i] = int.Parse(inputSequence[i]); } int j = 1; BigInteger absoluteDiff = 0; BigInteger resultEvenAbsoluteDifferences = 0; while(j < inputSequence.Length) { if (numbers[j] < numbers[j - 1]) { absoluteDiff = numbers[j - 1] - numbers[j]; }else { absoluteDiff = numbers[j] - numbers[j - 1]; } if(absoluteDiff % 2 == 0) { j += 2; resultEvenAbsoluteDifferences += absoluteDiff; } else { j += 1; } } Console.WriteLine(resultEvenAbsoluteDifferences); }
public SecP384R1FieldElement(BigInteger x) { if (x == null || x.SignValue < 0 || x.CompareTo(Q) >= 0) throw new ArgumentException("value invalid for SecP384R1FieldElement", "x"); this.x = SecP384R1Field.FromBigInteger(x); }
static void Main() { Console.Write("vavedi N:"); int numberN = int.Parse(Console.ReadLine()); Console.Write("vavedi K:"); int numberK = int.Parse(Console.ReadLine()); if (numberN > 1 && numberK > numberN) { var factorialN = new BigInteger(1); for (var i = 1; i <= numberN; i++) { factorialN *= i; } Console.WriteLine("Factorial n = {0}", factorialN); var factorialK = new BigInteger(1); for (var j = 1; j <= numberK; j++) { factorialK *= j; } Console.WriteLine("Factorial k = {0}", factorialK); var nAndK = new BigInteger(1); nAndK = factorialN/factorialK; Console.WriteLine("N!/K!={0}", nAndK); } else { Console.WriteLine("N > 1 and K > N"); } }
static bool IsPrime(BigInteger n) { bool isPrime = true; if(n==0||n==1) { return false; } else if(n==2||n==3) { return true; } else if(n<100&&n>3) { for(int s=2;s<n;s++) { if (n % s == 0) isPrime = false; } return isPrime; } else { for (BigInteger i = 3; (i * i) <= n; i+=2) { if (n%i==0) { isPrime = false; break; } } return isPrime; } }
public SecT113FieldElement(BigInteger x) { if (x == null || x.SignValue < 0) throw new ArgumentException("value invalid for SecT113FieldElement", "x"); this.x = SecT113Field.FromBigInteger(x); }
/// <param name="n">The modulus.</param> /// <param name="e">The public exponent.</param> public RsaPublicBcpgKey( BigInteger n, BigInteger e) { this.n = new MPInteger(n); this.e = new MPInteger(e); }
static void TenToAny(BigInteger decimalNumber) { List<BigInteger> number = new List<BigInteger>(); while (decimalNumber > 0) { number.Add(decimalNumber % 9); decimalNumber /= 9; } for (int i = number.Count - 1; i >= 0; i--) { if (number[i] < 9 && number[i] >= 0) { if (number[i] == 0) { Console.Write("LON+"); } if (number[i] == 1) { Console.Write("VK-"); } if (number[i] == 2) { Console.Write("*ACAD"); } if (number[i] == 3) { Console.Write("^MIM"); } if (number[i] == 4) { Console.Write("ERIK|"); } if (number[i] == 5) { Console.Write("SEY&"); } if (number[i] == 6) { Console.Write("EMY>>"); } if (number[i] == 7) { Console.Write("/TEL"); } if (number[i] == 8) { Console.Write("<<DON"); } } else { Console.Write(number[i]); } } }
/* * "Shamir's Trick", originally due to E. G. Straus * (Addition chains of vectors. American Mathematical Monthly, * 71(7):806-808, Aug./Sept. 1964) * * Input: The points P, Q, scalar k = (km?, ... , k1, k0) * and scalar l = (lm?, ... , l1, l0). * Output: R = k * P + l * Q. * 1: Z <- P + Q * 2: R <- O * 3: for i from m-1 down to 0 do * 4: R <- R + R {point doubling} * 5: if (ki = 1) and (li = 0) then R <- R + P end if * 6: if (ki = 0) and (li = 1) then R <- R + Q end if * 7: if (ki = 1) and (li = 1) then R <- R + Z end if * 8: end for * 9: return R */ public static ECPoint ShamirsTrick(ECPoint p, BigInteger k, ECPoint q, BigInteger l) { if (!p.Curve.Equals(q.Curve)) throw new ArgumentException("P and Q must be on same curve"); return ImplShamirsTrick(p, k, q, l); }
public void IntegerTimesZeroIsZero() { var a = new BigInteger(234); Assert.AreEqual(BigInteger.Zero, a * BigInteger.Zero); Assert.AreEqual(BigInteger.Zero, BigInteger.Zero * a); }
protected override BigInteger GenerateSearchBase (int bits, object Context) { if (Context == null) throw new ArgumentNullException ("Context"); BigInteger ret = new BigInteger ((BigInteger)Context); ret.setBit (0); return ret; }
public void ZeroPlusZeroIsZero() { var a = new BigInteger(0); var b = new BigInteger("0"); Assert.AreEqual(BigInteger.Zero, a + b); }
public void AdditionIsCommutative() { var a = new BigInteger("2342452452435235098091834098018"); var b = new BigInteger("102938209095450980895402985098560727234098123345"); Assert.AreEqual(a + b, b + a); }
public RSAKeyPair(BigInteger e, BigInteger d, BigInteger n, BigInteger u, BigInteger p, BigInteger q) { _publickey = new RSAPublicKey(e, n); _d = d; _u = u; _p = p; _q = q; }
public void SetupCrypto(BigInteger key) { byte[] ServerDecryptionKey = { 0xC2, 0xB3, 0x72, 0x3C, 0xC6, 0xAE, 0xD9, 0xB5, 0x34, 0x3C, 0x53, 0xEE, 0x2F, 0x43, 0x67, 0xCE }; byte[] ServerEncryptionKey = { 0xCC, 0x98, 0xAE, 0x04, 0xE8, 0x97, 0xEA, 0xCA, 0x12, 0xDD, 0xC0, 0x93, 0x42, 0x91, 0x53, 0x57 }; HMACSHA1 decryptHMAC = new HMACSHA1(ServerDecryptionKey); HMACSHA1 encryptHMAC = new HMACSHA1(ServerEncryptionKey); var decryptHash = decryptHMAC.ComputeHash(key.GetBytes()); var encryptHash = encryptHMAC.ComputeHash(key.GetBytes()); const int dropN = 1024; //1000 before WoTLK, 1024 now var buf = new byte[dropN]; ClientConnection.Decrypt = new ARC4(decryptHash); ClientConnection.Encrypt = new ARC4(encryptHash); ClientConnection.Decrypt.Process(buf, 0, buf.Length); ClientConnection.Encrypt.Process(buf, 0, buf.Length); }
// takes two numbers, converts them to arrays, whose index 0 is the last digit of // the numbers, then adds the elements up, then converts the result array back to a number static BigInteger AddAsArray(BigInteger first, BigInteger second) { BigInteger[] firstArr = NumberToArray(first); BigInteger[] secondArr = NumberToArray(second); BigInteger[] resultArr = new BigInteger[Math.Max(firstArr.Length, secondArr.Length)]; if (firstArr.Length >= secondArr.Length) { for (int i = 0; i < secondArr.Length; i++) { resultArr[i] = firstArr[i] + secondArr[i]; } for (int i = secondArr.Length; i < firstArr.Length; i++) { resultArr[i] = firstArr[i]; } } else { for (int i = 0; i < firstArr.Length; i++) { resultArr[i] = firstArr[i] + secondArr[i]; } for (int i = firstArr.Length; i < secondArr.Length; i++) { resultArr[i] = secondArr[i]; } } return ArrToNumber(resultArr); }
//converts an array, whose index 0 is the last digit of a number, to the number. static BigInteger ArrToNumber(BigInteger[] arr) { Array.Reverse(arr); string numberString = string.Join("", arr); BigInteger result = BigInteger.Parse(numberString); return result; }
public IssuerAndSerialNumber( X509Name name, BigInteger serialNumber) { this.name = name; this.serialNumber = new DerInteger(serialNumber); }
private static ECPoint ImplShamirsTrick(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { int m = System.Math.Max(k.BitLength, l.BitLength); ECPoint Z = P.Add(Q); ECPoint R = P.Curve.Infinity; for (int i = m - 1; i >= 0; --i) { R = R.Twice(); if (k.TestBit(i)) { if (l.TestBit(i)) { R = R.Add(Z); } else { R = R.Add(P); } } else { if (l.TestBit(i)) { R = R.Add(Q); } } } return R; }
public void Add_neg_pos_same_mag() { BigInteger x = new BigInteger(-1, new uint[] { 0x3 }); BigInteger y = new BigInteger(1, new uint[] { 0x3 }); BigInteger z = x.Add(y); Expect(z.IsZero); }
public void Add_neg_pos_second_larger_mag() { BigInteger x = new BigInteger(-1, new uint[] { 0x3 }); BigInteger y = new BigInteger(1, new uint[] { 0x5 }); BigInteger z = x.Add(y); Expect(SameValue(z, 1, new uint[] { 0x2 })); }
static void Main() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; BigInteger q4 = BigInteger.Parse(Console.ReadLine()); BigInteger q3 = BigInteger.Parse(Console.ReadLine()); BigInteger q2 = BigInteger.Parse(Console.ReadLine()); BigInteger q1 = BigInteger.Parse(Console.ReadLine()); BigInteger nextQNumber = 0; BigInteger tempNumber = 0; int rows = int.Parse(Console.ReadLine()); int columns = int.Parse(Console.ReadLine()); BigInteger[] matrix = new BigInteger[rows * columns]; matrix [0]= q4; matrix [1]= q3; matrix [2]= q2; matrix [3]= q1; for (int i = 4; i < rows*columns; i++) { matrix [i] = matrix [i-1]+matrix [i-2]+matrix [i-3]+matrix [i-4]; } int counter = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { Console.Write(matrix[counter]); Console.Write(" "); counter++; } Console.WriteLine(); } }
public void SetPublic(string modulus, string exponent) { if (string.IsNullOrEmpty(modulus) || string.IsNullOrEmpty(exponent)) throw new Exception("Invalid RSA public key"); Modulus = new BigInteger(modulus, 16); Exponent = new BigInteger(exponent, 16); }
/// <summary> /// Returns the number of bits in the binary representation of this which differ from the sign bit. /// <para>Use BitLength(0) if you want to know the length of the binary value in bits. /// If this is positive the result is equivalent to the number of bits set in the binary representation of this. /// If this is negative the result is equivalent to the number of bits set in the binary representation of -this - 1.</para> /// </summary> internal static int BitCount(BigInteger Value) { int bCount = 0; if (Value._sign == 0) return 0; int i = Value.FirstNonzeroDigit; ; if (Value._sign > 0) { for (; i < Value._numberLength; i++) bCount += IntUtils.BitCount(Value._digits[i]); } else { // this digit absorbs the carry bCount += IntUtils.BitCount(-Value._digits[i]); for (i++; i < Value._numberLength; i++) bCount += IntUtils.BitCount(~Value._digits[i]); // We take the complement sum: bCount = (Value._numberLength << 5) - bCount; } return bCount; }
static void Main() { Console.WriteLine("How many digits will contain the first number ?"); int lengthOne = int.Parse(Console.ReadLine()); BigInteger[] numberOne = new BigInteger[lengthOne]; Console.WriteLine("Enter the digits of the number"); for (int i = lengthOne - 1; i > -1; i--) { numberOne[i] = BigInteger.Parse(Console.ReadLine()); } Console.WriteLine("How many digits will contain the second number ?"); int lengthTwo = int.Parse(Console.ReadLine()); BigInteger[] numberTwo = new BigInteger[lengthTwo]; Console.WriteLine("Enter the digits of the number"); for (int i = lengthTwo - 1; i > -1; i--) { numberTwo[i] = BigInteger.Parse(Console.ReadLine()); } BigInteger[] sum = SumNumber(numberOne, numberTwo); Console.WriteLine(); foreach (BigInteger i in sum) { Console.Write(i); } }
private static void CheckNumForNull(BigInteger[] array, int targetIndex) { if (array[targetIndex] < 0) { array[targetIndex] = 0; } }
public DHParameters( BigInteger p, BigInteger g, BigInteger q) : this(p, g, q, 0) { }
private static BigInteger CalculateScore(int heigth, int width, int[] moves, BigInteger[][] matrix) { BigInteger sumVisited = 0; int coeficient = Math.Max(heigth, width); int posX = 0; int posY = heigth - 1; for (int i = 0; i < moves.GetLength(0); i++) { int moveToX = moves[i] % coeficient; int moveToY = moves[i] / coeficient; int walkXFrom = Math.Min(moveToX, posX); int walkXTo = Math.Max(moveToX, posX); for (int j = walkXFrom; j <= walkXTo; j++) { sumVisited += matrix[posY][j]; matrix[posY][j] = 0; } posX = moveToX; int walkYFrom = Math.Min(moveToY, posY); int walkYTo = Math.Max(moveToY, posY); for (int j = walkYFrom; j <= walkYTo; j++) { sumVisited += matrix[j][posX]; matrix[j][posX] = 0; } posY = moveToY; } return sumVisited; }
/** * D.3.2 pg 101 * @see org.bouncycastle.math.ec.multiplier.ECMultiplier#multiply(org.bouncycastle.math.ec.ECPoint, java.math.BigInteger) */ public ECPoint Multiply(ECPoint p, BigInteger k, PreCompInfo preCompInfo) { // TODO Probably should try to add this // BigInteger e = k.Mod(n); // n == order of p BigInteger e = k; BigInteger h = e.Multiply(BigInteger.Three); ECPoint neg = p.Negate(); ECPoint R = p; for (int i = h.BitLength - 2; i > 0; --i) { R = R.Twice(); bool hBit = h.TestBit(i); bool eBit = e.TestBit(i); if (hBit != eBit) { R = R.Add(hBit ? p : neg); } } return R; }
private static void PortableDigitCount(BigInteger bi) { int kb=0; if(!bi.IsZero){ while(true){ if(bi.CompareTo((BigInteger)Int32.MaxValue)<=0) { int tmp = (int)bi; while (tmp > 0) { kb++; tmp /= 10; } kb=(kb == 0 ? 1 : kb); return kb; } BigInteger q=bi/(BigInteger)bidivisor; if(q.IsZero){ int b=(int)bi; while(b>0){ kb++; b/=10; } break; } else { kb+=4; bi=q; } } } else { kb=1; } return kb; }
public static void WriteECFieldElement(int fieldSize, BigInteger x, Stream output) { TlsUtilities.WriteOpaque8(SerializeECFieldElement(fieldSize, x), output); }
public RSA(BigInteger e, BigInteger p, BigInteger q) { E = e; N = p * q; SetPrivateKey(p, q); }
public void SetPrivateKey(BigInteger p, BigInteger q) { Trace.Assert(p * q == N); HasPrivateKey = true; _p = p; _q = q; }
private Block PrepareBlock() { BlockHeader parentHeader = _blockTree.Head; if (parentHeader == null) { return(null); } Block parent = _blockTree.FindBlock(parentHeader.Hash, false); UInt256 timestamp = _timestamp.EpochSeconds; UInt256 difficulty = _difficultyCalculator.Calculate(parent.Difficulty, parent.Timestamp, _timestamp.EpochSeconds, parent.Number + 1, parent.Ommers.Length > 0); BlockHeader header = new BlockHeader( parent.Hash, Keccak.OfAnEmptySequenceRlp, Address.Zero, difficulty, parent.Number + 1, parent.GasLimit, timestamp > parent.Timestamp ? timestamp : parent.Timestamp + 1, Encoding.UTF8.GetBytes("Nethermind")); header.TotalDifficulty = parent.TotalDifficulty + difficulty; if (_logger.IsDebug) { _logger.Debug($"Setting total difficulty to {parent.TotalDifficulty} + {difficulty}."); } var transactions = _txPool.GetPendingTransactions().OrderBy(t => t?.Nonce); // by nonce in case there are two transactions for the same account, TODO: test it List <Transaction> selected = new List <Transaction>(); BigInteger gasRemaining = header.GasLimit; if (_logger.IsDebug) { _logger.Debug($"Collecting pending transactions at min gas price {MinGasPriceForMining} and block gas limit {gasRemaining}."); } int total = 0; foreach (Transaction transaction in transactions) { total++; if (transaction == null) { throw new InvalidOperationException("Block transaction is null"); } if (transaction.GasPrice < MinGasPriceForMining) { if (_logger.IsTrace) { _logger.Trace($"Rejecting transaction - gas price ({transaction.GasPrice}) too low (min gas price: {MinGasPriceForMining}."); } continue; } if (transaction.GasLimit > gasRemaining) { if (_logger.IsTrace) { _logger.Trace($"Rejecting transaction - gas limit ({transaction.GasPrice}) more than remaining gas ({gasRemaining})."); } break; } selected.Add(transaction); gasRemaining -= transaction.GasLimit; } if (_logger.IsDebug) { _logger.Debug($"Collected {selected.Count} out of {total} pending transactions."); } Block block = new Block(header, selected, new BlockHeader[0]); header.TxRoot = block.CalculateTxRoot(); return(block); }
/// <inheritdoc/> public Target CalculateRetarget(uint firstBlockTime, Target firstBlockTarget, uint secondBlockTime, BigInteger targetLimit) { this.logger.LogTrace("({0}:{1},{2}:{3},{4}:{5},{6}:{7})", nameof(firstBlockTime), firstBlockTime, nameof(firstBlockTarget), firstBlockTarget, nameof(secondBlockTime), secondBlockTime, nameof(targetLimit), targetLimit); uint targetSpacing = TargetSpacingSeconds; uint actualSpacing = firstBlockTime > secondBlockTime ? firstBlockTime - secondBlockTime : targetSpacing; if (actualSpacing > targetSpacing * 10) actualSpacing = targetSpacing * 10; uint targetTimespan = RetargetIntervalMinutes * 60; uint interval = targetTimespan / targetSpacing; BigInteger target = firstBlockTarget.ToBigInteger(); long multiplyBy = (interval - 1) * targetSpacing + actualSpacing + actualSpacing; target = target.Multiply(BigInteger.ValueOf(multiplyBy)); long divideBy = (interval + 1) * targetSpacing; target = target.Divide(BigInteger.ValueOf(divideBy)); this.logger.LogTrace("The next target difficulty will be {0} times higher (easier to satisfy) than the previous target.", (double)multiplyBy / (double)divideBy); if ((target.CompareTo(BigInteger.Zero) <= 0) || (target.CompareTo(targetLimit) >= 1)) target = targetLimit; var finalTarget = new Target(target); this.logger.LogTrace("(-):'{0}'", finalTarget); return finalTarget; }
public Division(BigInteger bigInt1, BigInteger bigInt2) : base(bigInt1, bigInt2) { }
public static void WriteECParameter(BigInteger x, Stream output) { TlsUtilities.WriteOpaque8(BigIntegers.AsUnsignedByteArray(x), output); }
public static ECDomainParameters ReadECParameters(int[] namedCurves, byte[] ecPointFormats, Stream input) { try { byte curveType = TlsUtilities.ReadUint8(input); switch (curveType) { case ECCurveType.explicit_prime: { CheckNamedCurve(namedCurves, NamedCurve.arbitrary_explicit_prime_curves); BigInteger prime_p = ReadECParameter(input); BigInteger a = ReadECFieldElement(prime_p.BitLength, input); BigInteger b = ReadECFieldElement(prime_p.BitLength, input); byte[] baseEncoding = TlsUtilities.ReadOpaque8(input); BigInteger order = ReadECParameter(input); BigInteger cofactor = ReadECParameter(input); ECCurve curve = new FpCurve(prime_p, a, b, order, cofactor); ECPoint basePoint = DeserializeECPoint(ecPointFormats, curve, baseEncoding); return(new ECDomainParameters(curve, basePoint, order, cofactor)); } case ECCurveType.explicit_char2: { CheckNamedCurve(namedCurves, NamedCurve.arbitrary_explicit_char2_curves); int m = TlsUtilities.ReadUint16(input); byte basis = TlsUtilities.ReadUint8(input); if (!ECBasisType.IsValid(basis)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } int k1 = ReadECExponent(m, input), k2 = -1, k3 = -1; if (basis == ECBasisType.ec_basis_pentanomial) { k2 = ReadECExponent(m, input); k3 = ReadECExponent(m, input); } BigInteger a = ReadECFieldElement(m, input); BigInteger b = ReadECFieldElement(m, input); byte[] baseEncoding = TlsUtilities.ReadOpaque8(input); BigInteger order = ReadECParameter(input); BigInteger cofactor = ReadECParameter(input); ECCurve curve = (basis == ECBasisType.ec_basis_pentanomial) ? new F2mCurve(m, k1, k2, k3, a, b, order, cofactor) : new F2mCurve(m, k1, a, b, order, cofactor); ECPoint basePoint = DeserializeECPoint(ecPointFormats, curve, baseEncoding); return(new ECDomainParameters(curve, basePoint, order, cofactor)); } case ECCurveType.named_curve: { int namedCurve = TlsUtilities.ReadUint16(input); if (!NamedCurve.RefersToASpecificNamedCurve(namedCurve)) { /* * RFC 4492 5.4. All those values of NamedCurve are allowed that refer to a * specific curve. Values of NamedCurve that indicate support for a class of * explicitly defined curves are not allowed here [...]. */ throw new TlsFatalAlert(AlertDescription.illegal_parameter); } CheckNamedCurve(namedCurves, namedCurve); return(GetParametersForNamedCurve(namedCurve)); } default: throw new TlsFatalAlert(AlertDescription.illegal_parameter); } } catch (Exception e) { throw new TlsFatalAlert(AlertDescription.illegal_parameter, e); } }
public static BigInteger EuclidAlgorithm(BigInteger a, BigInteger b, out BigInteger x, out BigInteger y) { if (b > a) { BigInteger t; t = a; a = b; b = t; } Triplet prev = new Triplet(a, 1, 0); Triplet cur = new Triplet(b, 0, 1); Triplet temp; while (cur.X != 0) { temp = cur; cur = prev - (prev.X / cur.X) * cur; prev = temp; } x = prev.Y; y = prev.Z; return prev.X; }
public static void WriteECExponent(int k, Stream output) { BigInteger K = BigInteger.ValueOf(k); WriteECParameter(K, output); }
public Triplet(BigInteger x, BigInteger y, BigInteger z) { X = x; Y = y; Z = z; }
public static byte[] SerializeECFieldElement(int fieldSize, BigInteger x) { return(BigIntegers.AsUnsignedByteArray((fieldSize + 7) / 8, x)); }
private void ValidateInteger(JsonSchemaModel schema) { if (schema == null) { return; } if (!TestType(schema, JsonSchemaType.Integer)) { return; } ValidateNotDisallowed(schema); object value = _reader.Value; if (schema.Maximum != null) { if (JValue.Compare(JTokenType.Integer, value, schema.Maximum) > 0) { RaiseError("Integer {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema); } if (schema.ExclusiveMaximum && JValue.Compare(JTokenType.Integer, value, schema.Maximum) == 0) { RaiseError("Integer {0} equals maximum value of {1} and exclusive maximum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema); } } if (schema.Minimum != null) { if (JValue.Compare(JTokenType.Integer, value, schema.Minimum) < 0) { RaiseError("Integer {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema); } if (schema.ExclusiveMinimum && JValue.Compare(JTokenType.Integer, value, schema.Minimum) == 0) { RaiseError("Integer {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema); } } if (schema.DivisibleBy != null) { bool notDivisible; #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (value is BigInteger) { // not that this will lose any decimal point on DivisibleBy // so manually raise an error if DivisibleBy is not an integer and value is not zero BigInteger i = (BigInteger)value; bool divisibleNonInteger = !Math.Abs(schema.DivisibleBy.Value - Math.Truncate(schema.DivisibleBy.Value)).Equals(0); if (divisibleNonInteger) { notDivisible = i != 0; } else { notDivisible = i % new BigInteger(schema.DivisibleBy.Value) != 0; } } else #endif { notDivisible = !IsZero(Convert.ToInt64(value, CultureInfo.InvariantCulture) % schema.DivisibleBy.GetValueOrDefault()); } if (notDivisible) { RaiseError("Integer {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema); } } }
public static BigInteger GenerateUnsignedRandomBigInteger(BigInteger minValue, BigInteger maxValue) { BigInteger result = 0; do { int length = (int)Math.Ceiling(BigInteger.Log(maxValue, 2)); int numBytes = (int)Math.Ceiling(length / 8.0); byte[] data = new byte[numBytes]; rand.NextBytes(data); result = new BigInteger(data, isUnsigned: true); } while (result >= maxValue || result < minValue); return result; }
private static BigInteger Solve(BigInteger[] days, int i, BigInteger d) { BigInteger day = days[i]; BigInteger value = d / day; return value * day; }
public ECPrivateKeyParameters( BigInteger d, ECDomainParameters parameters) : this("EC", d, parameters) { }
/// <summary> /// Generates numbers that range from the value of the current instance to the value of end. /// </summary> /// <param name="start">The current instance.</param> /// <param name="end">The number to end at.</param> /// <param name="step">The step to take on each iteration.</param> /// <returns>An enumerable containing the numbers.</returns> /// <remarks>Yet Another Language Geek - http://blogs.msdn.com/b/wesdyer/archive/2007/02/23/linq-to-ascii-art.aspx</remarks> public static IEnumerable <BigInteger> To(this BigInteger start, BigInteger end, BigInteger step) { #if DOTNET4 Contract.Requires(step > 0); Contract.Ensures(Contract.Result <IEnumerable <BigInteger> >() != null); Contract.Ensures(Contract.Result <IEnumerable <BigInteger> >().Any()); #endif if (start < end) { for (BigInteger i = start; i <= end; i += step) { yield return(i); } } else if (start > end) { for (BigInteger i = start; i >= end; i -= step) { yield return(i); } } else { yield return(end); } }
private static string ToStringInternal(BigInteger value) { return(value.ToString(null, CultureInfo.InvariantCulture)); }
public ECDsaPublicBcpgKey( DerObjectIdentifier oid, BigInteger encodedPoint) : base(oid, encodedPoint) { }
public static BigInteger[] ReadBigIntegeNumbers() { var splitParts = ConsoleReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); return splitParts.Select(e => BigInteger.Parse(e)).ToArray(); }
private void CallCompareTo() { // <Snippet6> BigInteger bigIntegerInstance = BigInteger.Parse("3221123045552"); byte byteInteger = 16; sbyte sByteInteger = -16; short shortInteger = 1233; ushort uShortInteger = 1233; int normalInteger = -12233; uint normalUInteger = 12233; long longInteger = 12382222; ulong uLongInteger = 1238222; float singleValue = -123.49951F; double doubleValue = 123.49951992; decimal decimalValue = 1234.556M; Console.WriteLine("Comparison of {0} with {1}: {2}", bigIntegerInstance, byteInteger, bigIntegerInstance.CompareTo(byteInteger)); Console.WriteLine("Comparison of {0} with {1}: {2}", bigIntegerInstance, sByteInteger, bigIntegerInstance.CompareTo(sByteInteger)); Console.WriteLine("Comparison of {0} with {1}: {2}", bigIntegerInstance, shortInteger, bigIntegerInstance.CompareTo(shortInteger)); Console.WriteLine("Comparison of {0} with {1}: {2}", bigIntegerInstance, uShortInteger, bigIntegerInstance.CompareTo(uShortInteger)); Console.WriteLine("Comparison of {0} with {1}: {2}", bigIntegerInstance, normalInteger, bigIntegerInstance.CompareTo(normalInteger)); Console.WriteLine("Comparison of {0} with {1}: {2}", bigIntegerInstance, normalUInteger, bigIntegerInstance.CompareTo(normalUInteger)); Console.WriteLine("Comparison of {0} with {1}: {2}", bigIntegerInstance, longInteger, bigIntegerInstance.CompareTo(longInteger)); Console.WriteLine("Comparison of {0} with {1}: {2}", bigIntegerInstance, uLongInteger, bigIntegerInstance.CompareTo(uLongInteger)); try { Console.WriteLine("Comparison of {0} with {1}: {2}", bigIntegerInstance, singleValue, bigIntegerInstance.CompareTo(singleValue)); } catch (ArgumentException) { Console.WriteLine("Unable to compare {0} with a {1} value of {2}", bigIntegerInstance, singleValue.GetType().Name, singleValue); } try { Console.WriteLine("Comparison of {0} with {1}: {2}", bigIntegerInstance, doubleValue, bigIntegerInstance.CompareTo(doubleValue)); } catch (ArgumentException) { Console.WriteLine("Unable to compare {0} with a {1} value of {2}", bigIntegerInstance, doubleValue.GetType().Name, doubleValue); } try { Console.WriteLine("Comparison of {0} with {1}: {2}", bigIntegerInstance, decimalValue, bigIntegerInstance.CompareTo(decimalValue)); } catch (ArgumentException) { Console.WriteLine("Unable to compare {0} with a {1} value of {2}", bigIntegerInstance, decimalValue.GetType().Name, decimalValue); } // // The code produces the following output to the console: // // Comparison of 3221123045552 with 16: 1 // Comparison of 3221123045552 with -16: 1 // Comparison of 3221123045552 with 1233: 1 // Comparison of 3221123045552 with 1233: 1 // Comparison of 3221123045552 with -12233: 1 // Comparison of 3221123045552 with 12233: 1 // Comparison of 3221123045552 with 12382222: 1 // Comparison of 3221123045552 with 1238222: 1 // Unable to compare 3221123045552 with a Single value of -123.4995 // Unable to compare 3221123045552 with a Double value of 123.49951992 // Unable to compare 3221123045552 with a Decimal value of 1234.556 // </Snippet6> }
public void set_register_value(char name, BigInteger value) { registers[name].value = value; }
public override ECFieldElement FromBigInteger(BigInteger x) { return(new SecT163FieldElement(x)); }
private void CreateBigIntegers() { // <Snippet3> BigInteger bigIntFromDouble = new BigInteger(179032.6541); BigInteger bigIntFromInt64 = new BigInteger(934157136952); // </Snippet3> Console.WriteLine(bigIntFromDouble); Console.WriteLine(bigIntFromInt64); // <Snippet4> BigInteger assignedFromLong = 6315489358112; BigInteger assignedFromDouble = (BigInteger)179032.6541D; BigInteger assignedFromDecimal = (BigInteger)64312.65m; // </Snippet4> Console.WriteLine(assignedFromLong); Console.WriteLine(assignedFromDecimal); Console.WriteLine(assignedFromDouble); // <Snippet34> decimal fractionalNumber = 13456.92m; BigInteger wholeNumber = new BigInteger(fractionalNumber); Console.WriteLine(wholeNumber); // Displays 13456 // </Snippet34> // <Snippet35> // Create a BigInteger from a large double value double impreciseNumber = -6e35; BigInteger preciseNumber = new BigInteger(impreciseNumber); Console.WriteLine(impreciseNumber.ToString("F")); Console.WriteLine(preciseNumber); impreciseNumber++; preciseNumber++; Console.WriteLine(impreciseNumber.ToString("F")); Console.WriteLine(preciseNumber); // The example displays the following output to the console: // -600000000000000000000000000000000000.00 // -599999999999999981180196647507853312 // -600000000000000000000000000000000000.00 // -599999999999999981180196647507853311 // </Snippet35> // <Snippet36> // Create a BigInteger from a large negatie float value float negativeFloat = Single.MinValue; BigInteger negativeNumber = new BigInteger(negativeFloat); Console.WriteLine(negativeFloat.ToString("F")); Console.WriteLine(negativeNumber); negativeFloat++; negativeNumber++; Console.WriteLine(negativeFloat.ToString("F")); Console.WriteLine(negativeNumber); // The example displays the following output to the console: // -340282300000000000000000000000000000000.00 // -340282346638528859811704183484516925440 // -340282300000000000000000000000000000000.00 // -340282346638528859811704183484516925439 // </Snippet36> }
private static void MultiDivide(BigInteger leftSide, BigInteger rightSide, out BigInteger quotient, out BigInteger remainder) { if (rightSide.IsZero) { throw new DivideByZeroException(); } DType val = rightSide.m_digits[rightSide.m_digits.DataUsed - 1]; int d = 0; for (uint mask = DigitsArray.HiBitSet; mask != 0 && (val & mask) == 0; mask >>= 1) { d++; } int remainderLen = leftSide.m_digits.DataUsed + 1; DType[] remainderDat = new DType[remainderLen]; leftSide.m_digits.CopyTo(remainderDat, 0, leftSide.m_digits.DataUsed); DigitsArray.ShiftLeft(remainderDat, d); rightSide = rightSide << d; ulong firstDivisor = rightSide.m_digits[rightSide.m_digits.DataUsed - 1]; ulong secondDivisor = (rightSide.m_digits.DataUsed < 2 ? (DType)0 : rightSide.m_digits[rightSide.m_digits.DataUsed - 2]); int divisorLen = rightSide.m_digits.DataUsed + 1; DigitsArray dividendPart = new DigitsArray(divisorLen, divisorLen); DType[] result = new DType[leftSide.m_digits.Count + 1]; int resultPos = 0; ulong carryBit = (ulong)0x1 << DigitsArray.DataSizeBits; // 0x100000000 for (int j = remainderLen - rightSide.m_digits.DataUsed, pos = remainderLen - 1; j > 0; j--, pos--) { ulong dividend = ((ulong)remainderDat[pos] << DigitsArray.DataSizeBits) + (ulong)remainderDat[pos - 1]; ulong qHat = (dividend / firstDivisor); ulong rHat = (dividend % firstDivisor); while (pos >= 2) { if (qHat == carryBit || (qHat * secondDivisor) > ((rHat << DigitsArray.DataSizeBits) + remainderDat[pos - 2])) { qHat--; rHat += firstDivisor; if (rHat < carryBit) { continue; } } break; } for (int h = 0; h < divisorLen; h++) { dividendPart[divisorLen - h - 1] = remainderDat[pos - h]; } BigInteger dTemp = new BigInteger(dividendPart); BigInteger rTemp = rightSide * new BigInteger((long)qHat); while (rTemp > dTemp) { qHat--; rTemp -= rightSide; } rTemp = dTemp - rTemp; for (int h = 0; h < divisorLen; h++) { remainderDat[pos - h] = rTemp.m_digits[rightSide.m_digits.DataUsed - h]; } result[resultPos++] = (DType)qHat; } Array.Reverse(result, 0, resultPos); quotient = new BigInteger(new DigitsArray(result)); int n = DigitsArray.ShiftRight(remainderDat, d); DigitsArray rDA = new DigitsArray(n, n); rDA.CopyFrom(remainderDat, 0, 0, rDA.DataUsed); remainder = new BigInteger(rDA); }
public override bool IsSatisfied(BigInteger value) { return(value % 5 == 0); }
/// <summary> /// Divide a BigInteger by another BigInteger and returning the result. /// </summary> /// <param name="leftSide">A BigInteger divisor.</param> /// <param name="rightSide">A BigInteger dividend.</param> /// <returns>The BigInteger result.</returns> public static BigInteger Divide(BigInteger leftSide, BigInteger rightSide) { return(leftSide / rightSide); }
private static void SingleDivide(BigInteger leftSide, BigInteger rightSide, out BigInteger quotient, out BigInteger remainder) { if (rightSide.IsZero) { throw new DivideByZeroException(); } DigitsArray remainderDigits = new DigitsArray(leftSide.m_digits); remainderDigits.ResetDataUsed(); int pos = remainderDigits.DataUsed - 1; ulong divisor = (ulong)rightSide.m_digits[0]; ulong dividend = (ulong)remainderDigits[pos]; DType[] result = new DType[leftSide.m_digits.Count]; leftSide.m_digits.CopyTo(result, 0, result.Length); int resultPos = 0; if (dividend >= divisor) { result[resultPos++] = (DType)(dividend / divisor); remainderDigits[pos] = (DType)(dividend % divisor); } pos--; while (pos >= 0) { dividend = ((ulong)(remainderDigits[pos + 1]) << DigitsArray.DataSizeBits) + (ulong)remainderDigits[pos]; result[resultPos++] = (DType)(dividend / divisor); remainderDigits[pos + 1] = 0; remainderDigits[pos--] = (DType)(dividend % divisor); } remainder = new BigInteger(remainderDigits); DigitsArray quotientDigits = new DigitsArray(resultPos + 1, resultPos); int j = 0; for (int i = quotientDigits.DataUsed - 1; i >= 0; i--, j++) { quotientDigits[j] = result[i]; } quotient = new BigInteger(quotientDigits); }
/// <summary> /// Multiply two BigIntegers returning the result. /// </summary> /// <param name="leftSide">A BigInteger.</param> /// <param name="rightSide">A BigInteger</param> /// <returns></returns> public static BigInteger Multiply(BigInteger leftSide, BigInteger rightSide) { return(leftSide * rightSide); }
private static void Divide(BigInteger leftSide, BigInteger rightSide, out BigInteger quotient, out BigInteger remainder) { if (leftSide.IsZero) { quotient = new BigInteger(); remainder = new BigInteger(); return; } if (rightSide.m_digits.DataUsed == 1) { SingleDivide(leftSide, rightSide, out quotient, out remainder); } else { MultiDivide(leftSide, rightSide, out quotient, out remainder); } }