题目链接 : TOJ10004
10004 - Prime Factorization
Memory Limit: 65536KB
Description
For a given integer, "Prime Factorization" is finding which prime numbers you need to multiply together to get the original number, also called prime decomposition.
Given a positive integer n>=2, the prime factorization is written
n = p1a1p2a2...pkak
where the pis are the k prime factors, each of order ai.
Write a program to factor a given integer n.
Input
One integer, n. (2<=n<=231-1).
Output
Output the prime factorization of n as follows:
n=p1(a1)p2(a2)...pk(ak)
Where p1<p2<...<pk, and ai denotes the exponent of pi.
For example, for n = 1500 = 22*3*53, the output should be:
1500=2(2)3(1)5(3)
Sample Input #1
2
Sample Output #1
2=2(1)
Sample Input #2
15
Sample Output #2
15=3(1)5(1)
Sample Input #3
1001
Sample Output #3
1001=7(1)11(1)13(1)
Note
Take a look at problem 20002 if you're interested in integer factoring problems.
大数的素因子分解
先筛小素数 然后用试除法
在O(sqrtn) 的判断试除后的数是不是质数
#include<cstdio>
bool vis[1000005];
int prim[90000];
int con[90000];
int cal()
{
int k=0;
for(int i=2;i<1000001;i++)
{
if(vis[i]==0) prim[k++]=i;
for(int j=0;prim[j]*i<1000001 && j<k;j++)
{
vis[i*prim[j]]=1;
if(i%prim[j]==0) break;
}
}
return k;
}
bool is(int n)
{
bool l=1;
for(long long i=2;i*i<=n;i++)
{
if(n%i==0)
{
l=0;
break;
}
}
return l;
}
int main()
{
int n,num=cal(),a=0,sp=0,ans,max=0;
scanf("%d",&n);
printf("%d=",n);
while(n!=1)
{
if(is(n))
{
sp=n;
break;
}
int c=n;
while(c==n)
{
while(n%prim[a]==0)
{
max=a;
n/=prim[a];
con[a]++;
}
a++;
}
}
for(int i=0;i<=a;i++)
{
if(con[i])
{
printf("%d(%d)",prim[i],con[i]);
}
}
if(sp) printf("%d(1)\n",sp);
else putchar(10);
return 0;
}