LintCode 728: Three Distinct Factors

本文介绍了一种高效算法,用于检查给定的正整数(1<=n<=10^18)是否恰好有三个不同的因子。通过判断该数是否可以表示为1、其平方根和平方根的平方,且平方根为质数,来确定其因子数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值