閱讀理解
- 描述
-
閱讀以下代碼:
#include<stdio.h>
bool _(int __)
{
int ___=1;
for(___++; ___<__; ___++)
if(!(__%___))
return false;
return true;
}
int main()
{
int a,b,cnt=0;
while(~scanf("%d%d",&a,&b))
{
printf("Case %%%d:",++cnt);
int count=0;
for(int i=a; i<=b; i++)
if(_(i))
count++;
printf("%d\n",count);
}
}PS: _ 爲合法標識符。
- 輸入
- 輸入兩個數(0 < a <= b < 100000 )
- 輸出
- 格式及細節見代碼及輸出樣例
- 樣例輸入
-
2 3 3 5
- 樣例輸出
-
Case %1:2 Case %2:2
- 來源
- 流年
- 上傳者
這道題一直被超時困擾着,1、常規的求素數方法會導致超時,2、把求素數改成篩法後,再判斷,還是會超時。
方法:篩法加打表,先都預處理出來,堅決不重複計算任何一個部分,哪怕是小小的判斷,大數據會直接導致超時,shit
/** * Project Name: nyoj_2.0 * File Name: 1167.cpp * Created on: 2015年5月16日 下午3:14:26 * Author: jtahstu * QQ: 1373758426 E-mail:[email protected] * Copyright (c) 2015, jtahstu , All Rights Reserved. */ /** * Project Name: C++ * File Name: nyoj1167.cpp * Created on: 2015年4月7日 下午9:14:33 * Author: jtahstu * Copyright (c) 2015, jtahstu , All Rights Reserved. */ #include<iostream> #include<cstdio> #include<cmath> #include<algorithm> #include<string> #include<cstring> using namespace std; int a[100005], ans[100005]; int main() { memset(a, 0, sizeof(a)); memset(ans, 0, sizeof(ans)); int c, b, count = 0, sum = 0; for (int i = 2; i < 100001; i++) { //篩法確實是可以大大縮短時間,但還是超時 if (a[i] == 0) for (int j = i + i; j < 100001; j += i) a[j] = 1; } for (int i = 0; i <= 100000; i++) { //篩法後還要打表以節約時間 if (!a[i]) { sum++; } ans[i] = sum; } while (scanf("%d%d", &c, &b) != EOF) { count++; printf("Case %%"); printf("%d:%d\n", count, ans[b] - ans[c - 1]); //減去a的前一個數 } return 0; }