Tall algorithm is not necessarily practical!

Made a factorization problem of topics
Here Insert Picture Description
here relate to prime numbers, I think the method Euler hit the table nearest school, wrote the following error demonstration:

#include <iostream>
#include <algorithm>
#include<string.h>
using namespace std;
int prime[100000000]={0},t_e[100000000]={0};
int main()
{
    int n,num=0,i,j;
    int temp=0;
    while(scanf("%d",&n)!=EOF)
    {
        if(temp<n)
        {
            num=0;
            memset(t_e,0,sizeof(t_e));
            for(i=2;i<=n/2;i++)     //欧拉打表
            {
                if(t_e[i]==0)
                {
                    num++;
                    prime[num]=i;
                }
            for(j=1;j<=num&&((i*prime[j]<=n/2));++j)
             {
                t_e[i*prime[j]]=1;
                if(i%prime[j]==0)break;
             }
            }
        }
        temp=n;
        for(i=1;i<=num;i++)
    {
        while(n%prime[i]==0)
        {  
            if(n==temp)cout<<prime[i];
            else cout<<"*"<<prime[i];
            n/=prime[i];
        }
        if(n==1)break;
    }
    cout<<endl;
    } 
    return 0;
}

This method is very fast playing table O (n)
but the table was to the big fight
, but an array of driving too large, then the time will need to apply for more time memory! ! ! Overtime! !
To the small shrink, nor subject to the range, not a good deal, so here choose to give up playing table method

The following is a correct demonstration

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<vector>
#include<list>
#include<deque>
#include<set>
#include<map>
#include<stack>

using namespace std;

int main(){
    int n;
    vector<int> ret; 
    cin>>n;
    for(int i=2;i<=n;i++){    //这个算法需要明确一个东西---合数由质数得来的
        while(n%i==0){        //例如:4=2*2,6=3*2,这个while循环已经把2这条路给堵死
            n/=i;              //如果连2都除不了,4必定除不了
            ret.push_back(i);   //从2开始循环除以i,能除得进i的就压进容器
        }
    }
    for(int i=0;i<ret.size();i++){
        if(i==ret.size()-1){
            cout<<ret[i];
        }else
            cout<<ret[i]<<"*";
    } 
    return 0; 
}
//这段代码是网上复制的

Summary: The
algorithm is sometimes not practical on a tall - still have to choose the right strategy
this law is really horrible, it is easy to solve the problem with prime numbers to the factorization

Guess you like

Origin blog.csdn.net/a10201516595/article/details/93179869