您的位置:首页 > 其它

hdu5108——Alexandra and Prime Numbers(素数)

2017-04-16 20:49 211 查看

Alexandra and Prime Numbers

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 2208    Accepted Submission(s): 723


[align=left]Problem Description[/align]
Alexandra has a little brother. He is new to programming. One day he is solving the following problem: Given an positive integer N, judge whether N is prime.

The problem above is quite easy, so Alexandra gave him a new task: Given a positive integer N, find the minimal positive integer M, such that N/M is prime. If such M doesn't exist, output 0.

Help him!
 

[align=left]Input[/align]
There are multiple test cases (no more than 1,000). Each case contains only one positive integer N.
N≤1,000,000,000.

Number of cases with N>1,000,000
is no more than 100.
 

[align=left]Output[/align]
For each case, output the requested M, or output 0 if no solution exists.
 

[align=left]Sample Input[/align]

3
4
5
6

 

[align=left]Sample Output[/align]

1
2
1
2

题意:给定一个n,找最小的m,使n/m是素数
思路:n/m是素数,那么n/素数就可以求m(n%(素数)==0),m最小,则该素数就得最大,因此对n分解质因子,找出最大的质因子,那么n/最大质因子就是最小m
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <stack>
using namespace std;
typedef long long ll;
#define PI 3.1415926535897932
#define E 2.718281828459045
#define INF 0x3f3f3f3f
#define mod 1000000007
#define N 1000005

bool isprime
;
ll prime
;
int cnt;

void getpri()
{
    ll i;
    int j;
    cnt=0;
    memset(isprime,false,sizeof(isprime));
    for(i=2; i<1000000LL; i++)
    {
        if(!isprime[i])prime[cnt++]=i;
        for(j=0; j<cnt&&prime[j]*i<1000000LL; j++)
        {
            isprime[i*prime[j]]=1;
            if(i%prime[j]==0)break;
        }
    }
}
int main()
{
    int i,j;
    getpri();
    ll n,temp;

    while(~scanf("%I64d",&n))
    {
        if(n==1)
        {
            printf("0\n");
            continue;
        }
        int flag=0;
        temp=n;
        ll m=(ll)(sqrt(n))+1;
        ll ans=0;
        for(; m>1; m--)
            if(n%m==0)
            {
                while(n%m==0&&!isprime[m])
                    n/=m;
                if(!isprime[m])
                {
                    ans=max(ans,m);
                }
            }
        ans=(ll)max(ans,n);//ans可能是0
        printf("%I64d\n",temp/ans);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: