UVA11466 Largest Prime Divisor【筛选法】

All integer numbers are divisible by primes. If a number is divisible by more than one prime number,then it obviously has a largest prime divisor. The numbers which do not fall in this category do nothave a largest prime divisor. Given a number N your job is to write a program that finds its largestprime divisor. An integer number n is divisible by another integer number m if there is an integer tsuch that mt = n.

Input

The input file contains at most 450 sets of inputs. Each line contains a decimal integer N. N doesnot have more than 14 digits. Input is terminated by a line containing a single zero. So no other lineexcept the last line contains a zero in the input. This line need not be processed.

Output

For each line of the input produce one line of output. This line contains an integer LPD, which is thelargest prime divisor of the input number N. If the input number is not divisible by more than oneprime number output a ‘-1’.

Sample Input

2

6

100

0

Sample Output

-1

3

5

 

问题链接:UVA11466 Largest Prime Divisor

问题简述:(略)

问题分析:

  这个问题由于输入的n比较大,最大达到10^15,所以处理起来有些繁琐。

  由于sqrt(10^15)=31622776,所以首先求出小于31622776的素数备用。这个范围的素数有1951957个。这些数值需要事先计算,以便于定义数组时,既不会不够用也不会浪费空间。

  对于输入的n,从小到大用素数去除n(欧拉函数原理),直到得到最大因子。

程序说明:(略)

 

AC通过的C++语言程序如下:

 

/* UVA11466 Largest Prime Divisor */

#include <iostream>
#include <cmath>

using namespace std;

#define MAXN 31622776
bool sieveflag[MAXN+1] = {false, false, true};

#define PRIMEN 2000000
int prime[PRIMEN] = {2};
int count;

void esieve(bool sflag[], int n)
{
    // 初始化
    for(int i=3; i<=n; i++) {
        sflag[i++] = true;
        sflag[i] = false;
    }

    // 筛选
    int max = sqrt(n);
    for(int i=3; i<=max; i++){
        if(sflag[i]) {
            for(int j=i+i; j <= n; j+=i)
                sflag[j] = false;
        }
    }

}

void setprime(int prime[], bool sflag[], int n)
{
    int i;

    count = 1;

    for(i=3; i<=n; i++)
        if(sflag[i])
            prime[count++] = i;
}

int main(void)
{
    long long n, m;

    esieve(sieveflag, MAXN);

    setprime(prime, sieveflag, MAXN);

    while(cin >> n) {
        // 判定结束条件
        if(n == 0)
            break;

        // 负数的处理
        if(n < 0)
            n = -n;

        int factcount = 0;
        for(int i=0; i<count; i++) {
            if(n < prime[i])
                break;

            if(n % prime[i] == 0) {
                m = prime[i];
                factcount++;
                while (n % m == 0)
                    n /= m;
            }
        }
        if (n != 1) {
            m = n;
            factcount++;
        }

        if(factcount > 1)
            cout << m << endl;
        else
            cout << "-1" << endl;
    }

    return 0;
}

 

 

 

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值