Almost Prime Numbers(素數篩)

UVA10539

在這裏插入圖片描述

枚舉2到high\sqrt{high},分別看i2,i3ini^2,i^3\cdots i^n,是否在[left,right][left,right]中,統計多少個這樣的次方方在範圍中即可。

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <cstdio>
#include <cstring>
using namespace std;


const int MAXN = 1e7;
bool IsPrime[MAXN + 1];
vector<int> PTable;

void InitPTable() {
	for (int i = 2; i <= MAXN; ++i) {
		if (IsPrime[i] == false) {
			PTable.push_back(i);
			for (int j = 2 * i; j <= MAXN; j += i) {
				IsPrime[j] = true;
			}
		}
	}
}

int main() {

	int T;
	InitPTable();
	scanf("%d", &T);
	long long Left, Right;
	while (T--) {
		scanf("%lld%lld", &Left, &Right);
		int MAX = ceil(sqrt(static_cast<double>(Right)));
		int Ans = 0;
		for (const int& Prime : PTable) {
			long long i = static_cast<long long>(Prime) * Prime;
			if (i > Right) {
				break;
			}
			while (i < Left) {
				i *= Prime;
			}
			if (i <= Right) {
				++Ans;
			}
			while (true) {
				i *= Prime;
				if (i > Right) {
					break;
				}
				++Ans;
			} 
		}
		printf("%d\n", Ans);
	}

	return 0;

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章