一个只有2、3或5作为质因数的数被称为丑数。一些丑数包括:1、2、3、4、5、6、8、10、12、15等。
我们有一个数n,任务是在丑数序列中找到第n个丑数。
例如:
输入-1:
n = 5
输出:
5
explanation:
the 5th ugly number in the sequence of ugly numbers [1, 2, 3, 4, 5, 6, 8, 10, 12, 15] is 5.
input-2:
n = 7
输出:
8
解释:
在丑数序列[1, 2, 3, 4, 5, 6, 8, 10, 12, 15]中,第7个丑数是8。
解决这个问题的方法解决这个问题的一个简单方法是检查给定的数字是否可以被2、3或5整除,并跟踪序列直到给定的数字。现在找到数字是否满足所有丑数的条件,然后将该数字作为输出返回。
输入一个数字n来找到第n个丑数。一个布尔函数isugly(int n)以一个数字'n'作为输入,并返回true,如果它是一个丑数,否则返回false。一个整数函数findnthugly(int n)以'n'作为输入,并返回第n个丑数作为输出。示例演示
public class uglyn { public static boolean isuglynumber(int num) { boolean x = true; while (num != 1) { if (num % 5 == 0) { num /= 5; } else if (num % 3 == 0) { num /= 3; } // to check if number is divisible by 2 or not else if (num % 2 == 0) { num /= 2; } else { x = false; break; } } return x; } public static int nthuglynumber(int n) { int i = 1; int count = 1; while (n > count) { i++; if (isuglynumber(i)) { count++; } } return i; } public static void main(string[] args) { int number = 100; int no = nthuglynumber(number); system.out.println("the ugly no. at position " + number + " is " + no); }}
输出the ugly no. at position 100 is 1536.
以上就是在java中找到第n个丑数的详细内容。