首页 > 代码库 > 求最大公约数和小于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.cppint _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;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。