跳到正文

个人记录

DPS官方钦定唯一题解

Guozehao2022约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年10月16日
收录
2025年12月12日
更新
2026年10月11日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

相关题目链接

提示:不要利用该题解刷DPS AC率,该题解仅供参考与提供思路。

请自觉使用DPS解决该题,不要试图用其他不优秀的质数筛法解决本题。

唐氏筛将会美名远扬

欧拉筛将会臭名昭著

C++
#include <bits/stdc++.h>
using namespace std;

const int BASE = 10000, WIDTH = 4;

// 高精度整数类
struct BigInt {
	vector<int> d;

	BigInt(int x = 0) { *this = x; }

	BigInt& operator= (int x) {
		d.clear();
		while (x > 0) {
			d.push_back(x % BASE);
			x /= BASE;
		}
		if (d.empty()) d.push_back(0);
		return *this;
	}

	BigInt operator* (int b) const {
		BigInt c;
		c.d.resize(d.size() + 1);
		long long carry = 0;
		for (size_t i = 0; i < d.size(); ++i) {
			carry += 1LL * d[i] * b;
			c.d[i] = carry % BASE;
			carry /= BASE;
		}
		if (carry) c.d[d.size()] = carry;
		else c.d.resize(d.size());
		return c;
	}

	bool operator> (const BigInt &b) const {
		if (d.size() != b.d.size()) return d.size() > b.d.size();
		for (int i = d.size() - 1; i >= 0; --i)
			if (d[i] != b.d[i]) return d[i] > b.d[i];
		return false;
	}


	int to_int_safe() const {
		BigInt LIM(INT_MAX);
		if (*this > LIM)
			return 0;
		int res = 0;
		for (int i = d.size() - 1; i >= 0; --i)
			res = res * BASE + d[i];
		return res;
	}

	void print() const {
		printf("%d", d.back());
		for (int i = d.size() - 2; i >= 0; --i)
			printf("%0*d", WIDTH, d[i]);
	}
};

int qpow(int x,int p){
	int res=1;
	while(p){
		if(p&1)res=res*x;
		x=x*x;
		p>>=1;
	}
	return res;
}

int n;
vector<bool> is_composite;

void brute_sieve(int n) {
	is_composite.assign(n + 1, false);
	BigInt N(n);
	int total = n - 1;

	int total_states = pow(3, total);
	vector<int> state(total);

	for (int mask = 0; mask < total_states; ++mask) {
		int tmp = mask;
		int sum = 0;
		for (int i = 0; i < total; ++i) {
			state[i] = tmp % 3;
			sum += state[i];
			tmp /= 3;
		}
		if (sum < 2) continue;
		if (sum > log2(n))continue;

		BigInt prod(1);
		bool too_large = false;
		for (int i = 0; i < total; ++i) {
			int base = i + 2;
			prod=prod*qpow(base,state[i]);
		}

		int val;
		if(val=prod.to_int_safe())
			if (val <= n) is_composite[val] = true;
	}
	int cnt=0;
	for (int i = 2; i <= n; ++i)
		if (!is_composite[i])
			cnt++,printf("%d ", i);
	if(!cnt)printf("-1");
	printf("\n");
}

int main() {
	scanf("%d", &n);
	int start=clock();
	brute_sieve(n);
//	cout<<'\n'<<clock()-start<<'\n';
	return 0;
}
原文