题解 | #筛选法求素数#
筛选法求素数
https://www.nowcoder.com/practice/06c3dcc303654ef4926654023eca1e5a
public class Program { public static void Main() { string input; while ((input = System.Console.ReadLine()) != null) { int len = int.Parse(input); int[] inPutNum = new int[len - 1]; //把数字装入数组 for (int i = 2; i <= len; i++) inPutNum[i - 2] = i;
int clearNum = 0; //利用双循环去对比 for (int i = 0; i < inPutNum.Length; i++) { for (int j = 1 + i; j < inPutNum.Length; j++) { if (inPutNum[i] != 0 && inPutNum[j] != 0) { if (inPutNum[j] % inPutNum[i] == 0) { inPutNum[j] = 0; clearNum += 1; } else { continue; } } } } //输出结果 for (int i = 0; i < inPutNum.Length; i++) if (inPutNum[i] != 0) System.Console.Write(inPutNum[i] + " "); System.Console.WriteLine(); //输出被清零的个数 System.Console.WriteLine(clearNum); } }
}