Ejemplo n.º 1
0
        /// <summary>
        /// Either retrieves from memory, generates, or a combination of both, all primes upto
        /// a given value
        /// </summary>
        /// <param name="target">The maximum limit on the value of primes</param>
        /// <returns>A list of all primes less than or equal to the provided target</returns>
        public IList <int> GetPrimesTo(int target)
        {
            //If there's no stored primes, generate them all
            if (!Primes.Any())
            {
                Primes = _generator.GeneratePrimesTo(target).ToList();
            }
            else
            {
                //Is the last generated prime greater than the target
                var lastPrime = Primes.Last();
                if (lastPrime > target)
                {
                    //Just return the primes upto that point
                    return(Primes.Where(p => p <= target).ToList());
                }

                //Add the primes between the current maximum and the target
                Primes.AddRange(_generator.GeneratePrimesBetween(lastPrime + 1, target));
            }
            return(Primes.ToList());
        }