• 两种方法求丑数


    我们把仅仅包括因子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; }


    执行结果:



  • 相关阅读:
    C++实现按1的个数排序
    杨绛100岁感言
    体验电影演员后的自白
    安装Leanote极客范的云笔记
    Linux下SonarQube代码质量平台的安装和使用方法
    前端开发利器VSCode
    苏州一日游 有惊无险!
    setuptools安装和错误解决
    Linux pip安装使用
    Linux平台安装MongoDB
  • 原文地址:https://www.cnblogs.com/llguanli/p/8452735.html
Copyright © 2020-2023  润新知