Exemple #1
0
        public ECPoint GenerateKey(ECPoint publicKey, out byte[] key, BigInteger?k)
        {
            for (int i = 0; i < 100; i++)
            {
                if (k == null)
                {
                    byte[] kBytes = new byte[33];
                    rngCsp.GetBytes(kBytes);
                    kBytes[32] = 0;

                    k = new BigInteger(kBytes);
                }

                if (k.Value.IsZero || k.Value >= Secp256k1.N)
                {
                    continue;
                }

                var tag      = Secp256k1.G.Multiply(k.Value);
                var keyPoint = publicKey.Multiply(k.Value);

                if (keyPoint.IsInfinity || tag.IsInfinity)
                {
                    continue;
                }

                key = SHA256.DoubleHash(keyPoint.EncodePoint(false));

                return(tag);
            }

            throw new Exception("Unable to generate key");
        }
 public void GenerateNewAndEvaluate(IEquationFinderArgs equationArgs)
 {
     _result      = null;
     EquationArgs = equationArgs;
     Equation     = HelperClass.GenerateRandomEquation(EquationArgs);
     Solve();
 }
Exemple #3
0
        private async Task CreateNewBlockchainPolicy(I2B_Request request)
        {
            BigInteger?nonce = null;

            if (_blockchain_settings.transaction_fire_and_forget)
            {
                nonce = _web3geth_service.BlockchainManager.GetMainAccountNonceForRawTransaction;
            }

            CreatePolicy create_policy = JsonConvert.DeserializeObject <CreatePolicy>(request.task.payload);
            string       tx_hash       = await _web3geth_service.Policy.CreateAsync(
                task_uuid : request.task_uuid,
                pid : create_policy.pid.ToString(),
                psn : create_policy.psn,
                tenant_id : create_policy.tenant_id.ToString(),
                start_date_time : create_policy.start_date_time.ToString(),
                end_date_time : create_policy.end_date_time.ToString(),
                start_date_time_local : create_policy.start_date_time_local,
                end_date_time_local : create_policy.end_date_time_local,
                nonce : nonce);

            if (_blockchain_settings.transaction_fire_and_forget)
            {
                // check transaction is pending
                await MakeSureTransactionIsPending(tx_hash);

                var fire_and_forget = BackgroundWaitTransactionResult(tx_hash, request);
            }
            else
            {
                await BackgroundWaitTransactionResult(tx_hash, request);
            }
        }
Exemple #4
0
        private async Task UpdateBlockchainPolicy(I2B_Request request)
        {
            BigInteger?nonce = null;

            if (_blockchain_settings.transaction_fire_and_forget)
            {
                nonce = _web3geth_service.BlockchainManager.GetMainAccountNonceForRawTransaction;
            }

            UpdatePolicy update_policy = JsonConvert.DeserializeObject <UpdatePolicy>(request.task.payload);

            string tx_hash = await _web3geth_service.Policy.SetPolicyAllAttributes(
                contract_address : update_policy.contract_address,
                task_uuid : request.task_uuid,
                start_date_time : update_policy.start_date_time.ToString(),
                end_date_time : update_policy.end_date_time.ToString(),
                start_date_time_local : update_policy.start_date_time_local,
                end_date_time_local : update_policy.end_date_time_local,
                status : update_policy.status,
                deleted : update_policy.deleted.ToString(),
                nonce : nonce);

            if (_blockchain_settings.transaction_fire_and_forget)
            {
                // check transaction is pending
                await MakeSureTransactionIsPending(tx_hash);

                var fire_and_forget = BackgroundWaitTransactionResult(tx_hash, request);
            }
            else
            {
                await BackgroundWaitTransactionResult(tx_hash, request);
            }
        }
        public CurvePoint(EllypticCurve curve, Point point, BigInteger?orderOfGroup = default(BigInteger?))
        {
            if (curve.IsOnCurve(point))
            {
                Console.WriteLine($"Point {point} is on curve {curve.Coefficient}, {curve.Constant}");
            }
            else
            {
//                throw new ArgumentException($"Point {point} is not on curve {curve.Coefficient}, {curve.Constant}");
                Console.WriteLine($"Point {point} is not on curve {curve.Coefficient}, {curve.Constant}");
            }

            Curve = curve;
            Point = point;

            if (orderOfGroup.HasValue)
            {
                Order = orderOfGroup.Value;
            }
            else
            {
                Order = FindOrderOfGroup();
                Console.WriteLine($"Order of group is calculated {Order}");
            }
        }
        public async Task <Fee1559> SuggestFeeAsync(BigInteger?maxPriorityFeePerGas = null)
        {
            var lastBlock = await _ethGetBlockWithTransactionsHashes.SendRequestAsync(BlockParameter.CreateLatest()).ConfigureAwait(false);

            if (lastBlock.BaseFeePerGas == null)
            {
                return(FallbackFeeSuggestion);
            }

            var baseFee = lastBlock.BaseFeePerGas;

            if (maxPriorityFeePerGas == null)
            {
                var estimatedPriorityFee = await EstimatePriorityFeeAsync(
                    baseFee,
                    lastBlock.Number
                    );

                if (estimatedPriorityFee == null)
                {
                    return(FallbackFeeSuggestion);
                }

                maxPriorityFeePerGas = BigInteger.Max(estimatedPriorityFee.Value, DefaultPriorityFee);
            }

            return(SuggestMaxFeeUsingMultiplier(maxPriorityFeePerGas, baseFee));
        }
        /// <summary>
        /// Updates the timestamp for the point represented by <see cref="Instant"/>.
        /// </summary>
        /// <param name="timestamp">the timestamp</param>
        /// <param name="timeUnit">the timestamp precision</param>
        /// <returns></returns>
        public Point Timestamp(Instant timestamp, WritePrecision timeUnit)
        {
            Precision = timeUnit;

            switch (timeUnit)
            {
            case WritePrecision.S:
                _time = timestamp.ToUnixTimeSeconds();
                break;

            case WritePrecision.Ms:
                _time = timestamp.ToUnixTimeMilliseconds();
                break;

            case WritePrecision.Us:
                _time = (long)(timestamp.ToUnixTimeTicks() * 0.1);
                break;

            default:
                _time = (timestamp - NodaConstants.UnixEpoch).ToBigIntegerNanoseconds();
                break;
            }

            return(this);
        }
