Example #1
0
        static void Main(string[] args)
        {
            Dictionary<int, int> sums = new Dictionary<int, int>();

            sums.Add(0, 0);

            foreach (int n in Enumerable.Range(1, 10000))
            {
                if(sums.ContainsKey(n)== false)
                {
                    sums.Add(n, GetSumOfDivisors(n));
                }

                if(sums.ContainsKey(sums[n]) == false)
                {
                    sums.Add(sums[n], GetSumOfDivisors(sums[n]));
                }
            }

            HashSet<int> amicables = new HashSet<int>();
            foreach (var item in sums)
            {
                if (item.Key > 10000)
                    continue;

                if(item.Key == sums[item.Value] && item.Key != item.Value)
                {
                    amicables.Add(item.Key);
                    amicables.Add(item.Value);
                }
            }
            Console.WriteLine(amicables.Sum());
            Console.ReadLine();
        }
Example #2
0
        static void Main()
        {
            var digits = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            var matching = new HashSet<int>();

            var perms = digits.GetPermutations();
            Action<int[], int,int> a = (perm, i, j) =>
            {
                var multiplicand = DigitsToInt(perm, 0, i - 1);
                var multiplier = DigitsToInt(perm, i, i + j - 1);
                var product = DigitsToInt(perm, i + j, perm.Length - 1);

                if (multiplicand * multiplier == product)
                {
                    matching.Add(product);
                }
            };
            foreach (var perm in perms)
            {
                var permArray = perm.ToArray();
                a(permArray,1, 4);
                a(permArray,2, 3);
            }

            Console.WriteLine(matching.Sum());
            Console.ReadLine();
        }
Example #3
0
        void Main()
        {
            String digits = "123456789";
            permutation("", digits);
            HashSet<int> pandigitalNumbers = new HashSet<int>();

            foreach (string s in numbers)
            {
                int three = Convert.ToInt32(s.Substring(0, 3));
                int two = Convert.ToInt32(s.Substring(3, 2));

                int one = Convert.ToInt32(s.Substring(0, 1));
                int four = Convert.ToInt32(s.Substring(1, 4));

                int total = Convert.ToInt32(s.Substring(5, 4));

                if (three * two == total || one * four == total)
                {
                    Console.WriteLine("ADDING: " + s);
                    pandigitalNumbers.Add(total);
                }
            }

            Console.WriteLine(pandigitalNumbers.Sum());
        }
    static void Main(string[] args)
    {
        int N = int.Parse(Console.ReadLine());
        HashSet<House> Houses = new HashSet<House>();
        long amountOfCable = 0;
        for (int i = 0; i < N; i++)
        {
            string[] inputs = Console.ReadLine().Split(' ');
            Houses.Add(new House { X = int.Parse(inputs[0]), Y = int.Parse(inputs[1]) });
        }

        //Core: Calculate Average House Y index
        double Avg = Houses.Sum(x => x.Y) / N;

        //Core:find the house closest to the Avg Y and use its Y coordinate
        int closest = Houses.OrderBy(x => Math.Abs(x.Y - Avg)).First().Y;

        //lay the mainline
        amountOfCable += (Houses.Max(x => x.X) - Houses.Min(x => x.X));

        //per other House calculate distance from location to mainline
        foreach (var i in Houses)
        {
            amountOfCable += i.Y > closest ? i.Y - closest : closest - i.Y;
        }

        // Write an action using Console.WriteLine()
        // To debug: Console.Error.WriteLine("Debug messages...");

        Console.WriteLine(amountOfCable);
    }
        static void Main()
        {
            var collection = new HashSet<double> { 5.2, 8, -3.14, 0, 55 };

            Console.WriteLine(collection.Sum());
            Console.WriteLine(collection.Product());
            Console.WriteLine(collection.Min());
            Console.WriteLine(collection.Max());
            Console.WriteLine(collection.Average());
        }
Example #6
0
        public int S(int n)
        {
            var set = new HashSet<int>();
            for(int k=2;k<=n;k++)
            {
                set.Add(mps(k));
            }

            return set.Sum();
        }
Example #7
0
 private string Main()
 {
     permutation("", "123456789");
     HashSet<int> pandigitalNumbers = new HashSet<int>();
     foreach (string s in numbers.AsParallel().Where(
                                x => Convert.ToInt32(x.Substring(0, 3)) * Convert.ToInt32(x.Substring(3, 2)) == Convert.ToInt32(x.Substring(5, 4))
                                  || Convert.ToInt32(x.Substring(0, 1)) * Convert.ToInt32(x.Substring(1, 4)) == Convert.ToInt32(x.Substring(5, 4))))
         pandigitalNumbers.Add(Convert.ToInt32(s.Substring(5, 4)));
     return pandigitalNumbers.Sum().ToString();
 }
Example #8
0
        public long Solve()
        {
            var primes = new Utils.Prime(51L);
            var squereFree = new HashSet<long>();
            for (var row = 1; row <= 50; row++)
            {
                for (var number = 1; number <= row; number++)
                {
                    squereFree.Add(this.GetSquereFreeBinomilaNumber(number, row, primes));
                }
            }

            return squereFree.Sum();
        }
Example #9
0
 private static int GetSumOfDivisors(int n)
 {
     int sq = (int) Math.Sqrt(n);
     HashSet<int> divisors = new HashSet<int>();
     for(int i = 1; i <= sq; i++)
     {
         if(n % i == 0)
         {
             divisors.Add(i);
             divisors.Add(n / i);
         }
     }
     divisors.Remove(n);
     return divisors.Sum();
 }
        public int CalculateSum(int upperLimit)
        {
            var uniqueMultiples = new HashSet<int>();

            for (int i = 0; i < upperLimit; i++)
            {
                if (i%3 == 0 || i%5 == 0)
                {
                    uniqueMultiples.Add(i);
                }
            }

            var sum = uniqueMultiples.Sum();
            return sum;
        }
Example #11
0
		public P032 ()
		{
			ulong max = 987654321 / 2;
			var all = new HashSet<ulong> ();

			for (ulong a = max; a > 0; a--) {
				if (false
					|| (a % 10000000 == 0)
					|| (a < 10000000 && a % 100000 == 0)
					|| (a < 1000000 && a % 10000 == 0)
					|| (a < 100000 && a % 1000 == 0)
					|| (a < 10000 && a % 100 == 0)
					|| (a < 1000 && a % 10 == 0)
					|| (a < 100 && a % 1 == 0)
					) {
					Console.WriteLine ("a = " + a);
				}

				if (0 == Pandigital.Is1to9Pandigital (a)) {
					continue;
				}
				if (a % 10 == 1) {
					// x1 * yz = ??z
					continue;
				}

				for (ulong b = a; b <= max / a; b++) {
					if (b % 10 == 1) {
						// x1 * yz = ??z, thus can never be pandigital
						continue;
					}

					ulong c = a * b;
					var pan = Pandigital.Is1to9Pandigital (a, b, c);
					if (9 != pan) {
						continue;
					}
					all.Add (c);
					Console.WriteLine (a + " x " + b + " = " + c + "\t\ttotal: " + all.Count + ", sum " + all.Sum (x => (long) x));
				}
			}
		}
Example #12
0
        public void Solve() {
            HashSet<int> p = new HashSet<int>();  //guarantees uniqueness of items

            foreach (var i in 2.To(100)) {
                int start = 1234;

                if (i > 9)
                    start = 123;

                foreach (var j in start.To(10000 / i + 1)) {
                    string s = (i.ToString() + j.ToString() + (i * j).ToString());
                    if (s.ToLong().IsPanDigital()) {
                        p.Add(i * j);
                    }
                }
            }

            Util.WL("The sum of all products whose multiplicand/multiplier/product\nidentity can be written as a 1 through 9 pandigital is {0}"
                .FormatWith(p.Sum()));
        }
Example #13
0
        public long Solve()
        {
            var values = new HashSet<long> { 1 };

            for (var number = 2L; number <= Math.Sqrt(Limit); number++)
            {
                var powerSpecial = number * number;
                var sumSpecial = number + powerSpecial;

                while ((sumSpecial + 1) <= Limit)
                {
                    values.Add(sumSpecial + 1);

                    powerSpecial = powerSpecial * number;
                    sumSpecial = sumSpecial + powerSpecial;
                }
            }

            return values.Sum();
        }
Example #14
0
        public static int Answer()
        {
            var d = Util.Memoize<int, int>(n => MathEx.Divisors(n).Where(i => i != n).Sum());
            var amicableNumbers = new HashSet<int>();
            int max = 9999;

            for (int a = 1; a <= max; a++)
            {
                for (int b = a; b <= max; b++)
                {
                    if (a != b && d(a) == b && d(b) == a)
                    {
                        amicableNumbers.Add(a);
                        amicableNumbers.Add(b);
                    }
                }
            }

            return amicableNumbers.Sum();
        }
Example #15
0
        static void Main(string[] args)
        {
            HashSet<int> amicableNumbers = new HashSet<int>();

            for (int i = 220; i < 10000; i++)
            {
                if (amicableNumbers.Contains(i)) continue;
                int sum = Factorize(i).Sum();
                int sumCheck = Factorize(sum).Sum();
                if (sumCheck == i && sum != i)
                {
                    Console.WriteLine(i + " " + sum);
                    amicableNumbers.Add(i);
                    amicableNumbers.Add(sum);
                }

            }
            Console.WriteLine();
            Console.WriteLine(amicableNumbers.Sum());
            Console.ReadKey();
        }
Example #16
0
 static void Main(string[] args)
 {
     HashSet<int> results = new HashSet<int>();
     for(int n = 2; n < 50000; n++)
     {
         for(int m = 2; m <= Math.Sqrt(n); m++)
         {
             if(n % m == 0)
             {
                 int p = n / m;
                 if(is9PalindromicTriplet(n, m, p))
                 {
                     results.Add(n);
                     Console.WriteLine(n + " = " + m + " * " + p);
                 }
             }
         }
     }
     Console.WriteLine(results.Sum());
     Console.ReadLine();
 }
Example #17
0
		public P125 ()
		{
			ulong max = 100000000;
			var set = new HashSet<ulong> ();

			for (ulong start = 1; start < max; start++) {
				ulong sum = start * start;

				for (ulong cur = start + 1; ; cur++) {
					sum += cur * cur;
					if (sum >= max) {
						break;
					}
					if (Palindrome.IsPalindrome (sum)) {
						Console.WriteLine (sum + "\t" + start + "\t" + cur);
						set.Add (sum);
					}
				}
			}

			Console.WriteLine (set.Sum (x => (long) x));
		}
Example #18
0
        static void Main(string[] args)
        {
            var all = CombinatoricsUtilities.Permutations(Enumerable.Range(1, 9));

            var magicProducts = new HashSet<int>();

            foreach (var permutation in all.Select(p => string.Join("", p)))
            {
                // X1 X2 X3 ... X9
                // can multiply and equality signs be placed to form valid equation?
                // X1 x X2 X3 X3 X4 = X5 X6 X7 X8 X9
                // X1 X2 x X3 X3 X4 = X5 X6 X7 X8 X9
                // X1 X2 X3 x X3 X4 = X5 X6 X7 X8 X9
                // X1 X2 X3 X3 x X4 = X5 X6 X7 X8 X9

                for (int multLoc = 1; multLoc < 9 - 2; multLoc++)
                {
                    for (int equalsLoc = multLoc + 1; equalsLoc < 9; equalsLoc++)
                    {
                        // check that it forms correct equation
                        // a x b = c

                        int a = int.Parse(permutation.Substring(0, multLoc));
                        int b = int.Parse(permutation.Substring(multLoc, equalsLoc - multLoc));
                        int c = int.Parse(permutation.Substring(equalsLoc));

                        if (a * b == c)
                        {
                            string.Format("{0} x {1} = {2}", a, b, c).Dump();

                            magicProducts.Add(c);
                        }
                    }
                }
            }

            magicProducts.Sum().Dump("Answer");
        }
Example #19
0
        public long Solve()
        {
            var allSums = new HashSet<long>();

            for (var start = 1L; start <= 10000L; start++)
            {
                var sum = start * start;
                for (var next = start + 1; next <= 10000L; next++)
                {
                    sum += next * next;

                    if (sum > Max)
                        break;

                    if (this.IsPalindrom(sum))
                    {
                        Console.WriteLine("{0} - {1} {2}", start, next, sum);
                        allSums.Add(sum);
                    }
                }
            }

            return allSums.Sum();
        }
Example #20
0
        static void Main(string[] args)
        {
            HashSet<int> numbers = new HashSet<int>();
            for (int k = 2; k <= 12; k++)
            {
                for (int i = k; i <= k * k; i++)
                {
                    List<int> factors = i.PrimeFactors().ToList();
                    while(factors.Count < k)
                    {
                        factors.Add(1);
                    }
                    factors.Sort();
                    int j = factors.Count - 1;
                    while (factors[j] != 1 && factors.Sum() != factors.Product())
                    {
                        factors[j - 1] = factors[j] * factors[j - 1];
                        factors.Remove(factors[j]);
                        factors.Insert(0, 1);
                        j--;
                    }

                    if (factors.Sum() == factors.Product())
                    {
                        Console.WriteLine(k + " " + i + "    " + factors.ToStringPretty());
                        if (! numbers.Contains(i))
                        {
                            numbers.Add(i);
                        }
                        break;
                    }
                }
            }
            Console.WriteLine(numbers.Sum());
            Console.ReadKey();
        }
Example #21
0
        public override string GetAnswer()
        {
            HashSet<int> datas = new HashSet<int>();

            StringBuilder str = new StringBuilder();

            for (int i = 2; i <= 10000; i++) {
                int d1 = functionD(i);
                if (i == functionD(d1) && i != d1) {
                    datas.Add(i);
                    str.AppendFormat("친화수 쌍 : {0}, {1}", i, d1);
                    str.AppendLine();
                }
            }

            str.AppendFormat("친화수 ({0}개) : ", datas.Count);
            foreach(int data in datas) {
                str.AppendFormat("{0}, ", data);
            }
            str.AppendLine();
            str.AppendFormat("총합 : {0}", datas.Sum());

            return str.ToString();
        }
Example #22
0
		private static string ResponseStatusAll(ulong steamID) {
			if (steamID == 0) {
				Logging.LogNullError(nameof(steamID));
				return null;
			}

			if (!IsOwner(steamID)) {
				return null;
			}

			HashSet<Bot> botsRunning = new HashSet<Bot>(Bots.Where(bot => bot.Value.KeepRunning).OrderBy(bot => bot.Key).Select(bot => bot.Value));
			IEnumerable<string> statuses = botsRunning.Select(bot => bot.ResponseStatus(steamID));

			return Environment.NewLine +
				string.Join(Environment.NewLine, statuses) + Environment.NewLine +
				"There are " + botsRunning.Count + "/" + Bots.Count + " bots running, with total of " + botsRunning.Sum(bot => bot.CardsFarmer.GamesToFarm.Count) + " games (" + botsRunning.Sum(bot => bot.CardsFarmer.GamesToFarm.Sum(game => game.CardsRemaining)) + " cards) left to farm.";
		}
        private static Dictionary<int, double> CalculateComponentFunctionValues(Graph graph,
            Dictionary<Vertex, int> components)
        {
            Dictionary<int, double> fValues = new Dictionary<int, double>();
            foreach (var componentNumber in components.Values.Distinct())
            {
                //Get all edges in this component
                HashSet<Edge> edgesInComponent = new HashSet<Edge>();
                var verticesInComponent = components.Where(x => x.Value == componentNumber).Select(x => x.Key);
                var nrOfTerminals = verticesInComponent.Count(x => graph.Terminals.Contains(x));
                foreach (var v in verticesInComponent)
                {
                    foreach (var e in graph.GetEdgesForVertex(v))
                        edgesInComponent.Add(e);
                }

                if (edgesInComponent.Count > 0)
                {
                    double fVal = edgesInComponent.Sum(x => x.Cost)/Math.Pow(nrOfTerminals, 2);
                    fValues.Add(componentNumber, fVal);
                }
                else
                    fValues.Add(componentNumber, double.MaxValue);
            }
            return fValues;
        }
        public string Solve()
        {
            Func<string, int> getFitness = child =>
            {
                var queenLocations = new HashSet<Point>(child.Select(x => x.ToPoint(GeneSet, BoardWidth)));
                int fitness = queenLocations.Sum(x => CountQueensAttacked(GetAttackablePoints(x), queenLocations));
                fitness += 10000 * (GeneCount - queenLocations.Count);
                return fitness;
            };

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            Action<int, int, string, string> displayCurrentBest =
                (generation, fitness, genes, strategy) =>
                {
                    var board = new char?[BoardHeight, BoardWidth];

                    foreach (var queenLocation in genes.Select(x => x.ToPoint(GeneSet, BoardWidth)))
                    {
                        board[queenLocation.X, queenLocation.Y] = 'Q';
                    }

                    for (int i = 0; i < BoardHeight; i++)
                    {
                        for (int j = 0; j < BoardWidth; j++)
                        {
                            Console.Write(board[i, j] ?? '.');
                            Console.Write(' ');
                        }
                        Console.WriteLine();
                    }
                    Console.WriteLine("generation\t{0} fitness\t{1} elapsed: {2}",
                                      generation.ToString().PadLeft(5, ' '),
                                      fitness.ToString().PadLeft(2, ' '),
                                      stopwatch.Elapsed);
                };
            var geneticSolver = new GeneticSolver
            {
                GetCanonicalGenes = GetCanonicalGenes,
                MaxSecondsWithoutImprovement = 5
            };
            string result = geneticSolver.GetBest(GeneCount,
                                                  GeneSet,
                                                  getFitness,
                                                  displayCurrentBest);
            Console.WriteLine(result);
            return getFitness(result) == 0
                       ? GetCanonicalGenes(result)
                       : null;
        }
        public static int spiralSum(int size)
        {
            List<List<int>> grid = new List<List<int>>(size);
            for (int i = 0; i < size; i++) {
                grid.Add(new List<int>(size));
                for (int j = 0; j < size; j++) {
                    grid[i].Add(0);
                }
            }
            Direction dir = Direction.Left;
            bool filled = false;
            int currentNumber = size * size;
            int currentSize = size;
            int numMade = 0;
            int x = size - 1;
            int y = 0;

            while (filled == false) {
                grid[y][x] = currentNumber;
                currentNumber--;
                numMade++;
                if (currentNumber == 0) {
                    filled = true;
                }
                if (numMade == currentSize) {
                    numMade = 0;
                    switch (dir) {
                        case Direction.Left:
                            dir = Direction.Down;
                            currentSize--;
                            break;
                        case Direction.Down:
                            dir = Direction.Right;
                            break;
                        case Direction.Right:
                            dir = Direction.Up;
                            currentSize--;
                            break;
                        case Direction.Up:
                            dir = Direction.Left;
                            break;
                    }
                }
                switch (dir) {
                    case Direction.Left:
                        x--;
                        break;
                    case Direction.Down:
                        y++;
                        break;
                    case Direction.Right:
                        x++;
                        break;
                    case Direction.Up:
                        y--;
                        break;
                }
            }
            int sum = 0;
            x = 0;
            y = 0;
            HashSet<int> nums = new HashSet<int>();
            while (y < size && x < size) {
                /*Console.Write(grid[y][x]);
                Console.Write(", ");*/
                nums.Add(grid[y][x]);
                x++;
                y++;
            }
            //Console.WriteLine();
            x = size - 1;
            y = 0;
            while (y < size && x >= 0) {
                //Console.Write("{0}, ", grid[y][x]);
                nums.Add(grid[y][x]);
                y++;
                x--;
            }
            sum = nums.Sum();
               // Console.WriteLine();

            return sum;
        }
 private double JU(HashSet<int> unlabelled)
 {
     return unlabelled.Sum(index => JU_ii(index));
 }
 private double JL(HashSet<int> labelled)
 {
     return labelled.Sum(index => JL_ii(index));
 }
Example #28
0
        public PoiType TakePoiByDistribution(HashSet<PoiType> poiSet)
        {
            if (_poiTypesDistributionDict == null)
            {
                _poiTypesDistributionDict = new Dictionary<PoiType, double>();

                var totalFrequency = poiSet.Sum(poiType => poiType.Frequency);
                var orderedPois = poiSet.OrderBy(p => p.Frequency);

                double currentFreq = 0;

                foreach (var poiType in orderedPois)
                {
                    currentFreq += poiType.Frequency/totalFrequency;
                    _poiTypesDistributionDict.Add(poiType, currentFreq);
                }
            }

            var d = _random.NextDouble();

            return (from dictEntry in _poiTypesDistributionDict where d <= dictEntry.Value select dictEntry.Key).FirstOrDefault();
        }
Example #29
0
        protected override long GetCalculationResult()
        {
            const int max = 100000;
            const int halfmax = max / 2;

            var squares = new List<long>(halfmax) { 0 };

            for (int i = 1; i < halfmax; i++)
            {
                squares.Add(i * i);
            }

            var result = new HashSet<long>();

            for (int i = 1; i < squares.Count; i++)
            {
                for (int j = 1; j < squares.Count; j++)
                {
                    long res = squares[i] + squares[j];
                    if (squares.Contains(res))
                    {
                        long l = i + j + (int)Math.Sqrt(res);
                        if (!result.Contains(l))
                        {
                            //Print(
                            //    "{6} - {0}^2 + {1}^2 == {2} ({3} + {4} == {5})",
                            //    i,
                            //    j,
                            //    Math.Sqrt(res),
                            //    squares[i],
                            //    squares[j],
                            //    res,
                            //    l);
                            result.Add(l);
                        }
                    }
                    if (res > halfmax)
                    {
                        break;
                        Print("{0}", i);
                    }
                }
            }

            return result.Sum();
        }
Example #30
0
        void Main()
        {
            // Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

            HashSet<int> pandigital = new HashSet<int>();

            for (int i = 1000; i < 10000; i++)
            {
                String s = Convert.ToString(i);
                if (!s.Contains("0") && (s.ToCharArray().Count() == s.ToCharArray().Distinct().Count()))
                {
                    if (IsPandigital(i))
                    {
                        Console.WriteLine("Adding: " + i);
                        pandigital.Add(i);
                    }
                }
            }

            Console.WriteLine("Sum: " + pandigital.Sum());
        }