Largest prime factor
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 5260 Accepted Submission(s): 1858
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.
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
1 2 3 4 5
Sample Output
0 1 2 1 3
/*思路:根据求质数表的过程,将每个数的最大质因子保存到prime[],每个质因子的位置保存到pos[],最后只要找到输入的数的最大质因子是多少,因子所在的位置则查找pos[]即可以找到*/
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std ;
#define MAX 1000003
int prime[MAX], pos[MAX];
void Cprime()
{
memset(prime,0,sizeof(prime));
int i , j , k = 1;
for( i = 2 ; i < MAX ; i ++)
{
if(prime[i] == 0 )
{
pos[i] = k ++ ;
for( j = i ; j < MAX ; j += i)
prime[j] = i ;
}
}
return ;
}
int main(void)
{
int n ;
Cprime();
while(scanf("%d",&n)!=EOF )
{
if( n == 1 ){
//cout<<"0"<<endl;
printf("0\n");
continue ;
}
//cout<<pos[prime[n]]<<endl;
printf("%d\n",pos[prime[n]]);
}
return 0;
}
/*超时算法,打质数表求解*/
/*
思路:打质数表求解,打1000000内的所有质数的表,然后用a[]
整除小于b的所有质数,思路很简单,一定要打表,不然超时
*/
#include<iostream>
#include<stdlib.h>
#include<cmath>
#include<cstring>
#include<cstdio>
using namespace std;
#define N 1000000
int sieve[N + 1];
int prime[N+1],k=0;
int pos[N+1] ;
//质数表
void Cprime(){
memset(pos, 0 ,sizeof(pos));
int i;
for( i = 2; i <= N; i++) sieve[i] = 1;
for(i = 2; i <= N / 2; i++) sieve[i * 2] = 0;
int p = 2;
while(p * p <= N)
{
p = p + 1;
while(sieve[p] == 0)
p++;
int t = p * p;
int s = 2 * p;
while(t <= N)
{
sieve[t] = 0;
t = t + s;
}
}
for(i=2;i<=N;i++)
if(sieve[i]!=0){
prime[k++]=i;
pos[i] = k ;
}
return ;
}
int fun(int s )
{
int i ,max1 = 1 ;
for( i = 2; i <= (int)sqrt(s*1.0) ; i ++)
{
while(s%i== 0 )
{
s /= i ;
max1 = max1 < i ? i : max1 ;
}
}
return max1 ;
}
int main()
{
Cprime();
int n ;
while(scanf("%d",&n)!=EOF )
{
if(sieve[n]!=0)
//cout<<pos[n]<<endl;
printf("%d\n",pos[n]);
else
{
int s = fun(n);
//cout<<pos[s]<<endl;
printf("%d\n",pos[s]);
}
}
return 0;
}