C++ 程式,用於在給定範圍內找出具有 K 個奇數約數的數字


在這個問題中,我們收到三個整數 L、R 和 k。我們的任務是在給定範圍內找出具有 k 個約數的數字。我們將找到範圍內恰好有 k 個約數的數字數量。我們將把 1 和數字本身計算為約數。

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

輸入

a = 3, b = 10, k = 4

輸出

2

解釋

Numbers with exactly 3 divisors within the range 3 to 10 are
6 : divisors = 1, 2, 3, 6 8 : divisors = 1, 2, 4, 8

解決方案方法

解決問題的簡單方案是透過計算 k 個約數。因此,我們將計算範圍內所有數字的約數數量。如果約數的數量為 k,我們將在數字數量中新增 1。

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

示例

 線上演示

#include<bits/stdc++.h>
using namespace std;
int countDivisors(int n) {
   int divisors = 0;
   for (int i=1; i<=sqrt(n)+1; i++) {
      if (n%i==0) {
         divisors++;
         if (n/i != i)
            divisors ++;
      }
   }
   return divisors;
}
int countNumberKDivisors(int a,int b,int k) {
   int numberCount = 0;
   for (int i=a; i<=b; i++) {
      if (countDivisors(i) == k)
         numberCount++;
   }
   return numberCount;
}
int main() {
   int a = 3, b = 10, k = 4;
   cout<<"The count of numbers with "<<k<<" divisors is "<<countNumberKDivisors(a, b, k);
   return 0;
}

輸出

The count of numbers with 4 divisors is 2

更新日期: 2021-03-16

167 瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告