Exemple #8
0
        public BigInteger Solve(BigInteger?input = null)
        {
            bool[]     primesUnderAMillion = PrimeHelper.FindPrimesUnderLimit(1000000);
            BigInteger result = 0;

            for (int i = 2; i < 1000000; i++)
            {
                var testNumber = i;
                var circular   = true;
                var testString = testNumber.ToString();

                for (int j = 0; j <= i.ToString().Length + 1; j++)
                {
                    if (!primesUnderAMillion[testNumber] || testNumber > 1000000)
                    {
                        circular = false;
                        break;
                    }

                    testString = testString.Insert(testString.Length, testString.Substring(0, 1));
                    testString = testString.Remove(0, 1);
                    testNumber = int.Parse(testString);
                }

                if (circular)
                {
                    result++;
                }
            }

            return(result);
        }
        /// <summary>
        /// Updates the timestamp for the point.
        /// </summary>
        /// <param name="timestamp">the timestamp</param>
        /// <param name="timeUnit">the timestamp precision</param>
        /// <returns></returns>
        public Point Timestamp(long timestamp, WritePrecision timeUnit)
        {
            Precision = timeUnit;
            _time     = timestamp;

            return(this);
        }
        /// <summary>
        /// Updates the timestamp for the point represented by <see cref="TimeSpan"/>.
        /// </summary>
        /// <param name="timestamp">the timestamp</param>
        /// <param name="timeUnit">the timestamp precision</param>
        /// <returns></returns>
        public Point Timestamp(TimeSpan timestamp, WritePrecision timeUnit)
        {
            Precision = timeUnit;

            switch (timeUnit)
            {
            case WritePrecision.Ns:
                _time = timestamp.Ticks * 100;
                break;

            case WritePrecision.Us:
                _time = (BigInteger)(timestamp.Ticks * 0.1);
                break;

            case WritePrecision.Ms:
                _time = (BigInteger)timestamp.TotalMilliseconds;
                break;

            case WritePrecision.S:
                _time = (BigInteger)timestamp.TotalSeconds;
                break;
            }

            return(this);
        }
Exemple #11
0
        private static void AddItemLevels(
            GameData gameData,
            Dictionary <int, BigInteger> itemLevels,
            int?itemType,
            BigInteger?itemLevel)
        {
            if (itemType == null ||
                itemLevel == null ||
                itemLevel.Value == 0)
            {
                return;
            }

            ItemBonusType itemBonusType;

            if (!gameData.ItemBonusTypes.TryGetValue(itemType.Value, out itemBonusType))
            {
                return;
            }

            var        ancientId = itemBonusType.AncientId;
            BigInteger currentLevel;

            if (itemLevels.TryGetValue(ancientId, out currentLevel))
            {
                itemLevels[ancientId] = currentLevel + itemLevel.Value;
            }
            else
            {
                itemLevels.Add(ancientId, itemLevel.Value);
            }
        }
Exemple #12
0
 public void TestBasicBig()
 {
     inpt = BigInput;
     rslt = doConvert();
     Assert.IsTrue(rslt.HasValue);
     Assert.AreEqual(BigResult, rslt.Value);
 }
