Description:
-
The Number that contains only factors 2, 3, and 5 is called the Ugly Number ). For example, values 6 and 8 are ugly, but 14 is not because it contains factor 7.
In habits, we regard 1 as the first ugly number. Calculate the nth ugly number in the ascending order.
-
Input:
-
The input includes an integer N (1 <=n <= 1500 ).
-
Output:
-
Multiple groups of test data may exist. For each group of data,
Output the nth ugly number.
-
Sample input:
3
-
Sample output:
3
Solution:
The simplest idea is to check whether each number is an ugly number from 1 to A large number. The detection method can be considered.
int ugly(int number){ if(number%2 == 0){ return ugly(number/2); }else if(number%3 == 0){ return ugly(number/3); }else if(number%5 == 0){ return ugly(number/5); }else return number==1?true:false;}
However, this approach will waste a lot of time and time out.
Let's consider an array,The array stores the current ugly number. In the future, each ugly number is multiplied by the elements of the previous array.. The next step is how to get the ugly number and ensure that it is in order.
It can be thought that the first element of the array is the multiplication of 1, 1 and 2 3 5 respectively, and three values can be obtained. The smallest of these three values must be the maximum value of the next ugly number, then, the subscript of max2 is moved back to continue the comparison.
void mkUglyNumber(){ gArr[top++] = 1; int *max2 = gArr; int *max3 = gArr; int *max5 = gArr; while(top < 1500){ int min = getMin(*max2*2,*max3*3,*max5*5); gArr[top] = min; while(*max2*2 <= gArr[top]) ++max2; while(*max3*3 <= gArr[top]) ++max3; while(*max5*5 <= gArr[top]) ++max5; ++top; }}
For example,If the current array element is only 1, multiply it by 2 3 5 to get 2 3 5. Obviously, the minimum value is 2. The array element is changed to 1 2.
The subscript is changed to 2 1 1. Multiply the subscript by 2 3 5 to get 4 3 5. Find the smallest of them and put it in the array. The element is changed to 1 2 3.
Continue until the first ugly number is found. Read the ugly number each time..
All code:
#include <stdio.h>#define MAXSIZE 1500void mkUglyNumber();int getMin(int max2,int max3,int max5);int gArr[MAXSIZE];int top;int main(){ int n; top = 0; mkUglyNumber(); while(scanf("%d",&n)!=EOF && n>=1 && n<=1500){ printf("%d\n",gArr[n-1]); } return 0;}void mkUglyNumber(){ gArr[top++] = 1; int *max2 = gArr; int *max3 = gArr; int *max5 = gArr; while(top < 1500){ int min = getMin(*max2*2,*max3*3,*max5*5); gArr[top] = min; while(*max2*2 <= gArr[top]) ++max2; while(*max3*3 <= gArr[top]) ++max3; while(*max5*5 <= gArr[top]) ++max5; ++top; }}int getMin(int max2,int max3,int max5){ int min = max2<max3?max2:max3; return min<max5?min:max5;}/************************************************************** Problem: 1214 User: xhalo Language: C Result: Accepted Time:10 ms Memory:920 kb****************************************************************/