- Three Distinct Factors
Given a positive integer n (1 <= n <= 10^18). Check whether a number has exactly three distinct factors, return true if it has exactly three distinct factors, otherwise false.
Example
Example1
Input: n = 9
Output: true
Explanation:
Number 9 has exactly three factors: 1, 3, 9, so return true.
Example2
Input: n = 10
Output: false
Explanation:
Number 10 has four factors: 1, 2, 5, 10, so return false.
解法1:
注意满足3个因子的数一定是1 X sqrt X sqrt=N。其中sqrt必须是质数。
class Solution {
public:
/**
* @param n: the given number
* @return: return true if it has exactly three distinct factors, otherwise false
*/
bool isThreeDisctFactors(long long n) {
long long sqrtN = sqrt(n);
if (sqrtN * sqrtN != n) return false;
return isPrime(sqrtN);
}
private:
bool isPrime(long long num) {
long long sqrtNum = sqrt(num);
for (int i = 2; i <= sqrtNum; ++i) {
if (num % i == 0) return false;
}
return true;
}
};
代码同步在
https://github.com/luqian2017/Algorithm
本文介绍了一种高效算法,用于检查给定的正整数(1<=n<=10^18)是否恰好有三个不同的因子。通过判断该数是否可以表示为1、其平方根和平方根的平方,且平方根为质数,来确定其因子数量。
2541

被折叠的 条评论
为什么被折叠?