Exemple #13
0
        public NumberRational(BigInteger numerator, BigInteger denominator, BigInteger?exponent = null)
        {
            Numerator   = numerator;
            Denominator = denominator;
            Exponent    = exponent ?? 1;
            if (Denominator < 0)
            {
                Denominator = BigInteger.Negate(Denominator);
                Numerator   = BigInteger.Negate(Numerator);
            }
            var gcd = MathEx.EuclideanAlgorithm(this.Denominator, this.Numerator);

            this.Denominator /= gcd;
            this.Numerator   /= gcd;
            while (Denominator % 2 == 0)
            {
                Denominator /= 2;
                Exponent    -= 1;
                Numerator   *= 5;
            }
            while (Denominator % 5 == 0)
            {
                Denominator /= 5;
                Exponent    -= 1;
                Numerator   *= 2;
            }
            while (Numerator % 10 == 0)
            {
                Numerator /= 10;
                Exponent++;
            }
        }
Exemple #14
0
        public Transaction(
            string version,
            Address from,
            Address to,
            BigInteger?value,
            BigInteger?stepLimit,
            BigInteger?nonce,
            BigInteger?nid,
            BigInteger?timestamp,
            string dataType,
            object data,
            Hash32 hash,
            Signature signature)
        {
            Version   = version;
            From      = from;
            To        = to;
            Value     = value;
            StepLimit = stepLimit;
            Nonce     = nonce;
            NID       = nid;
            Timestamp = timestamp;
            DataType  = dataType;
            Data      = data;

            Hash      = hash;
            Signature = signature;
        }
Exemple #15
0
        public BigInteger Solve(BigInteger?input = null)
        {
            StreamReader sr = new StreamReader("Solutions\\21 - 30\\22.txt");

            string inputText = sr.ReadLine();

            sr.Close();

            List <string> names = inputText.Split(',').Select(s => s.Replace("\"", "")).ToList();

            names.Sort();
            int        index  = 1;
            BigInteger result = 0;

            foreach (string name in names)
            {
                int nameTotal = 0;
                for (int i = 0; i < name.Length; i++)
                {
                    nameTotal += (int)name[i] - 64;
                }

                result += index * nameTotal;
                index++;
            }

            return(result);
        }
Exemple #16
0
        public async Task <bool> ExecuteAsync(
            BigInteger?startBlock, BigInteger?endBlock, CancellationToken cancellationToken)
        {
            startBlock = startBlock ?? await GetStartingBlockNumber();

            if (endBlock.HasValue && startBlock.Value > endBlock.Value)
            {
                _log.StartBlockExceedsEndBlock(startBlock.Value, endBlock.Value);
                return(false);
            }

            _log.BeginFillContractCacheAsync();
            await _strategy.FillContractCacheAsync().ConfigureAwait(false);


            _log.BeginningBlockEnumeration();
            return(await new BlockEnumeration(
                       (blkNumber) => _strategy.ProcessBlockAsync(blkNumber),
                       (retryNum) => _strategy.WaitForNextBlock(retryNum),
                       (retryNum) => _strategy.PauseFollowingAnError(retryNum),
                       () => _strategy.GetMaxBlockNumberAsync(),
                       _strategy.MinimumBlockConfirmations,
                       _strategy.MaxRetries,
                       cancellationToken,
                       startBlock.Value,
                       endBlock,
                       _log.Logger
                       )
                   .ExecuteAsync().ConfigureAwait(false));
        }
        /// <summary>
        /// Used by the initiator. It first verifies that the incoming token is well-formed, and then removes the previously applied mask.
        /// </summary>
        /// <param name="ecParameters">Curve parameters</param>
        /// <param name="K">The public key point for the token scheme</param>
        /// <param name="P">Masked point initially submitted to the token service</param>
        /// <param name="Q">Signed masked point returned from the token service</param>
        /// <param name="c">Claimed challenge from the Chaum-Pedersen proof</param>
        /// <param name="z">Response from the Chaum-Pedersen proof</param>
        /// <param name="r">Masking of the initial point</param>
        /// <returns>A randomised signature W on the point chosen by the initiator</returns>
        public ECPoint RandomiseToken(X9ECParameters ecParameters, ECPoint K, ECPoint P, ECPoint Q, BigInteger c, BigInteger z, BigInteger r)
        {
            ECCurve?curve = ecParameters.Curve;

            // Check that P is a valid point on the currect curve
            if (ECPointVerifier.PointIsValid(P, curve) == false)
            {
                throw new AnonymousTokensException("P is not a valid point on the curve");
            }

            // Check that Q is a valid point on the currect curve
            if (ECPointVerifier.PointIsValid(Q, curve) == false)
            {
                throw new AnonymousTokensException("Q is not a valid point on the curve");
            }

            // Verify the proof (c,z).
            if (!VerifyProof(ecParameters, K, P, Q, c, z))
            {
                throw new AnonymousTokensException("Chaum-Pedersen proof is invalid");
            }

            // Removing the initial mask r. W = (1/r)*Q = k*T.
            BigInteger?rInverse = r.ModInverse(ecParameters.Curve.Order);
            ECPoint?   W        = Q.Multiply(rInverse);

            return(W);
        }
