C++中查找数字是否恰好有四个不同因子的查询
在这个问题中,我们得到了Q个查询,每个查询都有一个数字N。我们的任务是创建一个程序来解决这些查询,以判断C++中一个数字是否恰好有四个不同的因子。
问题描述
为了解决每个查询,我们需要找到数字N是否恰好有四个不同的因子。如果有,则打印YES,否则打印NO。
让我们举个例子来理解这个问题:
输入:Q = 3, 4, 6, 15
输出:NO YES YES
解释
对于查询1:4的因子是1, 2, 4
对于查询2:6的因子是1, 2, 3, 6
对于查询3:15的因子是1, 3, 5, 15
解决方案
一个简单的解决方案是找到该数字的所有因子。这是通过查找从1到√N的所有数字,并将计数器增加2来完成的。然后检查计数器是否等于4,并根据其相等性打印YES或NO。
示例
#include <iostream> #include <math.h> using namespace std; int solveQuery(int N){ int factors = 0; for(int i = 1; i < sqrt(N); i++){ if(N % i == 0){ factors += 2; } } if(factors == 4){ return 1; } return 0; } int main() { int Q = 3; int query[3] = {4, 6, 15}; for(int i = 0; i < Q; i++){ if(solveQuery(query[i])) cout<<"The number "<<query[i]<<" has exactly four distinct factors\n"; else cout<<"The number "<<query[i]<<" does not have exactly four distinct factors\n"; } }
输出
The number 4 does not have exactly four distinct factors The number 6 has exactly four distinct factors The number 15 has exactly four distinct factors
一种有效的方法是使用数论中关于四个因子数的概念。因此,如果一个数字有四个因子,则:
如果该数字是素数的立方。那么它将有四个不同的因子。例如,如果N = (p^3),则因子将是1, p, (p^2), N。
如果该数字是两个不同素数的乘积。那么它也将有四个不同的因子。例如,如果N = p1*p2,则因子将是1, p1, p2, N。
示例
#include <bits/stdc++.h> using namespace std; int N = 1000; bool hasFourFactors[1000]; void fourDistinctFactors() { bool primeNo[N + 1]; memset(primeNo, true, sizeof(primeNo)); for (int i = 2; i <= sqrt(N); i++) { if (primeNo[i] == true) { for (int j = i * 2; j <= N; j += i) primeNo[j] = false; } } vector<int> primes; for (int i = 2; i <= N; i++) if (primeNo[i]) primes.push_back(i); memset(hasFourFactors, false, sizeof(hasFourFactors)); for (int i = 0; i < primes.size(); ++i) { int p1 = primes[i]; if (1 *(pow(p1, 3)) <= N) hasFourFactors[p1*p1*p1] = true; for (int j = i + 1; j < primes.size(); ++j) { int p2 = primes[j]; if (1 * p1*p2 > N) break; hasFourFactors[p1*p2] = true; } } } int main() { int Q = 3; int query[] = {3, 6, 15}; fourDistinctFactors(); for(int i = 0; i < Q; i++){ if(hasFourFactors[query[i]]) cout<<"The number "<<query[i]<<" has exactly four distinct factors\n"; else cout<<"The number "<<query[i]<<" does not have exactly four distinct factors\n"; } return 0; }
输出
The number 3 does not have exactly four distinct factors The number 6 has exactly four distinct factors The number 15 has exactly four distinct factors
广告