码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-07-21 09:38:33      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   re   c   

//algorithm.h
enum SWAP_TYPE{MEMORY, COMPLEX};
struct SIntArray
{
    int *pData;
    int  num;
    SIntArray():pData(NULL),num(0){}
    void Clear(){delete pData; pData = NULL; num = 0;}
};
void      Wswap(int &m, int &n, SWAP_TYPE name = MEMORY);
int       Wgcd(int m, int n);
SIntArray Wprime(int m);

//algorithm.cpp
void 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; }

求最大公约数和小于n的所有质数,布布扣,bubuko.com

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

标签:style   blog   color   for   re   c   

原文地址:http://www.cnblogs.com/welen/p/3856144.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!