Ugly Numbers
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …
shows the first 11 ugly numbers. By convention, 1 is included.
Write a program to find and print the 1500’th ugly number.
Input and Output
There is no input to this program. Output should consist of a single line as shown below, with <number> replaced by the number computed.
Sample output
The 1500’th ugly number is <number>.
C Code
#include <stdio.h>
#define min(a,b) (a<b? a:b)
#define min_3(a,b,c) min(min(a,b),c)
int main()
{
int num=0,p2,p3,p5,n;
long a[1501];
a[1]=p2=p3=p5=n=1;
while(1)
{
a[++n]=min_3(2*a[p2],3*a[p3],5*a[p5]);
if(a[n]==2*a[p2]) p2++;
if(a[n]==3*a[p3]) p3++;
if(a[n]==5*a[p5]) p5++;
if(n==1500) break;
}
printf("The 1500'th ugly number is %ld.\n",a[n]);
return 0;
}