使用 C++ 查詢僅由素數數字(2、3、5 和 7)組成的第 n 個數


在這個問題中,我們給定一個數字 N。我們的任務是查詢僅由素數數字(2、3、5 和 7)組成的第 n 個數

僅由素數數字(2、3、5、7)組成的序列是:2、3、5、7、22、23、25、27、32、33...

讓我們舉個例子來理解這個問題:

Input: N = 6
Output: 23

解決方案方法

解決該問題的一種簡單方法是找到給定索引 i 處的數字,即找到該序列的項,為此,我們將觀察該序列。

我們有四個不同的素數,因此生成的序列可以被視為一個四位數字系統。在這個數字系統中,我們有 4x 個長度為 x 的數字。

現在要解決問題,我們有了一個序列,在這個序列中我們將找到構成這些數字的數字的長度。然後我們將計算第 N 個數字並列印所需的數字。

為了使用長度找到第 N 個數字,我們將從長度為 (x-1) 的第一個數字開始計數,然後計算這個 N。

示例

程式說明我們解決方案的工作原理

#include <iostream>
#include <math.h>
using namespace std;
void findNthNumber(int n){
   long x = 1;
   long lastNum = 0;
   while (true) {
      long currNum = lastNum + pow(4, x);
      if (lastNum < n && currNum >= n)
         break;
      x++;
      lastNum = currNum;
   }
   for (int i = 1; i <= x; i++) {
      for (long j = 1; j <= 4; j++) {
         if (lastNum + pow(4, x - i) < n)
            lastNum += pow(4, x - i);
         else {
            if (j == 1)
               cout<<"2";
            else if (j == 2)
               cout<<"3";
            else if (j == 3)
               cout<<"5";
            else if (j == 4)
               cout<<"7";
            break;
         }
      }
   }
}
int main(){
   int N = 32;
   cout<<N<<"th number made of prime digits is ";
   findNthNumber(N);
   return 0;
}

輸出

32th number made of prime digits is 257

更新於: 2022 年 2 月 1 日

491 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告