典型90問
次の典型90問へ
前の典型90問へ
典型90問 030 K Factors(★5)
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("15 2");
//5
}
else if (InputPattern == "Input2") {
WillReturn.Add("30 2");
//13
}
else if (InputPattern == "Input3") {
WillReturn.Add("200 4");
//0
}
else if (InputPattern == "Input4") {
WillReturn.Add("869120 1");
//869119
}
else if (InputPattern == "Input5") {
WillReturn.Add("10000000 3");
//6798027
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static int[] mSosuuArr;
static void Main()
{
List<string> InputList = GetInputList();
int[] wkArr = InputList[0].Split(' ').Select(pX => int.Parse(pX)).ToArray();
int N = wkArr[0];
int K = wkArr[1];
Eratosthenes(N);
int[] CntArr = new int[N + 1];
foreach (int EachSosuu in mSosuuArr) {
int CurrVal = EachSosuu;
while (CurrVal <= N) {
CntArr[CurrVal]++;
CurrVal += EachSosuu;
}
}
Console.WriteLine(CntArr.Count(pX => pX >= K));
}
// エラトステネスの篩
static void Eratosthenes(int pJyougen)
{
bool[] IsSosuuArr = new bool[pJyougen + 1];
for (int I = 2; I <= IsSosuuArr.GetUpperBound(0); I++) {
IsSosuuArr[I] = true;
}
for (int I = 2; I * I <= IsSosuuArr.GetUpperBound(0); I++) {
if (IsSosuuArr[I]) {
for (int J = I * 2; J <= IsSosuuArr.GetUpperBound(0); J += I) {
IsSosuuArr[J] = false;
}
}
}
var SosuuList = new List<int>();
for (int I = 2; I <= IsSosuuArr.GetUpperBound(0); I++) {
if (IsSosuuArr[I]) SosuuList.Add(I);
}
mSosuuArr = SosuuList.ToArray();
}
}
解説
最初にエラトステネスの篩で
N以下の素数を列挙してから
素数の倍数ごとに度数をインクリメントしてます。