- 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