Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Created July 2, 2013 19:21
Show Gist options
  • Select an option

  • Save riyadparvez/5912268 to your computer and use it in GitHub Desktop.

Select an option

Save riyadparvez/5912268 to your computer and use it in GitHub Desktop.
A number is ugly number in C# if it's product of 2, 3 and 5. This function finds nth ugly number using brute force approach.
public static int PowerRemainder(int n, int divisor)
{
while((n%divisor) == 0)
{
n /= divisor;
}
return n;
}
public static int UglyNumberNth(int n)
{
if(n<=0)
{
throw new ArgumentOutOfRangeException();
}
int count = 1;
int i = 2;
while(count < n)
{
int temp = PowerRemainder(i, 2);
temp = PowerRemainder(temp, 3);
temp = PowerRemainder(temp, 5);
if (temp == 1)
{
count++;
}
i++;
}
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment