/// <summary> /// Returns an array of Factors for a series from 2..maxDivisor. /// </summary> /// <param name="maxDivisor"></param> /// <returns></returns> private PrimeFactors[] GetPrimeFactorsForSeries(int maxDivisor) { var primeFactors = new PrimeFactors[maxDivisor - 1]; for (int divisor = 2; divisor <= maxDivisor; divisor++) { primeFactors[divisor - 2] = new PrimeFactors(divisor); } return primeFactors; }
/// <summary> /// This algorithm uses factorial math to speed up the processing. /// </summary> /// <param name="maxDivisor"></param> /// <returns></returns> /// <remarks>Relies on the fact that common prime factors can be removed to determine /// LCM (lowest common multiples) of two numbers.</remarks> public long GetSmallestPositiveNumberEvenlyDivisibleBySeries(int maxDivisor) { var primeFactors = GetPrimeFactorsForSeries(maxDivisor); var divisibleFactors = new PrimeFactors(); for (int i = 0; i < primeFactors.Length; i++) { // Calculate LCM divisibleFactors.AddFactors( primeFactors[i].RemoveFactors(divisibleFactors)); } return divisibleFactors.Product; }
public PrimeFactors RemoveFactors(PrimeFactors factorsToRemove) { foreach (long factorToRemove in factorsToRemove.Factors) MyFactors.Remove(factorToRemove); return this; }
public PrimeFactors AddFactors(PrimeFactors factorsToAdd) { MyFactors.AddRange(factorsToAdd.Factors); return this; }