public static HashSet <long> GetFactors(long n) { if (FactorsDictionary.ContainsKey(n)) { return(FactorsDictionary[n]); } // initialize the factor list to the prime factors and 1 and n var primeFactors = Sequences.GetPrimeFactors(n); var factorSet = new HashSet <long>(primeFactors) { 1, n }; // divide by primes and recursively determine the factors to be aggregated foreach (var prime in primeFactors) { var factor = n / prime; if (factor <= 2 || factorSet.Contains(factor)) { continue; } foreach (var subfactor in GetFactors(factor)) { factorSet.Add(subfactor); } } FactorsDictionary[n] = factorSet; return(factorSet); }
/// <summary> /// Find the prime factors of a^b. /// </summary> public static IEnumerable <long> PowerFactors(int a, int b) { var baseFactors = Sequences.GetPrimeFactors(a); var allFactors = Enumerable.Range(0, b).SelectMany(n => baseFactors); return(from factor in allFactors orderby factor select factor); }
public string Solve() { var answer = Sequences.LongRange(1, int.MaxValue) .First(n => { var count = new[] { n, n + 1, n + 2, n + 3 } .TakeWhile(x => Sequences.GetPrimeFactors(x).Distinct().Count() == 4) .Count(); return(count == 4); }); return(answer.ToString()); }
public static long GetGreatestCommonFactor(long a, long b) { var aPrimeFactors = Sequences.GetPrimeFactors(a).GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count()); var bPrimeFactors = Sequences.GetPrimeFactors(b).GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count()); // collect the factors between the two, similar to Problem005, // except this time pool the shared minimums var minCount = new Dictionary <long, int>(); foreach (var factor in aPrimeFactors.Concat(bPrimeFactors)) { if (aPrimeFactors.ContainsKey(factor.Key) && bPrimeFactors.ContainsKey(factor.Key)) { minCount[factor.Key] = minCount.ContainsKey(factor.Key) ? Math.Min(minCount[factor.Key], factor.Value) : factor.Value; } } return(minCount.Aggregate <KeyValuePair <long, int>, long>( 1, (current, factor) => current * (long)Math.Pow(factor.Key, factor.Value))); }
static long CommonFactorCountSolve() { // find the common factors between the numbers 1 to 20 var factorCounts = Sequences.LongRange(1, 20).Select(n => Sequences.GetPrimeFactors(n).GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count())); // collect the maximum factor counts for each of the numbers; // for instance, 16 is 2^4, so the 2 factors of 20 (2*2*5) // are not necessary as they are already accounted for var maxCount = new Dictionary <long, int>(); foreach (var factor in factorCounts.SelectMany(factorCount => factorCount)) { maxCount[factor.Key] = maxCount.ContainsKey(factor.Key) ? Math.Max(maxCount[factor.Key], factor.Value) : factor.Value; } // compute the smallest number that is divisible by all numbers from 1 to 20, // ie, the number with the minimum number of factors shared by those numbers return(maxCount.Aggregate <KeyValuePair <long, int>, long>( 1, (current, factor) => current * (long)Math.Pow(factor.Key, factor.Value) )); }