/// <remark> /// , /// . /// . /// /// , 276 . . ., , -- /// 194 . . ., . . /// /// . . /// /// . , /// 2. 2. /// . , /// . /// /// . 9.12.1999 Java /// C# 12.01.2005. ///</remark> using System; /// <summary> /// : . /// </summary> public class GeneratePrimes { ///<summary> /// . ///</summary> /// /// <param name=”maxValue”> .</param> public static int[] GeneratePrimeNumbers(int maxValue) { if (maxValue >= 2) // { // int s = maxValue + 1; // bool[] f = new bool[s]; int i; // true. for (i = 0; i < s; i++) f[i] = true; // f[0] = f[1] = false; // int j; for (i = 2; i < Math.Sqrt(s) + 1; i++) { if (f[i]) // i , . { for (j = 2 * i; j < s; j += i) f[j] = false; // – } } // ? int count = 0; for (i = 0; i < s; i++) { if (f[i]) count++; // } int[] primes = new int[count]; // for (i = 0, j = 0; i < s; i++) { if (f[i]) // primes[j++] = i; } return primes; // } else // maxValue < 2 return new int[0]; // , // } }
///<remark> /// , /// . /// . /// , 2: /// /// . , . ///</remark> using System; public class PrimeGenerator { private static bool[] crossedOut; private static int[] result; public static int[] GeneratePrimeNumbers(int maxValue) { if (maxValue < 2) return new int[0]; else { UncrossIntegersUpTo(maxValue); CrossOutMultiples(); PutUncrossedIntegersIntoResult(); return result; } } private static void UncrossIntegersUpTo(int maxValue) { crossedOut = new bool[maxValue + 1]; for (int i = 2; i < crossedOut.Length; i++) crossedOut[i] = false; } private static void PutUncrossedIntegersIntoResult() { result = new int[NumberOfUncrossedIntegers()]; for (int j = 0, i = 2; i < crossedOut.Length; i++) { if (NotCrossed(i)) result[j++] = i; } } private static int NumberOfUncrossedIntegers() { int count = 0; for (int i = 2; i < crossedOut.Length; i++) { if (NotCrossed(i)) count++; // } return count; } private static void CrossOutMultiples() { int limit = DetermineIterationLimit(); for (int i = 2; i <= limit; i++) { if (NotCrossed(i)) CrossOutputMultiplesOf(i); } } private static int DetermineIterationLimit() { // // , // , , // . double iterationLimit = Math.Sqrt(crossedOut.Length); return (int)iterationLimit; } private static void CrossOutputMultiplesOf(int i) { for (int multiple = 2 * i; multiple < crossedOut.Length; multiple += i) crossedOut[multiple] = true; } private static bool NotCrossed(int i) { return crossedOut[i] == false; } }
Source: https://habr.com/ru/post/231325/
All Articles