Thursday, December 17, 2009

Ugly Number Calculation Algorithm

package javaapplication1;
/**
** @author sachika
*/
public class Main {

public static void main(String[] args) {

Main mainObj = new Main();
int no = mainObj.getNthUglyNo(11);
System.out.print(no);
try{
System.in.read();
}
catch(Exception s) {}

}

int maxDivide(int a, int b)
{
while (a%b == 0)
a = a/b;
return a;
}

boolean isUgly(int no)
{
no = maxDivide(no, 2);
no = maxDivide(no, 3);
no = maxDivide(no, 5);

return (no == 1)? true : false;
}

int getNthUglyNo(int n)
{
int i = 1;
int count = 1; /* ugly number count */

/*Check for all integers untill ugly count
becomes n*/
while (n > count)
{
i++;
if (isUgly(i))
count++;
}
return i;
}

}

Post a Comment