在C++中查詢給定範圍內具有K個奇數約數的數字


在這個問題中,我們得到了三個整數值L、R和k。我們的任務是在給定的範圍內查詢具有K個奇數約數的數字。我們將查詢區間[L, R]中恰好具有k個約數的數字的數量。

我們將1和數字本身都計算為約數。

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

輸入

a = 3, b = 10, k = 3

輸出

2

解釋

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

解決方案方法

解決這個問題的一個簡單方法是計算k個約數。因此,為了使k成為奇數(如問題所示),該數字必須是完全平方數。因此,我們將只計算完全平方數的約數個數(這將節省編譯時間)。如果約數的個數為k,我們將把數字計數加1。

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

示例

 線上演示

#include<bits/stdc++.h>
using namespace std;
bool isPerfectSquare(int n) {
   int s = sqrt(n);
   return (s*s == n);
}
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 (isPerfectSquare(i))
         if (countDivisors(i) == k)
            numberCount++;
   }
   return numberCount;
}
int main() {
   int a = 3, b = 10, k = 3;
   cout<<"The count of numbers with K odd divisors is "<<countNumberKDivisors(a, b, k);
   return 0;
}

輸出

The count of numbers with K odd divisors is 2

更新於:2021年3月15日

147 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.