Exemple #18
0
        /// <summary>
        /// Updates the timestamp for the point represented by <see cref="Instant"/>.
        /// </summary>
        /// <param name="timestamp">the timestamp</param>
        /// <param name="timeUnit">the timestamp precision</param>
        /// <returns></returns>
        public PointData Timestamp(Instant timestamp, WritePrecision timeUnit)
        {
            BigInteger?time = null;

            switch (timeUnit)
            {
            case WritePrecision.S:
                time = timestamp.ToUnixTimeSeconds();
                break;

            case WritePrecision.Ms:
                time = timestamp.ToUnixTimeMilliseconds();
                break;

            case WritePrecision.Us:
                time = (long)(timestamp.ToUnixTimeTicks() * 0.1);
                break;

            default:
                time = (timestamp - NodaConstants.UnixEpoch).ToBigIntegerNanoseconds();
                break;
            }


            return(new PointData(_measurementName,
                                 timeUnit,
                                 time,
                                 _tags,
                                 _fields));
        }
Exemple #19
0
        /// <summary>
        /// Updates the timestamp for the point represented by <see cref="TimeSpan"/>.
        /// </summary>
        /// <param name="timestamp">the timestamp</param>
        /// <param name="timeUnit">the timestamp precision</param>
        /// <returns></returns>
        public PointData Timestamp(TimeSpan timestamp, WritePrecision timeUnit)
        {
            BigInteger?time = null;

            switch (timeUnit)
            {
            case WritePrecision.Ns:
                time = timestamp.Ticks * 100;
                break;

            case WritePrecision.Us:
                time = (BigInteger)(timestamp.Ticks * 0.1);
                break;

            case WritePrecision.Ms:
                time = (BigInteger)timestamp.TotalMilliseconds;
                break;

            case WritePrecision.S:
                time = (BigInteger)timestamp.TotalSeconds;
                break;
            }

            return(new PointData(_measurementName,
                                 timeUnit,
                                 time,
                                 _tags,
                                 _fields));
        }
Exemple #20
0
 public AccountSignerTransactionManager(IClient rpcClient, Account account, BigInteger?chainId = null)
 {
     ChainId            = chainId;
     Account            = account ?? throw new ArgumentNullException(nameof(account));
     Client             = rpcClient;
     _transactionSigner = new TransactionSigner();
 }
        public void GenerateNewAndEvaluate(IEquationFinderArgs args)
        {
            _result      = null;
            _isSolution  = false;
            EquationArgs = args;

            IncreasingOperations = new List <TupleOperation>();
            DecreasingOperations = new List <TupleOperation>();

            foreach (char op in EquationArgs.OperatorPool)
            {
                TupleOperation tupleOperation = new TupleOperation(op);

                switch (tupleOperation.Operand)
                {
                case OperationType.Add:
                case OperationType.Multiply:
                case OperationType.Exponentiation:
                    IncreasingOperations.Add(tupleOperation);
                    break;

                case OperationType.Subtract:
                case OperationType.Divide:
                    DecreasingOperations.Add(tupleOperation);
                    break;
                }
            }

            BuildEquation();
        }
Exemple #22
0
        // CONSTRUCTORS
        public MainViewModel()
        {
            rand = new System.Random();

            A    = null;
            B    = null;
            algo = new Models.Algorithm();

            p      = null;
            a      = null;
            smallX = null;
            smallY = null;
            bigX   = null;
            bigY   = null;
            k1     = null;
            k2     = null;

            #region Commands
            generatePA = new RelayCommand(GeneratePAMethod);
            sendPA     = new RelayCommand(SendPAMethod, IsPSetted);
            generateX  = new RelayCommand(GenerateXMethod, IsABSetted);
            generateY  = new RelayCommand(GenerateYMethod, IsABSetted);
            sendX      = new RelayCommand(SendXMethod, IsABSetted);
            sendY      = new RelayCommand(SendYMethod, IsABSetted);
            #endregion
        }
Exemple #23
0
 public HeaderValidator(IBlockTree blockTree, ISealEngine sealEngine, ISpecProvider specProvider, ILogManager logManager)
 {
     _logger         = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
     _blockTree      = blockTree ?? throw new ArgumentNullException(nameof(blockTree));
     _sealEngine     = sealEngine ?? throw new ArgumentNullException(nameof(sealEngine));
     _daoBlockNumber = specProvider?.DaoBlockNumber;
 }
Exemple #24
0
        public BigInteger Solve(BigInteger?input = null)
        {
            int numberOfDivisors = 0;
            int i = 2, triangleNumber = 1;

            while (numberOfDivisors < 500)
            {
                numberOfDivisors = 0;
                triangleNumber  += i;

                int testNumber = triangleNumber;
                Dictionary <int, int> divisors = DivisorsHelper.CalculatePrimeDivisors(testNumber, PrimeHelper.FindPrimesUnderLimit(200000000));

                numberOfDivisors = divisors.Values.ElementAt(0) + 1;
                for (int l = 1; l < divisors.Count; l++)
                {
                    numberOfDivisors *= divisors.Values.ElementAt(l) + 1;
                }

                i++;
            }


            return(triangleNumber);
        }
 public void LastBlockProcessed(BigInteger?lastBlock)
 {
     if (IsInfoEnabled)
     {
         Logger.Info(lastBlock == null ? "No blocks previously processed" : $"Last Block: {lastBlock}");
     }
 }
Exemple #26
0
        public static BigInteger 乘(BigInteger 因数_左_输入, BigInteger 因数_右_输入)                      // !万级Cell效率衰减严重!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        {
            // 预处理
            BigInteger?积容器 = 异常值计算(因数_左_输入, 因数_右_输入, 算术运算.乘);

            if (积容器 != null)                    // ?是否可用default
            {
                return(积容器.Value);
            }
            else
            {
                // 占位
            }

            BigInteger 积 = default;                     // 仅有空壳,需要后续的赋值

            // 赋值
            // 处理符号
            // 因数		因数		积
            // +			+			+
            // +			−			−
            // −			+			−
            // −			−			+
            积.正号 = !(因数_左_输入.正号 ^ 因数_右_输入.正号);                          // 即同或

            // 因为是整数乘法,所以不会出现乘分数等于除以整数的转移

            积.数值组 = 乘_核心(因数_左_输入.数值组, 因数_右_输入.数值组);
            积.数值组 = Trim(积.数值组);

            // 无穷不需要赋值,因一般运算无法呈现此态

            return(积);
        }
        public static new CeloAccount LoadFromKeyStore(string json, string password, BigInteger?chainId = null)
        {
            var keyStoreService = new KeyStoreService();
            var key             = keyStoreService.DecryptKeyStoreFromJson(password, json);

            return(new CeloAccount(key, chainId));
        }
 public CeloAccount(byte[] privateKey, Chain chain, string feeCurrency = null, string gatewayFeeRecipient = null, BigInteger?gatewayFee = null) : base(privateKey, chain)
 {
     FeeCurrency         = feeCurrency;
     GatewayFeeRecipient = gatewayFeeRecipient;
     GatewayFee          = gatewayFee;
     InitialiseDefaultTransactionManager();
 }
Exemple #29
0
        public IEnumerator SuggestFee(BigInteger?maxPriorityFeePerGas = null)
        {
            if (maxPriorityFeePerGas == null)
            {
                maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;
            }

            yield return(_ethGetBlockWithTransactionsHashes.SendRequest(BlockParameter.CreateLatest()));

            if (_ethGetBlockWithTransactionsHashes.Exception == null)
            {
                var lastBlock    = _ethGetBlockWithTransactionsHashes.Result;
                var baseFee      = lastBlock.BaseFeePerGas;
                var maxFeePerGas = baseFee.Value * 2 + maxPriorityFeePerGas;
                this.Result = new Fee1559()
                {
                    BaseFee = baseFee,
                    MaxPriorityFeePerGas = maxPriorityFeePerGas,
                    MaxFeePerGas         = maxFeePerGas
                };
            }
            else
            {
                this.Exception = _ethGetBlockWithTransactionsHashes.Exception;
                yield break;
            }
        }
Exemple #30
0
        public BigInteger Solve(BigInteger?input = null)
        {
            BigInteger maxPallindrome = 0;

            for (int i = 900; i < 999; i++)
            {
                for (int j = 900; j < 999; j++)
                {
                    int result = i * j;
                    if (result > maxPallindrome)
                    {
                        string resultString    = result.ToString();
                        char[] resultCharArray = resultString.ToCharArray();
                        Array.Reverse(resultCharArray);
                        string reverseResultString = new string(resultCharArray);
                        if (resultString == reverseResultString)
                        {
                            maxPallindrome = result;
                        }
                    }
                }
            }

            return(maxPallindrome);
        }
Exemple #31
0
 Node(Variable v, BigInteger? lo, BigInteger? hi, Node next) {
   Contract.Requires(lo != null || hi != null);  // don't accept empty constraints
   Contract.Requires(next == null || StrictlyBefore(v, next.V));
   V = v;
   Lo = lo;
   Hi = hi;
   Next = next;
 }
