兩種方法求醜數
我們把僅僅包括因子2、3和5的數稱作醜數(Ugly Number)。比如6、8都是醜數,但14不是,由於它包括因子7。
方法1 :
暴力破解。逐個推斷
代碼:
<pre name="code" class="cpp">#include <iostream> #include <vector> using namespace std; //推斷是否是醜數 bool isUgly(int index){ while(index % 2 == 0){ index /= 2; } while(index % 3 == 0){ index /= 3; } while(index % 5 ==0){ index /=5; } if(index == 1) return true; else return false; } int print(int index){ int count=1; int number = 0; int uglyFound =0; while(uglyFound < index){ ++number; if(isUgly(number)){ ++uglyFound; } } return number; } int main() { cout<<print(1500); return 0; }
執行結果:
方法2 : 採用空間換時間,僅僅是推斷醜數。
一個醜數能夠有另外一個醜數* 2 或者*3 或者*5 得到。
#include <iostream> #include <vector> using namespace std; int Min(int pm2,int pm3,int pm5){ int min = pm2 > pm3 ? pm3 : pm2; return min > pm5 ?pm5 : min; } void print(unsigned int index){ if(index == 0) return; int * pUglyNumber = new int[index]; int pNextIndex=1; pUglyNumber[0] = 1; int *pM2 = pUglyNumber; int *pM3 = pUglyNumber; int *pM5 = pUglyNumber; while(pNextIndex < index){ int min=Min(*pM2 * 2,*pM3 * 3, *pM5 * 5); pUglyNumber[pNextIndex] = min; while(*pM2 * 2 <=pUglyNumber[pNextIndex]) ++pM2; while(*pM3 * 3 <=pUglyNumber[pNextIndex]) ++pM3; while(*pM5 * 5 <= pUglyNumber[pNextIndex]) ++pM5; pNextIndex ++; } int ugly = pUglyNumber[pNextIndex - 1]; delete [] pUglyNumber; cout<< ugly; } int main() { print(7); return 0; }
執行結果:
兩種方法求醜數