Analyzing a number is not the number of ugly

Here Insert Picture Description

#include<iostream>
using namespace std;
bool func(int num)
{
	int flag = 0;
	for (int i = 2; i <= sqrt(num); ++i)
	{
		if (num% i == 0)
		{
			flag = 1;
			break;
		}
	}
	if (flag == 1)
		return false;
	return true;
}
int GetUglyNumber_Solution(int index) {
	if (index == 1)
		return 1;
	if (index == 2)
		return 2;
	if (index == 3)
		return 3;
	int count = 3;
	int i = 0;
	int j = 4;
	while (1)
	{
		int flag = 0;
		for (int i = 2; i <= j; ++i)
		{
			if (i != 2 && i != 3 && i != 5 && j % i == 0 && func(i))
			{
					flag = 1;
					break;
			}
		}
		if (flag == 0)
			cout << count++ << endl;;
		if (count == index)
			break;
		++j;
	}
	return j;
}
int main()
{

	cout << GetUglyNumber_Solution(1300) << endl;
	return 0;
}

The code above, the time complexity is too high
to go about four hundred, the speed will be very slow

And then I found the Gangster code of this code, it was possible to find a regular, violence is not acceptable
Here Insert Picture Description

class Solution {
public:
int GetUglyNumber_Solution(int index) {
        if(index<7) 
            return index;
        int* ret = new int[index];
        ret[0]=1;
        int t2=0,t3=0,t5=0;
        for(int i=1;i<index;i++) {
            ret[i] = min(min(ret[t2]*2,ret[t3]*3),ret[t5]*5);
            if(ret[i] == ret[t2]*2) t2++;
            if(ret[i] == ret[t3]*3) t3++;
            if(ret[i] == ret[t5]*5) t5++;
        }
        return ret[index-1];
    }
    static int min(int a,int b) {
        return a<b ? a : b; 
    }
};
Published 230 original articles · won praise 28 · views 9314

Guess you like

Origin blog.csdn.net/weixin_43767691/article/details/103553146