数论_质数_CH3101_阶乘分解

版权声明:本文为博主原创作品, 转载请注明出处! https://blog.csdn.net/solider98/article/details/84580363

点此打开题目页面

思路分析:

    易知n!的所有质因数均不超过n, 故可先预处理2到n之间的所有质数, 对该范围内的每个质数p, 可以证明将n!分解质因数之后p的幂指数为\left \lfloor \frac{n}{p} \right \rfloor+\left \lfloor \frac{n}{p^{2}} \right \rfloor+...+\left \lfloor \frac{n}{p^{m}} \right \rfloor, p^{m}<= n. 根据此策略给出如下AC代码:

//CH3101_阶乘分解
#include <iostream>
#include <map>
#include <cstring>
using namespace std;
const int MAX = 1e6 + 5;
int primes[MAX], N;//primes[i]为1表示质数, 为2表示合数 
map<int, long long> res;//N!分解的结果 
//筛法求2...n之间的素数
void getPrimes(int n){
	memset(primes, 0, sizeof(primes));
	for(int i = 2; i <= n; ++i)
		if(!primes[i]){
			primes[i] = 1; for(int j = i; j <= n / i; ++j) primes[j * i] = 2;
		}
} 
int main(){
	getPrimes(MAX - 1), cin >> N;
	for(int i = 2; i <= N; ++i)
		if(primes[i] == 1){
			long long sum = 0; for(long long p = i; p <= N; p *= i) sum += N / p;
			if(!res.count(i)) res[i] = sum; else res[i] += sum;
		}
	for(map<int, long long>::iterator it = res.begin(); it != res.end(); ++it)
		cout << it->first << " " << it->second << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/solider98/article/details/84580363