Created
July 2, 2013 19:21
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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