查询以找出在C ++中数字是否恰好具有四个不同的因子
在这个问题中,我们给了Q个查询,每个查询都有一个N。我们的任务是创建一个程序来解决查询,以查找一个数字在C++中是否具有完全不同的四个因素。
问题描述
为了解决每个查询,我们需要确定数字N是否正好具有四个不同的因子。如果打印的是,则为否。
让我们举个例子来了解这个问题,
输入:Q=3,4,6,15
输出:否是是
说明
对于查询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
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短