Largest prime factor

来源:互联网 发布:黑色沙漠男忍捏脸数据 编辑:程序博客网 时间:2024/06/05 02:18

Largest prime factor

Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 5632 Accepted Submission(s): 1712
Problem Description
Everybody knows any number can be combined by the prime number.
Now, your task is telling me what position of the largest prime factor.
The position of prime 2 is 1, prime 3 is 2, and prime 5 is 3, etc.
Specially, LPF(1) = 0.
 

Input
Each line will contain one integer n(0 < n < 1000000).
 

Output
Output the LPF(n).
 

Sample Input
12345
 

Sample Output
01213
 

Author
Wiskey
 

Source
HDU 2007-11 Programming Contest_WarmUp
 

Recommend
威士忌
 


分解质因数:

每个合数都可以写成几个质数(即素数)相乘的形式,其中每个质数都是这个合数的因数,做这个合数的分解质因数。该题就是求输入n,对n进行分解质因数。在其所有的质因数中的最大的质因数在素数表中的位置。当然针对素数本身分解质因数可视为1*自身(注:分解质因数只针对合数)。


分解质因数算法:

/*分解质因数*/#include<iostream>using namespace std;int main(){    int n,n2;    cin>>n;    n2=n;    cout<<n<<"=";    for(int i=2;i<=n;i++)    {        for(;n2%i==0;)        {            n2=n2/i;            cout<<i<<"*";        }        if(n2==1)            break;    }    cout<<"1";    return 0;}

测试结果:



结合分解质因数和筛法,AC的结果:

#include<stdio.h>#include<string.h>#define MAX 1000000using namespace std;int LPF[MAX];int main(){    //利用建立一张素数表,其index代表素数,其值LPF[index]代表位置信息    int i;    int val;    memset(LPF,0,sizeof(LPF));    LPF[2]=1;    for(i=4;i<MAX;i+=2)//处理偶数    {        LPF[i]=LPF[2];    }    int cnt=2;    for(i=3;i<MAX;i+=2)//处理奇数    {        if(LPF[i])//即非0            continue;        LPF[i]=cnt++;        for(int j=(i<<1);j<MAX;j+=i)        {            LPF[j]=LPF[i];        }    }    //必须得用scanf与printf,涉及到效率问题,传送门http://bbs.csdn.net/topics/390774520    while(~scanf("%d",&val))        printf("%d\n",LPF[val]);    return 0;}



0 0
原创粉丝点击