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.
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP