在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
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP