E8本(数学)
次のE8本(数学)の問題へ
前のE8本(数学)の問題へ
E8本(数学) 097 Primes in an Interval
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("21 40");
//4
}
else if (InputPattern == "Input2") {
WillReturn.Add("101 130");
//6
}
else if (InputPattern == "Input3") {
WillReturn.Add("1 100");
//25
}
else if (InputPattern == "Input4") {
WillReturn.Add("217 217");
//0
}
else if (InputPattern == "Input5") {
WillReturn.Add("999999500000 1000000000000");
//18228
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
long[] wkArr = InputList[0].Split(' ').Select(pX => long.Parse(pX)).ToArray();
long L = wkArr[0];
long R = wkArr[1];
long SqrtVal = 1;
while (SqrtVal * SqrtVal <= R) {
SqrtVal++;
}
Eratosthenes(SqrtVal);
var NonPriceSet = new HashSet<long>();
foreach (long EachPrime in mSosuuArr) {
long CurrVal = L - (L % EachPrime);
while (CurrVal <= R) {
if (Array.BinarySearch(mSosuuArr, CurrVal) < 0) {
if (L <= CurrVal && CurrVal <= R) {
NonPriceSet.Add(CurrVal);
}
}
CurrVal += EachPrime;
}
}
long Answer = R - L + 1 - NonPriceSet.Count;
if (L == 1) Answer--;
Console.WriteLine(Answer);
}
static long[] mSosuuArr;
// エラトステネスの篩
static void Eratosthenes(long pJyougen)
{
bool[] IsSosuuArr = new bool[pJyougen + 1];
for (long I = 2; I <= IsSosuuArr.GetUpperBound(0); I++) {
IsSosuuArr[I] = true;
}
for (long I = 2; I * I <= IsSosuuArr.GetUpperBound(0); I++) {
if (IsSosuuArr[I]) {
for (long J = I * 2; J <= IsSosuuArr.GetUpperBound(0); J += I) {
IsSosuuArr[J] = false;
}
}
}
var SosuuList = new List<long>();
for (long I = 2; I <= IsSosuuArr.GetUpperBound(0); I++)
if (IsSosuuArr[I]) SosuuList.Add(I);
mSosuuArr = SosuuList.ToArray();
}
}
解説
区間篩で解いてます。