首頁 > Java > java教程 > 主體

在Java中找到第N個醜數

PHPz
發布: 2023-08-20 18:25:07
轉載
754 人瀏覽過

在Java中找到第N個醜數

一個只有2、3或5作為質因數的數稱為醜數。一些醜數包括:1、2、3、4、5、6、8、10、12、15等。

我們有一個數N,任務是在醜數序列中找到第N個醜數。

例如:

##

N = 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:

5
登入後複製

輸出:

N = 7
登入後複製
##解釋:

##在醜數序列[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個醜數作為輸出。

    範例
  • 示範
  • 8
    登入後複製
  • 輸出
  • 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);
       }
    }
    登入後複製

    以上是在Java中找到第N個醜數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!