大素数

K - Alexandra and Prime Numbers

 

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!

Input

There are multiple test cases (no more than 1,000). Each case contains only one positive integer N. 
N≤1,000,000,000N≤1,000,000,000. 
Number of cases with N>1,000,000N>1,000,000 is no more than 100.

Output

For each case, output the requested M, or output 0 if no solution exists.

Sample Input

3
4
5
6

Sample Output

1
2
1
2

题意:给你一个数n(1<=n<=1e9)  要你求满足n/m是素数的最小m的值

分析:p=n/m p是素数,m=n/p 要使m最小,那么p就要最大,且由唯一分解定理的n=p1*p2*p3....*pn(pi为素数),那么就是要求n最大的素数因子就为p,此时m最小,p从sqrt(n)+1开始枚举,因为n不可能有两个大于sqrt(n)的素数因子

Ac code:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<iomanip>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxn=1e5+2;
//int prime[maxn];
bool vis[maxn];
int cnt;
void set_prime()
{
    cnt=0;
    memset(vis,0,sizeof vis);
    for(int i=2;i<=100000;i++)
    {
        if(!vis[i])
        {
            //prime[cnt++]=i;
            for(int j=i+i;j<=100000;j+=i)
                vis[j]=1;
        }
    }
}
int main()
{
    set_prime();
    ll n;
    while(scanf("%lld",&n)!=EOF)
    {
        if(n==1)
        {
            printf("0\n");
            continue;
        }
        ll temp=n;
        ll ans=0;
        ll m=(ll)sqrt(n)+1;
        for(m;m>1;m--)///找小于n的最大的素数因子,且不会有两个素数因子
                      ///都大于sqrt(n),故从sqrt(n)+1开始找
            if(n%m==0)
        {
            while(n%m==0&&!vis[m])
                n/=m;
            if(!vis[m])
                ans=max(ans,m);
        }
        ans=max(ans,n);///n若本来就是个素数,或剩下的因子更大
        printf("%lld\n",temp/ans);
    }
    return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值