Pankaj Tanwar
Published on

Three Divisors.

––– views
Authors

Problem of the day - Three Divisors

Tag - Easy

Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.

An integer m is a divisor of n if there exists an integer k such that n = k * m.

Example 1:

Input: n = 2 Output: false Explantion: 2 has only two divisors: 1 and 2.


Just by looking at the problem, I figured out the algorithm.

The trick in this question is, as for each number, it would be divisible to 1 and the number itself. Which meas, We just have to check if its divisible by a perfect square.

class Solution {
public:
bool isPrime(int n) {
for(int i=2;i<n;i++) {
if(n % i == 0) return false;
}
return true;
}
bool isThree(int n) {
// checck the value of n
if(n == 1) return false;
int sq = sqrt(n);
// perfect square and check of isPrime
if(sq * sq == n && isPrime(sq)) return true;
return false;
}
};

I was going through the leetcode discussion tab and I found a great & smart approach for this problem.

If you feel, I am missing on something, feel free to reach out to me

I welcome your suggestions to improve it further!


Thanks for being part of my daily-code-workout journey. As always, if you have any thoughts about anything shared above, don't hesitate to reach out.


You might like previous editions of my coding diary