Example #1
0
        private static long GetSmallestMultiple(IEnumerable <int> numbers)
        {
            long smallestMultiple     = 1;
            var  listOfFactorizations = numbers.Select(number => PrimeHelper.GetPrimeFactorization(number));
            Dictionary <int, int> factorizationOfAnswer = GetPrimeFactorizationOfSmallestMultiple(listOfFactorizations);

            foreach (var key in factorizationOfAnswer.Keys)
            {
                smallestMultiple *= (long)Math.Pow(key, factorizationOfAnswer[key]);
            }
            return(smallestMultiple);
        }
Example #2
0
        public void GetPrimeFactorization_18_ReturnsExpectedDictionary()
        {
            // Arrange
            var number             = 18;
            var expectedDictionary = new Dictionary <int, int>
            {
                [2] = 1,
                [3] = 2
            };

            // Act
            var result = PrimeHelper.GetPrimeFactorization(number);

            // Assert
            result.Should().BeEquivalentTo(expectedDictionary);
        }
Example #3
0
        private static BigInteger CalculatePrimitiveRoot(BigInteger p)
        {
            // Check if p is prime or not
            if (!PrimeHelper.IsProbablePrime(p))
            {
                throw new ArgumentException($"Parameter {nameof(p)} must be a prime number.", nameof(p));
            }

            BigInteger phi = p - 1;             // The Euler Totient function phi of a prime number p is p-1
            IEnumerable <BigInteger> primeFactors = PrimeHelper.GetPrimeFactorization(phi).Distinct();
            List <BigInteger>        powersToTry  = primeFactors.Select(factor => phi / factor).ToList();

            for (int r = 2; r <= phi; r++)                                 // Check for every number from 2 to phi
            {
                if (powersToTry.All(n => BigInteger.ModPow(r, n, p) != 1)) // If there was no n such that r^n ≡ 1 (mod p)
                {
                    return(r);                                             // We found our primitive root
                }
            }

            throw new Exception($"No primitive root found for prime {p}!");             // If no primitive root found
        }