HDU5428 The Factor【分解质因子】

问题链接HDU5428 The Factor

题意简述:对于给出的一组数 找出这组数乘积中的一个最小的至少三个质因子的数。

问题分析

其实就是最小的两个素数因子的乘积。

将各个数分别进行质因子分解,将质因子保存在数组中,排序后找到最小的两个乘积即可。

程序说明

给出2个C++语言程序,前一个程序使用变量maxfact记录已经找到的最大因子,限制质因子分解计算,也许会快一些。


AC的C++语言程序如下

/* HDU5428 The Factor */

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 10000;
unsigned int fact[N], maxfact;
int fcount;

void solve(unsigned int x)
{
    for(int i=2; i*i<=x; i++) {
        if(i >= maxfact && fcount >= 2)
            break;

        while(x % i == 0) {
            fact[fcount++] = i;
            x /= i;

            if(i > maxfact)
                maxfact = i;
        }
    }

    if(x > 1) {
        if(x >= maxfact && fcount >= 2)
            ;
        else {
            fact[fcount++] = x;
            if(x > maxfact)
                maxfact = x;
        }
    }
}

int main()
{
    int t, n;
    unsigned int a;

    cin >> t;
    while(t--) {
        cin >> n;

        fcount = 0;
        maxfact = 0;
        while(n--) {
            cin >> a;
            solve(a);
        }

        sort(fact, fact + fcount);

        if(fcount < 2)
            cout << -1 << endl;
        else
            cout << (long long)fact[0] * fact[1] << endl;
    }

    return 0;
}


AC的C++语言程序如下

/* HDU5428 The Factor */

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 10000;
unsigned int fact[N] ;
int fcount;

void solve(unsigned int x)
{
    for (unsigned int i=2; i*i<=x; i++) {
        while(x % i == 0) {
            fact[fcount++] = i;
            x /= i ;
        }
    }
    if (x > 1)
        fact[fcount++] = x;
}

int main()
{
    int t, n;
    unsigned int a;

    cin >> t ;
    while(t--) {
        cin >> n ;

        fcount = 0 ;
        while(n--) {
            cin >> a;
            solve(a);
        }

        sort(fact, fact + fcount);

        if (fcount < 2)
            cout<< -1 << endl;
        else
            cout << (long long) fact[0] * fact[1] << endl;
    }

    return 0 ;
}



转载于:https://www.cnblogs.com/tigerisland/p/7563760.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值