Check if given number has 7 divisors

Given a number N, the task is to check whether N has 7 divisors or not.

Examples:

Input: 64
Output:
Explanation: 1, 2, 4, 8, 16, 32, 64 -> 7 divisors so output is 1

Input: 100
Output: 0
Explanation: 1, 2, 4, 5, 10, 20, 25, 50, 100 -> 8 divisors so output is 0

Input: 729
Output: 1
Explanation: 1, 2, 4, 8, 16, 32, 64 -> 7 divisors so output is 1

Approach: The problem can be solved based on the following mathematical observation:

The prime factorization of a number is:
N = p1e1 * p2e2 * . . . * pnen 
So number of divisors = ( e1 + 1 ) * (e2 + 1) *. . . * (en + 1).

In this case, number of divisors = 7 .
So, ( e1 + 1 ) * (e2 + 1) *. . . * (en + 1) = 7

7 is multiplication of at most 2 natural numbers. 
So, it can be only written as ( e1 + 1 ) * (e2 + 1) = 1 * 7    
So, e1 = 0  &  e2 = 6  from above equation.

So, it is clear that for 7 divisors only one case is possible and that is (prime number)6. Follow the steps to solve the problem:

  • Check if N(1/6) is a prime number or not.
  • If it is prime number then output “Yes”.
  • Otherwise, the output will be “No”.

Below is the implementation of the above approach: 

C++

  

#include <bits/stdc++.h>

using namespace std;

  

int sevenDivisors(int N)

{

    

    int k = pow(N, 1 / 6.);

  

    

    

    int res = pow(k, 6);

  

    

    

    if (N == res)

        return 1;

    return 0;

}

  

int main()

{

    int N = 64;

  

    

    bool ans = sevenDivisors(N);

    if (ans)

        cout << "Yes";

    else

        cout << "No";

    return 0;

}

Time Complexity: O(logN)
Auxiliary Space: O(1)