Ejemplo n.º 1
0
        protected override string Solve()
        {
            int result = 0;

            IEnumerable <long> primes = PrimeHelper.GeneratePrimes(999999);

            foreach (long prime in primes)
            {
                IEnumerable <long> rotations = NumberHelper.GetRotations(prime);

                int primeCount = 0;

                foreach (long rotation in rotations)
                {
                    if (PrimeHelper.IsPrime(rotation))
                    {
                        primeCount++;
                    }
                }

                if (primeCount == rotations.Count())
                {
                    result++;
                }
            }

            return(result.ToString("0"));
        }
Ejemplo n.º 2
0
    public void Primes()
    {
        var expected = 15485863;
        var actual   = PrimeHelper.Primes().Skip(1000000 - 1).First();

        Assert.Equal(expected, actual);
    }
Ejemplo n.º 3
0
        //Problem 7: 10001st prime
        //By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
        //What is the 10 001st prime number?
        //Answer: 104743
        //First Time: 18 seconds
        //Second Time: 0.003 seconds
        public string GetAnswer()
        {
            var primes = PrimeHelper.FindPrimes_ToCount(10001);
            var answer = primes.Last();

            return("Problem 7: " + answer.ToString());
        }
Ejemplo n.º 4
0
        //Problem 10: Summation of primes
        //The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
        //Find the sum of all the primes below two million.
        //Problem 10 Answer: 142913828922
        //First Elapsed Time (seconds): 4 hours something - forgot to sieve
        //Second Elapsed Time (seconds): 0.0190295
        public string GetAnswer()
        {
            var primes = PrimeHelper.FindPrimes_ToLimit(2000000);
            var sum    = primes.Sum();

            return("Problem 10: " + sum.ToString());
        }
Ejemplo n.º 5
0
        void Resize()
        {
            int newSize = PrimeHelper.ToPrime((table.Length << 1) | 1);

            // allocate new hash table and link slots array
            var newTable = new int [newSize];
            var newLinks = new Link [newSize];

            for (int i = 0; i < table.Length; i++)
            {
                int current = table [i] - 1;
                while (current != NO_SLOT)
                {
                    int hashCode = newLinks [current].HashCode = GetItemHashCode(slots [current]);
                    int index    = (hashCode & int.MaxValue) % newSize;
                    newLinks [current].Next = newTable [index] - 1;
                    newTable [index]        = current + 1;
                    current = links [current].Next;
                }
            }

            table = newTable;
            links = newLinks;

            // allocate new data slots, copy data
            var newSlots = new T [newSize];

            Array.Copy(slots, 0, newSlots, 0, touched);
            slots = newSlots;

            threshold = (int)(newSize * DEFAULT_LOAD_FACTOR);
        }
Ejemplo n.º 6
0
    private void Resize(int newSize)
    {
      // Hash table size needs to be prime.
      newSize = PrimeHelper.NextPrime(newSize);

      var newTable = new int[newSize];
      var newSlots = new Slot[newSize];

      // Copy current slots.
      Array.Copy(_slots, 0, newSlots, 0, _touchedSlots);

      // Update hash table and rebuild chains.
      for (int slotIndex = 0; slotIndex < _touchedSlots; slotIndex++)
      {
        int hashCode = GetHashCode(newSlots[slotIndex].ObjectA, newSlots[slotIndex].ObjectB);
        int tableIndex = hashCode % newSize;
        newSlots[slotIndex].Next = newTable[tableIndex] - 1;
        newTable[tableIndex] = slotIndex + 1;
      }

      _table = newTable;
      _slots = newSlots;

      if (_used != null)
      {
        var newUsed = new bool[newSize];
        Array.Copy(_used, 0, newUsed, 0, _touchedSlots);
        _used = newUsed;
      }
    }
Ejemplo n.º 7
0
        //The prime factors of 13195 are 5, 7, 13 and 29.

        //What is the largest prime factor of the number 600851475143 ?
        public static long Execute()
        {
            const long value        = 600851475143;
            long       largestPrime = 0;
            var        max          = Math.Ceiling(Math.Sqrt(value));

            for (long i = 2; i < max; i++)
            {
                if (value % i != 0)
                {
                    continue;
                }

                if (PrimeHelper.IsPrime(i))
                {
                    largestPrime = i;
                }

                var divider = value / i;

                if (!PrimeHelper.IsPrime(divider))
                {
                    continue;
                }

                largestPrime = divider;
                i            = divider;
            }

            return(largestPrime);
        }
