zoukankan      html  css  js  c++  java
  • 求最大公约数和小于n的所有质数

    //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;// j 2*j   (j-1)*j    1:(j-1) have been processed, so only process j ... n/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; }
  • 相关阅读:
    hdu 4521 小明系列问题——小明序列(线段树 or DP)
    hdu 1115 Lifting the Stone
    hdu 5476 Explore Track of Point(2015上海网络赛)
    Codeforces 527C Glass Carving
    hdu 4414 Finding crosses
    LA 5135 Mining Your Own Business
    uva 11324 The Largest Clique
    hdu 4288 Coder
    PowerShell随笔3 ---别名
    PowerShell随笔2---初始命令
  • 原文地址:https://www.cnblogs.com/welen/p/3856144.html
Copyright © 2011-2022 走看看