Tuesday, July 22, 2008

C program to find 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.

Here is the program to find nth Ugly number



main()
{
int i, j, n, count = 0;
printf("Enter which ugly number you want\n");
scanf("%d", &n);
int b[n];
for(i = 1; count < n; i++)
{
j = i;
while(j % 2 == 0)
{
j = j / 2;
}
while(j % 3 == 0)
{
j = j /3;
}
while(j % 5 == 0)
{
j = j / 5;
}
if(j == 1)
{
b[count] = i;
count++;
}
}
printf("nth ugly number is %d", b[n-1]);
getch();
}

No comments: