首页 > 代码库 > 求最大公约数和小于n的所有质数

求最大公约数和小于n的所有质数

//algorithm.henum SWAP_TYPE{MEMORY, COMPLEX};struct SIntArray{    int *pData;    int  num;    SIntArray():pData(NULL),num(0){}    void Clear(){delete pData; pData = http://www.mamicode.com/NULL; num = 0;}};void      Wswap(int &m, int &n, SWAP_TYPE name = MEMORY);int       Wgcd(int m, int n);SIntArray Wprime(int m);//algorithm.cppvoid Wswap(int &m, int &n, SWAP_TYPE name)//交换{    switch(name)    {    case MEMORY:        m = m + n;        n = m - n;        m = m - n;        break;    case COMPLEX:        int temp = m;        m = n;        n = temp;        break;    }}int GCD(int m, int n){    if( n == 0)    {        return m;    }    else    {        int r = m % n;        GCD(n, r);    }}int Wgcd(int m, int n)//寻找最大公约数{    if(m > n)    {        Wswap(m, n);//make sure m > n        }    int result = GCD(m, n);    return result;}SIntArray Wprime(int m)//找所有小于m的质数{    SIntArray result;    if(m <= 0)    {        return result;    }    int *number = new int [m+1];    for(int i = 0; i <= m; i++)    {        number[i] = i;    }    int limit = sqrt((float)m);    for(int j = 2; j <= limit; j++)    {        if(number[j] != 0)        {            int temp = j*j;            while(temp <= m) // eliminate            {                number[temp] = 0;                temp = temp + j;                            }        }    }    int count = 0;    for(int j = 2; j <= m; j++)    {        if(number[j])        {            number[count] = number[j];            count++;        }    }    int *out = new int [count];    memcpy(out, number, count*sizeof(int));    delete number;    number = NULL;    result.pData = out;    result.num = count;    return result;}
//main.cpp
int _tmain(int argc, _TCHAR* argv[]){/* Wgcd 最大公约数 int m,n; cout<<"input two number:"<<endl; cin>>m>>n; cout<<"greatest common divisor:"<<endl; cout<<Wgcd(m, n)<<endl;*/ int m; //小于n的所有质数 cout<<"input one number:"<<endl; cin>>m; cout<<"prime number:"<<endl; SIntArray result; result = Wprime(m); for(int i = 0; i <result.num; i++) { cout<<result.pData[i]<<" "; } result.Clear(); return 0;}