在给定的问题中,我们需要打印给定整数 n 的所有约数。
input: 15output: 1 3 5 15explanationdivisors of 15 are: 1,3, 5, 15input: 30output: 1 2 3 5 15 30
在给定的问题中,我们可以应用埃拉托斯特尼筛法中使用的方法来找到n的所有约数。
找到解决方案的方法在给定的方法中,我们将应用埃拉托斯特尼筛法的概念,并找到n的约数。
示例#include <bits/stdc++.h>#define mod 1000000007using namespace std;vector<int> divisors[100001]; // our vector containing number with all of its divisorsvoid 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 61 2 3 5 6 10 15 30
上述代码的解释在这种方法中,我们遵循与埃拉托色尼筛相同的概念。我们找到 105 之前每个数字的除数。当我们收到 q 个查询时,我们不需要找到除数,因此这大大降低了我们在询问 q 个查询时的时间复杂度。因此,我们的复杂度变为 o(q*n),其中 q 是我们处理的查询数量,n 是 n 的除数数量。
结论在本文中,我们解决了一个问题:查询打印 n 的所有约数,其中我们应用了埃拉托斯特尼筛法原理。我们还学习了解决此问题的 c++ 程序以及解决此问题的完整方法(normal)。我们可以用其他语言比如c、java、python等语言来编写同样的程序。我们希望这篇文章对您有所帮助。
以上就是使用c++打印出n的所有因数的查询的详细内容。