求最大公约数采用辗转相除法
求最小公倍数 = 最大公约数 * (A/最大公约数)*(B/最大公约数)
//#include<stdafx.h> #include<math.h> #include<assert.h> #include<stdlib.h> #include<iostream> #include<time.h> using namespace std; #define INVALID_VALUE32 (0xffffffff) class ALL_DISTRIBUTE { public: static double standartDis(int ave, double delta); static int __rand(int i, int j); static int findMinMulti(int a[], int i, int j); static int findMaxDev(int a[], int i, int j); private: static double __rand_zero_one(void); static int __minGbs(int i, int j); static int __maxGys(int i, int j); }; /* 两个数的最小公倍数 */ int ALL_DISTRIBUTE::__minGbs(int i, int j) { int maxGys = __maxGys(i, j); //cout << maxGys << endl; return maxGys * (i/maxGys) * (j/maxGys); } /* 两个数的最大公约数 */ int ALL_DISTRIBUTE::__maxGys(int i, int j) { int max = i < j ? j : i; int min = i < j ? i : j; int idx = min; if (min == 0) { return 1; } do { if (max % idx == 0 && min % idx == 0) { return idx; } else { idx = max % min; max = min; min = idx; } } while (idx > 0); return 1; } /* 获取最大公约数 */ int ALL_DISTRIBUTE::findMaxDev(int a[], int i, int j) { int idx = 0; if (i>j) { return -1; } if (i==j) { if (a[0]==0) { return 1; } else { return a[i]; } } int maxGys = __maxGys(a[i], a[i+1]); for (idx = i+2; idx<=j; idx++) { maxGys = __maxGys(maxGys, a[idx]); } return maxGys; } /* 获取最小公倍数 */ int ALL_DISTRIBUTE::findMinMulti(int a[], int i, int j) { int minGbs; int idx; if (i<0 || i>j) { return -1; } if (i==j) { return a[i]; } minGbs = __minGbs(a[i], a[i+1]); for (idx = i+2; idx <= j; idx++) { minGbs = __minGbs(minGbs, a[idx]); //cout << minGbs << endl; } return minGbs; } int ALL_DISTRIBUTE::__rand(int i, int j) { int ret = 0; if (i>j) { return INVALID_VALUE32; } ret = i + rand() % (j - i + 1); return ret; } //产生一个[0-1]的均匀随机数 double ALL_DISTRIBUTE::__rand_zero_one(void) { int ret = rand() % 32767; double res = (32767.0 - ret) / 32767; return res; } double ALL_DISTRIBUTE::standartDis(int ave, double delta) { double random_1 = __rand_zero_one(); double random_2 = __rand_zero_one(); double res = 0; if (delta <=0 ) { assert(0); } res = sqrt(delta)*sqrt(-2 * log(random_1))*cos(2*3.14*random_2) + ave; return res; } int main(int argc, char** argv) { int i = 0; int a[3] = { 312, 374, 380 }; for (i=0; i<3; i++) { cout << a[i] << " "; } cout << endl; cout << ALL_DISTRIBUTE::findMaxDev(a, 0, 2) << endl; cout << ALL_DISTRIBUTE::findMinMulti(a, 0, 2) << endl; return 0; }