Exemple #32
0
        static void GreedieDwarf()
        {
            foreach (var pattern in patterns)
            {
                // Helpers.
                var dwarf = 0;
                var gold = (BigInteger)0;
                var nextPatternStep = 0;
                var moves = 0;
                var flags = new bool[valley.Count];

                while (true)
                {
                    // If not visitied, collect the gold
                    // or stop.
                    if (!flags[dwarf])
                    {
                        gold += valley[dwarf];
                        flags[dwarf] = true;
                    }
                    else break;

                    // Next index from pattern.
                    nextPatternStep = moves % pattern.Count;
                    moves++;

                    // Next Dwarf position.
                    dwarf += pattern[nextPatternStep];

                    // If outside of the valley break.
                    if (dwarf < 0 || valley.Count <= dwarf) break;
                }

                maxGoldCollected = maxGoldCollected == null ?
                                   gold : gold > maxGoldCollected ?
                                          gold : maxGoldCollected;
            }
        }
 public override LiteralExpr VisitLiteralExpr(LiteralExpr node)
 {
     if (node.Val is BigNum) {
       var n = ((BigNum)node.Val).ToBigInteger;
       Lo = n;
       Hi = n + 1;
     } else if (node.Val is BigDec) {
       var n = ((BigDec)node.Val).Floor(-BigInteger.Pow(10, 12), BigInteger.Pow(10, 12));
       Lo = n;
       Hi = n + 1;
     } else if (node.Val is bool) {
       if ((bool)node.Val) {
     // true
     Lo = one;
     Hi = null;
       } else {
     // false
     Lo = null;
     Hi = one;
       }
     }
     return node;
 }
Exemple #34
0
 /// <summary>
 /// This constructor leaves Next as null, allowing the caller to fill in Next to finish off the construction.
 /// </summary>
 public Node(Variable v, BigInteger? lo, BigInteger? hi) {
   Contract.Requires(lo != null || hi != null);  // don't accept empty constraints
   V = v;
   Lo = lo;
   Hi = hi;
 }
		void SetNumResults()
		{
			NumResults = null;
			if ((UseCount > ItemCount) && (!Repeat))
				return;

			switch (Type)
			{
				case CombinationsPermutationsType.Combinations:
					switch (Repeat)
					{
						case true: NumResults = Factorial(ItemCount + UseCount - 1) / Factorial(UseCount) / Factorial(ItemCount - 1); break;
						case false: NumResults = Factorial(ItemCount) / Factorial(ItemCount - UseCount) / Factorial(UseCount); break;
					}
					break;
				case CombinationsPermutationsType.Permutations:
					switch (Repeat)
					{
						case true: NumResults = BigInteger.Pow(ItemCount, UseCount); break;
						case false: NumResults = Factorial(ItemCount) / Factorial(ItemCount - UseCount); break;
					}
					break;
			}
		}
Exemple #36
0
 protected override Node nextToEvaluate()
 {
     if (!_evaluated)
     {
         if (_stdin == null)
             _stdin = FuncitonLanguage.PretendStdin ?? FuncitonLanguage.StringToInteger(Console.In.ReadToEnd());
         _result = _stdin.Value;
         _evaluated = true;
     }
     return null;
 }
Exemple #37
0
      // Override visitors for all expressions that can return a boolean, integer, or real result

      public override Expr VisitExpr(Expr node) {
        Lo = Hi = null;
        return base.VisitExpr(node);
      }
Exemple #38
0
 public override Expr VisitLiteralExpr(LiteralExpr node) {
   if (node.Val is BigNum) {
     var n = ((BigNum)node.Val).ToBigInteger;
     Lo = n;
     Hi = n + 1;
   } else if (node.Val is BigDec) {
     BigInteger floor, ceiling;
     ((BigDec)node.Val).FloorCeiling(out floor, out ceiling);
     Lo = floor;
     Hi = ceiling;
   } else if (node.Val is bool) {
     if ((bool)node.Val) {
       // true
       Lo = one;
       Hi = null;
     } else {
       // false
       Lo = null;
       Hi = one;
     }
   }
   return node;
 }
