使用 C++ 中 [1, n] 範圍內的所有數字的因數數


此題給定一個數字 N。我們的任務是求出 [1, n] 範圍內的所有數字的因數數。

讓我們舉一個例子來理解一下這個問題,

Input : N = 7
Output : 1 2 2 3 2 4 2

求解方法

解決這個問題的一個簡單方法是,從 1 到 N 依次遍歷,併為每個數字計算因數數,然後輸出。

示例 1

編寫程式演示我們解決方案的工作原理

#include <iostream>
using namespace std;
int countDivisor(int N){
   int count = 1;
   for(int i = 2; i <= N; i++){
      if(N%i == 0)
         count++;
   }
   return count;
}
int main(){
   int N = 8;
   cout<<"The number of divisors of all numbers in the range are \t";
   cout<<"1 ";
   for(int i = 2; i <= N; i++){
      cout<<countDivisor(i)<<" ";
   }
   return 0;
}

輸出

The number of divisors of all numbers in the range are 1 2 2 3 2 4 2 4

解決這個問題的另一種方法是使用增量值。為此,我們將建立一個大小為 (N+1) 的陣列。然後,從 1 到 N,我們將檢查每個值 i,我們會增加所有 i 之倍數(小於 n)的陣列值。

示例 2

編寫程式演示我們解決方案的工作原理,

#include <iostream>
using namespace std;
void countDivisors(int N){
   int arr[N+1];
   for(int i = 0; i <= N; i++)
      arr[i] = 1;
      for (int i = 2; i <= N; i++) {
         for (int j = 1; j * i <= N; j++)
            arr[i * j]++;
      }
      for (int i = 1; i <= N; i++)
         cout<<arr[i]<<" ";
}
int main(){
   int N = 8;
   cout<<"The number of divisors of all numbers in the range are \t"; countDivisors(N);
   return 0;
}

輸出

The number of divisors of all numbers in the range are 1 2 2 3 2 4 2 4

更新於: 2022-01-24

709 瀏覽量

開啟你的職業

透過完成課程獲得認證

開始吧
廣告