Ejemplo n.º 8
0
        public void Get10001stPrime()
        {
            var findPrime = new PrimeHelper();
            var result    = findPrime.GetNthPrime(10001);

            Assert.True(result == 104743);
        }
Ejemplo n.º 9
0
        protected override string Solve()
        {
            int result = 0;

            for (int i = 1; i < 10; i++)
            {
                string numberString = string.Empty;

                for (int j = 1; j <= i; j++)
                {
                    numberString += j.ToString();
                }

                int number = int.Parse(numberString);

                int[] permutations = number.GetPermutations();

                foreach (int candidate in permutations)
                {
                    if (PrimeHelper.IsPrime(candidate) &&
                        candidate > result)
                    {
                        result = candidate;
                    }
                }
            }

            return(result.ToString("0"));
        }
Ejemplo n.º 10
0
        public void Solve()
        {
            var  ph     = new PrimeHelper();
            long result = ph.PrimesAtOrdinal(10001);

            Console.WriteLine($"Problem 7: {result}");
        }
Ejemplo n.º 11
0
    /// <summary>
    /// Sets the capacity of the <see cref="HashSetEx{T}"/> to a value suitable for the current
    /// number of elements in the set.
    /// </summary>
    /// <remarks>
    /// <para>
    /// This method can be used to minimize a collection's memory overhead if no new elements will 
    /// be added to the collection.
    /// </para>
    /// <para>
    /// This method is an O(n) operation, where n is <see cref="Count"/>. 
    /// </para>
    /// <para>
    /// To reset a <see cref="HashSetEx{T}"/> to its initial state, call the <see cref="Clear"/> 
    /// method before calling <see cref="TrimExcess"/> method. Trimming an empty 
    /// <see cref="HashSetEx{T}"/> sets the capacity of the <see cref="HashSetEx{T}"/> to the
    /// default capacity.
    /// </para>
    /// </remarks>
    public void TrimExcess()
    {
      // Similar to Resize(), except that TrimExcess() compacts the items and clears 
      // the free list!

      int newSize = PrimeHelper.NextPrime((_count > 0) ? _count : InitialSize);
      int[] newTable = new int[newSize];
      var newSlots = new Slot[newSize];

      // Insert items in new hash table and slots (without recomputing the hash code).
      int newIndex = 0;
      for (int oldIndex = 0; oldIndex < _touchedSlots; oldIndex++)
      {
        if (_slots[oldIndex].HashCode >= 0)
        {
          newSlots[newIndex].HashCode = _slots[oldIndex].HashCode;
          newSlots[newIndex].Item = _slots[oldIndex].Item;

          int tableIndex = newSlots[newIndex].HashCode % newSize;
          newSlots[newIndex].Next = newTable[tableIndex] - 1;
          newTable[tableIndex] = newIndex + 1;
          newIndex++;
        }
      }

      _table = newTable;
      _slots = newSlots;
      _touchedSlots = newIndex;
      _freeList = -1;
      _version++;
    }
Ejemplo n.º 12
0
        public BigInteger Solve(BigInteger?input = null)
        {
            int result      = 0;
            int primesLimit = 100000;

            while (result == 0)
            {
                BigInteger numberOfPrimes = 0;
                bool[]     test           = PrimeHelper.FindPrimesUnderLimit(primesLimit);
                for (int i = 0; i < test.Length; i++)
                {
                    if (test[i])
                    {
                        numberOfPrimes++;

                        if (numberOfPrimes == input)
                        {
                            result = i;
                        }
                    }
                }

                primesLimit += 100000;
            }
            return(result);
        }
Ejemplo n.º 13
0
    private void Resize(int newSize)
    {
      // Similar to TrimAccess(), except that Resize() does not compact the items.
      // The free list remains!

      // Hash table size needs to be prime.
      newSize = PrimeHelper.NextPrime(newSize);

      var newTable = new int[newSize];
      var newSlots = new Slot[newSize];

      // Copy current slots.
      Array.Copy(_slots, 0, newSlots, 0, _touchedSlots);

      // Update hash table and rebuild chains.
      for (int slotIndex = 0; slotIndex < _touchedSlots; slotIndex++)
      {
        int tableIndex = newSlots[slotIndex].HashCode % newSize;
        newSlots[slotIndex].Next = newTable[tableIndex] - 1;
        newTable[tableIndex] = slotIndex + 1;
      }

      _table = newTable;
      _slots = newSlots;
    }