Exemple #39
0
 public override Expr VisitNAryExpr(NAryExpr node) {
   if (node.Fun is UnaryOperator) {
     var op = (UnaryOperator)node.Fun;
     Contract.Assert(node.Args.Count == 1);
     if (op.Op == UnaryOperator.Opcode.Neg) {
       BigInteger? lo, hi;
       VisitExpr(node.Args[0]);
       lo = Lo; hi = Hi;
       if (hi != null) {
         Lo = node.Type.IsReal ? -hi : 1 - hi;
       } else {
         Lo = null;
       }
       if (lo != null) {
         Hi = node.Type.IsReal ? -lo : 1 - lo;
       } else {
         Hi = null;
       }
     }
     else if (op.Op == UnaryOperator.Opcode.Not) {
       VisitExpr(node.Args[0]);
       Contract.Assert((Lo == null && Hi == null) ||
         (Lo == null && (BigInteger)Hi == 1) ||
         (Hi == null && (BigInteger)Lo == 1));
       var tmp = Lo;
       Lo = Hi;
       Hi = tmp;
     }
   } else if (node.Fun is BinaryOperator) {
     var op = (BinaryOperator)node.Fun;
     Contract.Assert(node.Args.Count == 2);
     BigInteger? lo0, hi0, lo1, hi1;
     VisitExpr(node.Args[0]);
     lo0 = Lo; hi0 = Hi;
     VisitExpr(node.Args[1]);
     lo1 = Lo; hi1 = Hi;
     Lo = Hi = null;
     var isReal = node.Args[0].Type.IsReal;
     switch (op.Op) {
       case BinaryOperator.Opcode.And:
         if (hi0 != null || hi1 != null) {
           // one operand is definitely false, thus so is the result
           Lo = null; Hi = one;
         } else if (lo0 != null && lo1 != null) {
           // both operands are definitely true, thus so is the result
           Lo = one; Hi = null;
         }
         break;
       case BinaryOperator.Opcode.Or:
         if (lo0 != null || lo1 != null) {
           // one operand is definitely true, thus so is the result
           Lo = one; Hi = null;
         } else if (hi0 != null && hi1 != null) {
           // both operands are definitely false, thus so is the result
           Lo = null; Hi = one;
         }
         break;
       case BinaryOperator.Opcode.Imp:
         if (hi0 != null || lo1 != null) {
           // either arg0 false or arg1 is true, so the result is true
           Lo = one; Hi = null;
         } else if (lo0 != null && hi1 != null) {
           // arg0 is true and arg1 is false, so the result is false
           Lo = null; Hi = one;
         }
         break;
       case BinaryOperator.Opcode.Iff:
         if (lo0 != null && lo1 != null) {
           Lo = one; Hi = null;
         } else if (hi0 != null && hi1 != null) {
           Lo = one; Hi = null;
         } else if (lo0 != null && hi1 != null) {
           Lo = null; Hi = one;
         } else if (hi0 != null && lo1 != null) {
           Lo = null; Hi = one;
         }
         if (op.Op == BinaryOperator.Opcode.Neq) {
           var tmp = Lo; Lo = Hi; Hi = tmp;
         }
         break;
       case BinaryOperator.Opcode.Eq:
       case BinaryOperator.Opcode.Neq:
         if (node.Args[0].Type.IsBool) {
           goto case BinaryOperator.Opcode.Iff;
         }
         // For Eq:
         // If the (lo0,hi0) and (lo1,hi1) ranges do not overlap, the answer is false.
         // If both ranges are the same unit range, then the answer is true.
         if (hi0 != null && lo1 != null && (isReal ? hi0 < lo1 : hi0 <= lo1)) {
           // no overlap
           Lo = null; Hi = one;
         } else if (lo0 != null && hi1 != null && (isReal ? hi1 < lo0 : hi1 <= lo0)) {
           Lo = null; Hi = one;
           // no overlaop
         } else if (lo0 != null && hi0 != null && lo1 != null && hi1 != null &&
           lo0 == lo1 && hi0 == hi1 &&  // ranges are the same
           (isReal ? lo0 == hi0 : lo0 + 1 == hi0)) {  // unit range
           // both ranges are the same unit range
           Lo = one; Hi = null;
         }
         if (op.Op == BinaryOperator.Opcode.Neq) {
           var tmp = Lo; Lo = Hi; Hi = tmp;
         }
         break;
       case BinaryOperator.Opcode.Le:
         if (isReal) {
           // If hi0 <= lo1, then the answer is true.
           // If hi1 < lo0, then the answer is false.
           if (hi0 != null && lo1 != null && hi0 <= lo1) {
             Lo = one; Hi = null;
           } else if (hi1 != null && lo0 != null && hi1 < lo0) {
             Lo = null; Hi = one;
           }
         } else {
           // If hi0 - 1 <= lo1, then the answer is true.
           // If hi1 <= lo0, then the answer is false.
           if (hi0 != null && lo1 != null && hi0 - 1 <= lo1) {
             Lo = one; Hi = null;
           } else if (lo0 != null && hi1 != null && hi1 <= lo0) {
             Lo = null; Hi = one;
           }
         }
         break;
       case BinaryOperator.Opcode.Lt:
         if (isReal) {
           // If hi0 < lo1, then the answer is true.
           // If hi1 <= lo0, then the answer is false.
           if (hi0 != null && lo1 != null && hi0 < lo1) {
             Lo = one; Hi = null;
           } else if (hi1 != null && lo0 != null && hi1 <= lo0) {
             Lo = null; Hi = one;
           }
         } else {
           // If hi0 <= lo1, then the answer is true.
           // If hi1 - 1 <= lo0, then the answer is false.
           if (hi0 != null && lo1 != null && hi0 <= lo1) {
             Lo = one; Hi = null;
           } else if (lo0 != null && hi1 != null && hi1 - 1 <= lo0) {
             Lo = null; Hi = one;
           }
         }
         break;
       case BinaryOperator.Opcode.Gt:
         // swap the operands and then continue as Lt
         {
           var tmp = lo0; lo0 = lo1; lo1 = tmp;
           tmp = hi0; hi0 = hi1; hi1 = tmp;
         }
         goto case BinaryOperator.Opcode.Lt;
       case BinaryOperator.Opcode.Ge:
         // swap the operands and then continue as Le
         {
           var tmp = lo0; lo0 = lo1; lo1 = tmp;
           tmp = hi0; hi0 = hi1; hi1 = tmp;
         }
         goto case BinaryOperator.Opcode.Le;
       case BinaryOperator.Opcode.Add:
         if (lo0 != null && lo1 != null) {
           Lo = lo0 + lo1;
         }
         if (hi0 != null && hi1 != null) {
           Hi = isReal ? hi0 + hi1 : hi0 + hi1 - 1;
         }
         break;
       case BinaryOperator.Opcode.Sub:
         if (lo0 != null && hi1 != null) {
           Lo = isReal ? lo0 - hi1 : lo0 - hi1 + 1;
         }
         if (hi0 != null && lo1 != null) {
           Hi = hi0 - lo1;
         }
         break;
       case BinaryOperator.Opcode.Mul:
         // this uses an incomplete approximation that could be tightened up
         if (lo0 != null && lo1 != null) {
           if (0 <= (BigInteger)lo0 && 0 <= (BigInteger)lo1) {
             Lo = lo0 * lo1;
             Hi = hi0 == null || hi1 == null ? null : isReal ? hi0 * hi1 : (hi0 - 1) * (hi1 - 1) + 1;
           } else if ((BigInteger)lo0 < 0 && (BigInteger)lo1 < 0) {
             Lo = null;  // approximation
             Hi = isReal ? lo0 * lo1 : lo0 * lo1 + 1;
           }
         }
         break;
       case BinaryOperator.Opcode.Div:
         // this uses an incomplete approximation that could be tightened up
         if (lo0 != null && lo1 != null && 0 <= (BigInteger)lo0 && 0 <= (BigInteger)lo1) {
           Lo = BigInteger.Zero;
           Hi = hi0;
         }
         break;
       case BinaryOperator.Opcode.Mod:
         // this uses an incomplete approximation that could be tightened up
         if (lo0 != null && lo1 != null && 0 <= (BigInteger)lo0 && 0 <= (BigInteger)lo1) {
           Lo = BigInteger.Zero;
           Hi = hi1;
           if (lo0 < lo1 && hi0 != null && hi0 < lo1) {
             Lo = lo0;
             Hi = hi0;
           }
         }
         break;
       case BinaryOperator.Opcode.RealDiv:
         // this uses an incomplete approximation that could be tightened up
         if (lo0 != null && lo1 != null && 0 <= (BigInteger)lo0 && 0 <= (BigInteger)lo1) {
           Lo = BigInteger.Zero;
           Hi = 1 <= (BigInteger)lo1 ? hi0 : null;
         }
         break;
       case BinaryOperator.Opcode.Pow:
         // this uses an incomplete approximation that could be tightened up
         if (lo0 != null && lo1 != null && 0 <= (BigInteger)lo0 && 0 <= (BigInteger)lo1) {
           Lo = 1 <= (BigInteger)lo1 ? BigInteger.One : BigInteger.Zero;
           Hi = hi1;
         }
         break;
       default:
         break;
     }
   } else if (node.Fun is IfThenElse) {
     var op = (IfThenElse)node.Fun;
     Contract.Assert(node.Args.Count == 3);
     BigInteger? guardLo, guardHi, lo0, hi0, lo1, hi1;
     VisitExpr(node.Args[0]);
     guardLo = Lo; guardHi = Hi;
     VisitExpr(node.Args[1]);
     lo0 = Lo; hi0 = Hi;
     VisitExpr(node.Args[2]);
     lo1 = Lo; hi1 = Hi;
     Contract.Assert(guardLo == null || guardHi == null);  // this is a consequence of the guard being boolean
     if (guardLo != null) {
       // guard is always true
       Lo = lo0; Hi = hi0;
     } else if (guardHi != null) {
       // guard is always false
       Lo = lo1; Hi = hi1;
     } else {
       // we don't know which branch will be taken, so join the information from the two branches
       Lo = Node.Min(lo0, lo1, false);
       Hi = Node.Max(hi0, hi1, false);
     }
   } else if (node.Fun is FunctionCall) {
     var call = (FunctionCall)node.Fun;
     // See if this is an identity function, which we do by checking: that the function has
     // exactly one argument and the function has been marked by the user with the attribute {:identity}
     bool claimsToBeIdentity = false;
     if (call.ArgumentCount == 1 && call.Func.CheckBooleanAttribute("identity", ref claimsToBeIdentity) && claimsToBeIdentity && node.Args[0].Type.Equals(node.Type)) {
       VisitExpr(node.Args[0]);
     }
   }
   return node;
 }