Java实现查找第N个丑数


如果一个数的质因数只有2、3或5,则称其为丑数。一些丑数是:1, 2, 3, 4, 5, 6, 8, 10, 12, 15,等等。

我们有一个数字**N**,任务是找到丑数序列中的第N个丑数。

例如

输入-1

N = 5

输出

5

解释

丑数序列[1, 2, 3, 4, 5, 6, 8, 10, 12, 15]中的第5个丑数是5。

输入-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.

更新于:2021年2月23日

905 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.