Returns the nth number of ugly

Source: Internet
Author: User
The numbers that contain only 2, 3, and 5 are called ugly Numbers (Ugly number), for example: 2,3,4,5,6,8,9,10,12,15, and so on, we used to think of 1 as the first ugly number.

Write an efficient algorithm to return the nth ugly number.

Solution 1: To determine whether a number is an ugly number, consecutive find the nth number of ugly

#include <iostream>
using namespace std;

BOOL isugly (int num) {
	if (num < 1) return
		false;
	if (num = 1) return
		true;
	while (num% 2 = 0)
		num/= 2;
	while (num% 3 = 0)
		num/= 3;
	while (num% 5 = 0)
		num/= 5;
	return num = = 1;
}

int nthugly (int n) {
	int index = 1, x = 2;
	while (Index < n) {
		if (isugly (x)) {
			index++;
			++x;
		}
		else
			++x;
	}
	return x-1;
}

int main () {
	int n;
	cout << "Input the number n:\n";
	CIN >> N;
	cout << nthugly (n);
	return 0;
}


Solution 2: Multiply 2,3,5 in the current ugly number to find the smallest subsequent ugly number added to the sequence

#include <iostream>
using namespace std;

int minOf3 (int a, int b, int c) {
	int temp = (A < b a:b);
	Return (Temp < C. temp:c);
}

Long findugly (int n) {
	int *ugly = new Int[n];
	Ugly[0] = 1;
	int index2 = 0, index3 = 0, index5 = 0;
	int index = 1;
	while (Index < n) {
		int val = minOf3 (Ugly[index2] * 2, UGLY[INDEX3] * 3, UGLY[INDEX5] * 5);
		Ugly[index] = val;
		while (Val >= ugly[index2] * 2)
			++index2;
		while (Val >= ugly[index3] * 3)
			++index3;
		while (Val >= ugly[index5] * 5)
			++index5;
		index++;
	}
	cout <<	ugly[n-1];
	delete [] ugly;
	return 0;
}

int main () {
	int n;
	cout << "Input the number n:\n";
	CIN >> N;
	findugly (n);
	return 0;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.