Almost Prime Numbers(素数筛)

UVA10539

在这里插入图片描述

枚举2到 h i g h \sqrt{high} ,分别看 i 2 , i 3 i n i^2,i^3\cdots i^n ,是否在 [ l e f t , r i g h t ] [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;

}
发布了71 篇原创文章 · 获赞 80 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_42971794/article/details/104628300