Factorial Decomposition ----------------------------------------- Number Theory (Linear Sieve)

Given an integer N, try factorizing N! To decompose the prime factors, and output the pi and ci in the decomposition result in the form of the basic theorem of arithmetic.

Input format
An integer N.

The output format
N! The result after decomposing the prime factors is a total of several lines, each line of a pair of pi, ci, that contains pcii items. The output is in order of pi from small to large.

Data range
1≤N≤106
Input sample:
5
Output sample:
2 3
3 1
5 1
Sample explanation
5! = 120 = 23 ∗ 3 ∗ 5

Analysis: the
first step: sieve out all the prime numbers from 1 to 1e6 The
second step: find the number of prime numbers p n / p, n / p 2 , n / p 3 … n / p n

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+1000;
int prime[N],cnt;
bool st[N];
int n;
void init(int n)
{
	memset(st,false,sizeof st);
	cnt=0;
	for(int i=2;i<=n;i++)
	{
		if(!st[i]) prime[++cnt]=i;
		for(int j=1;j<=cnt&&prime[j]<=n/i;j++)
		{
			st[prime[j]*i]=true;
			if(i%prime[j]==0) break; 
		} 
	 } 
}
int main()
{
	scanf("%d",&n);
	init(n);
	for(int i=1;i<=cnt;i++)
	{
		int p=prime[i];
		int s=0;
		for(int j=n;j;j/=p) s+=j/p;
		cout<<p<<" "<<s<<endl;
	}
}
Published 572 original articles · praised 14 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/105386692