Problem

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

Given n = 9, return true
Number 9 has exactly three factors: 1, 3, 9, so return true.

Given n = 10, return false

Solution

public class Solution {
    /**
     * @param n: the given number
     * @return:  return true if it has exactly three distinct factors, otherwise false
     */
    public boolean isThreeDisctFactors(long n) {
        // write your code here
        long fac = (long) Math.sqrt(n);
        if (fac * fac != n) return false;
        for (long i = 2; i < fac; i++) {
            if (n % i == 0) return false;
        }
        return true;
    }
}

linspiration
161 声望53 粉丝