zoukankan      html  css  js  c++  java
  • HDU-1164-Eddy's research I(分解质因数)

    由于这道题目数据范围小,所以属于水题。可以采取暴力的做法来解决。

    代码如下:

    #include"bits/stdc++.h"
    using namespace std;
    const int maxn=65535;
    bool tag[maxn+5];
    vector<int>v;int n;
    bool judge(int m){
        while(n%m==0){
            if(n==m){
                printf("%d
    ",m);
                return true;
            }
            else printf("%d*",m);
            n/=m;
        }
        return false;
    }
    int main(){
        for(int i=2;i<=maxn;i++){
            if(!tag[i])v.push_back(i);
            for(int j=i<<1;j<=maxn;j+=i)
            tag[j]=true;
        }
        while(~scanf("%d",&n)){
            for(int i=0;i<v.size();i++)
            if(n%v[i]==0&&judge(v[i]))
            break;
        }
        return 0;
    }

    但是如果把这题的数据范围加到1e8,那么用这种暴力的方法光是打一个素数表都很耗时。如何快速解决1e8的因式分解呢?可以这样想:

    1e8以内的数大于1e4的质因子最多只能出现一次(因为1e4的平方等于1e8,所以如果出现一次以上就会超过1e8),而且如果这个数出现了大于1e4的质因子,那么当我们把小于1e4的质因子都除尽时,留下的就是这个大于1e4的质因子。所以我们打素数表时其实不用打到1e8,只要1e4就够了(如果范围是n就打到根号n),这样可以加速了1e4倍。

    代码如下:

    #include"bits/stdc++.h"
    using namespace std;
    const int maxn=1e4;
    bool tag[maxn+5];
    vector<int>v;int n;
    bool judge(int m){
        while(n%m==0){
            if(n==m) return true;
            else printf("%d*",m);
            n/=m;
        }
        return false;
    }
    int main(){
        for(int i=2;i<=maxn;i++){
            if(!tag[i])v.push_back(i);
            for(int j=i<<1;j<=maxn;j+=i)
            tag[j]=true;
        }
        while(~scanf("%d",&n)){
            for(int i=0;i<v.size();i++)
            if(n%v[i]==0&&judge(v[i]))
            break;
            printf("%d
    ",n);
        }
        return 0;
    }

    对于这一题65535的范围maxn只要设为256就够了,其他基本没有改动

    还有一种解决因式分解的方法,如果如果内存足够并且测试数据有很多组的情况下这种方式会比较优

    代码如下:

    #include"bits/stdc++.h"
    using namespace std;
    const int maxn=1e4;
    const int maxm=1e8;
    int tag[maxm+5];
    vector<int>v;int n;
    int main(){
        for(int i=2;i<=maxn;i++){
            if(!tag[i])v.push_back(i);
            for(int j=i<<1;j<=maxm;j+=i)
            if(!tag[j])tag[j]=i;
        }
        while(~scanf("%d",&n)){
            while(tag[n]){
                printf("%d*",tag[n]);
                n/=tag[n];
            }
            printf("%d
    ",n);
        }
        return 0;
    }
  • 相关阅读:
    c++中sort()及qsort()的用法总结
    POJ的层次感分类
    DFS练习-HDU1010
    Dijkstra&&Floyd
    DFS练习一---HDU 1342
    快速幂取模算法
    树的实现
    C++的队列和pair
    BFS练习-POJ.2386
    Codeforces 1139E(二分图最大匹配)
  • 原文地址:https://www.cnblogs.com/Angel-Demon/p/9696977.html
Copyright © 2011-2022 走看看