使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP