首页 > 文章列表 > 使用C++打印出n的所有因数的查询

使用C++打印出n的所有因数的查询

打印 c 因数
372 2023-09-08

在给定的问题中,我们需要打印给定整数 n 的所有约数。

Input: 15
Output: 1 3 5 15
Explanation
Divisors of 15 are: 1,3, 5, 15

Input: 30
Output: 1 2 3 5 15 30

在给定的问题中,我们可以应用埃拉托斯特尼筛法中使用的方法来找到n的所有约数。

找到解决方案的方法

在给定的方法中,我们将应用埃拉托斯特尼筛法的概念,并找到n的约数。

示例

#include <bits/stdc++.h>
#define MOD 1000000007

using namespace std;

vector<int> divisors[100001]; // our vector containing number with all of its divisors
void findsieve(int max) { // filling data in vector divisors till 10e5
   for(int i = 1; i <= max; i++) {
      for(int j = i; j <= max; j += i)
         divisors[j].push_back(i);
   }
}
void __print(int n){ // the function to print divisors
   for(auto x : divisors[n])
      cout << x << " ";
   cout << "n";
}

int main() {
   findsieve(100000); // we hardcode the sieve and divisors till 10e5
   int n = 6; // the given n
   __print(n);
   n = 30; // new n
   __print(n);
   return 0;
}

输出

1 2 3 6
1 2 3 5 6 10 15 30

上述代码的解释

在这种方法中,我们遵循与埃拉托色尼筛相同的概念。我们找到 105 之前每个数字的除数。当我们收到 q 个查询时,我们不需要找到除数,因此这大大降低了我们在询问 q 个查询时的时间复杂度。因此,我们的复杂度变为 O(Q*N),其中 Q 是我们处理的查询数量,N 是 n 的除数数量。

结论

在本文中,我们解决了一个问题:查询打印 n 的所有约数,其中我们应用了埃拉托斯特尼筛法原理。我们还学习了解决此问题的 C++ 程序以及解决此问题的完整方法(Normal)。我们可以用其他语言比如C、java、python等语言来编写同样的程序。我们希望这篇文章对您有所帮助。