Ejemplo n.º 14
0
        public void TestIsPrime()
        {
            var input = new[]
            {
                18, 13, 68, 99, 93, 34, 11, 47, 64, 10,
                809, 3420, 9391, 8999, 5154, 8934, 5416, 5669, 2755, 3159,
                285080, 727881, 846232, 665370, 153194, 157833, 585896, 914054, 505284, 333258,
                49086597, 78119724, 76928802, 23260170, 1955743, 39360664, 10885879, 30169506, 65889970, 95425647,
                179424551, 179424571, 179424577, 179424601, 179424611, 179424617, 179424629, 179424667, 179424671, 179424673,
                1683899352, 883641873, 114883641, 1000000007, 1000000009, 1000000021, 1000000033, 1000000087, 1000000093, 2147483629
            };
            var output = new[]
            {
                0, 1, 0, 0, 0, 0, 1, 1, 0, 0,
                1, 0, 1, 1, 0, 0, 0, 1, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                0, 0, 0, 1, 1, 1, 1, 1, 1, 1
            };

            Assert.AreEqual(input.Length, output.Length, "setup");
            for (var index = 0; index < output.Length; index++)
            {
                Assert.AreEqual(output[index] == 1, PrimeHelper.IsPrime(input[index]));
            }
        }
Ejemplo n.º 15
0
        public void TestToPrime()
        {
            var input = new[]
            {
                18, 13, 68, 99, 93, 34, 11, 47, 64, 10,
                809, 3420, 9391, 8999, 5154, 8934, 5416, 5669, 2755, 3159,
                285080, 727881, 846232, 665370, 153194, 157833, 585896, 914054, 505284, 333258,
                49086597, 78119724, 76928802, 23260170, 1955743, 39360664, 10885879, 30169506, 65889970, 95425647,
                179424551, 179424571, 179424577, 179424601, 179424611, 179424617, 179424629, 179424667, 179424671, 179424673,
                1683899352, 883641873, 114883641, 1000000007, 1000000009, 1000000021, 1000000033, 1000000087, 1000000093
            };
            var output = new[]
            {
                19, 13, 71, 101, 97, 37, 11, 47, 67, 11,
                809, 3433, 9391, 8999, 5167, 8941, 5417, 5669, 2767, 3163,
                285091, 727891, 846233, 665381, 153247, 157837, 585899, 914117, 505301, 333269,
                49086613, 78119749, 76928807, 23260187, 1955747, 39360683, 10885891, 30169523, 65889997, 95425663,
                179424551, 179424571, 179424577, 179424601, 179424611, 179424617, 179424629, 179424667, 179424671, 179424673,
                1683899359, 883641893, 114883661, 1000000007, 1000000009, 1000000021, 1000000033, 1000000087, 1000000093
            };

            Assert.AreEqual(input.Length, output.Length, "setup");
            for (var index = 0; index < output.Length; index++)
            {
                Assert.AreEqual(output[index], PrimeHelper.ToPrime(input[index]));
                Assert.IsTrue(PrimeHelper.IsPrime(output[index]));
            }
        }
Ejemplo n.º 16
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);
        }
Ejemplo n.º 17
0
        private void btnGenerateSequenceToFile_Click(object sender, EventArgs e)
        {
            if (!IsFilterOpen)
            {
                return;
            }

            string filename = FormHelper.SaveFileDlg(FormHelper.FiletypeFilters.SequenceFiles);

            if (!string.IsNullOrWhiteSpace(filename))
            {
                int randomNumber = rand.Next(50000);

                BigInteger randomIncrementValue = PrimeHelper.GetPreviousPrime(randomNumber);

                ByteGenerator.SequenceGenerator randomSequence = new ByteGenerator.SequenceGenerator(8, randomNumber, (int)randomIncrementValue);

                int           counter            = 0;
                int           maxElements        = filter.MaxElementsToHash / 2;
                List <string> elementsCollection = new List <string>();
                while (counter < maxElements)
                {
                    string nextElement = randomSequence.GetNext();
                    elementsCollection.Add(nextElement);
                    counter++;
                }

                File.WriteAllLines(filename, elementsCollection);
            }
        }
Ejemplo n.º 18
0
 public void TestBasicNonPrimes1To10()
 {
     int[] notPrimes = { 1, 4, 6, 8, 9, 10 };
     foreach (int notPrime in notPrimes)
     {
         Assert.IsFalse(PrimeHelper.IsPrime(notPrime), $"{notPrime} was found to be prime");
     }
 }
Ejemplo n.º 19
0
        public void GetNthPrime(uint nthPrime, uint target)
        {
            var findPrime = new PrimeHelper();

            var result = findPrime.GetNthPrime(nthPrime);

            Assert.True(result == target);
        }
Ejemplo n.º 20
0
 public void TestBasicPrimes1To10()
 {
     int[] primes = { 2, 3, 5, 7 };
     foreach (int prime in primes)
     {
         Assert.IsTrue(PrimeHelper.IsPrime(prime), $"{prime} was not found to be prime");
     }
 }
Ejemplo n.º 21
0
    /// <summary>
    /// Initializes a new instance of the <see cref="SynchronizedHashtable{TKey,TValue}"/> class.
    /// </summary>
    /// <param name="capacity">The number of buckets in the hash table.</param>
    /// <remarks>
    /// For efficiency the <paramref name="capacity"/> is automatically incremented to the next 
    /// prime number.
    /// </remarks>
    /// <exception cref="ArgumentOutOfRangeException">
    /// <paramref name="capacity"/> is less than 1.
    /// </exception>
    public SynchronizedHashtable(int capacity)
    {
      if (capacity < 1)
        throw new ArgumentOutOfRangeException("capacity", "The initial capacity must be greater than 0.");

      capacity = PrimeHelper.NextPrime(capacity);
      _buckets = new Node[capacity];
    }
Ejemplo n.º 22
0
        public void TestGetLowestAndHighestFactor()
        {
            int number = 909;
            LowestAndHighestFactor factors         = PrimeHelper.GetLowestAndHighestFactor(number);
            LowestAndHighestFactor expectedFactors = new LowestAndHighestFactor(3, 303);

            Assert.AreEqual(expectedFactors.lowest, factors.lowest, $"The lowest factor of {number} was incorrect");
            Assert.AreEqual(expectedFactors.highest, factors.highest, $"The highest factor of {number} was incorrect");
        }
Ejemplo n.º 23
0
        public void Solve()
        {
            var  helper = new PrimeHelper();
            long input  = 600851475143;

            List <long> primeFactorisation = helper.PrimeFactorisation(input);

            Console.WriteLine($"Problem 3: {primeFactorisation.Max ()}");
        }
        public static int ExpandPrime(int oldSize)
        {
            int num = 2 * oldSize;

            if (num > 2146435069 && 2146435069 > oldSize)
            {
                return(2146435069);
            }
            return(PrimeHelper.GetPrime(num));
        }
Ejemplo n.º 25
0
        protected override string Solve()
        {
            long result = 0;

            IEnumerable <long> primes = PrimeHelper.GeneratePrimes(1999999);

            result = primes.Sum();

            return(result.ToString("0"));
        }
Ejemplo n.º 26
0
    public void PrimesRepeatability()
    {
        var primes = PrimeHelper.Primes().Take(20).ToArray();
        var p2     = PrimeHelper.Primes().Take(20).ToArray();

        for (var i = 0; i < p2.Length; i++)
        {
            Assert.Equal(primes[i], p2[i]);
        }
    }
Ejemplo n.º 27
0
        public void GetAllTruncatablePrimes_WhenCalled_ReturnsExpectedNumberOfPrimes()
        {
            // Arrange
            var expectedNumberOfTruncatablePrimes = 11;

            // Act
            var result = PrimeHelper.GetAllTruncatablePrimes();

            // Result
            result.Should().HaveCount(expectedNumberOfTruncatablePrimes);
        }
Ejemplo n.º 28
0
    private void Initialize(int capacity)
    {
      capacity = PrimeHelper.NextPrime(capacity);

      _table = new int[capacity];
      _slots = new Slot[capacity];
      _touchedSlots = 0;
      _freeList = -1;
      _count = 0;
      _version = 0;
    }
Ejemplo n.º 29
0
        public void TestPrimeBounds()
        {
            // 2147483629 is tha last prime below int.MaxValue
            Assert.AreEqual(2, PrimeHelper.NextPrime(-1));
            Assert.AreEqual(3, PrimeHelper.NextPrime(2));
            Assert.Throws <OverflowException>(() => PrimeHelper.NextPrime(2147483629));

            // 2147483629 is tha last prime below int.MaxValue
            Assert.AreEqual(2, PrimeHelper.ToPrime(-1));
            Assert.AreEqual(2, PrimeHelper.ToPrime(2));
            Assert.AreEqual(2147483629, PrimeHelper.ToPrime(2147483629));
        }
Ejemplo n.º 30
0
        protected override string Solve()
        {
            //stab in the dark here, the 10001st prime is probably below 10million?

            //could check numbers incrementally as prime or not, but a Sieve would be faster still

            IList <long> primes = PrimeHelper.GeneratePrimes(10000000).ToList();

            primes.OrderBy(o => o);

            return(primes[10000].ToString("0"));
        }