Check if a number is a Trojan Numbers in C++

C++Server Side ProgrammingProgramming

Concept

With respect of given number n, the task is to verify whether n is a Trojan Number or not. Trojan Number is defined as a number that is a strong number without a perfect power. We can say that a number n is treated as a strong number if, for every prime divisor or factor p of n, p^2 is also a divisor. We can say in another way, every prime factor appears at least twice. We should remember that all Trojan numbers are strong. But it is not true for vice-versa that means, not all strong numbers are Trojan numbers: only those that cannot be represented as a^b, where a and b are positive integers greater than 1.

Input 

n = 72
72 is expressed as 6×6×2 i.e. (6^2)×2 i.e. Strong Number but without perfect power.

Output 

YES

Input 

n = 16
16 is expressed as 2×2×2×2 i.e. 2^4 i.e. Strong number with perfect power.

Output 

NO

Approach

At first, we have to store the count of each prime factor and verify if the count is greater than 2 then it will be a Strong Number.

In case of next step, we have to verify whether the given number is expressed as a^b or not. If it is not expressed as a^b, we can say that it is perfect power; otherwise it is perfect power. Finally, at the last step, we can conclude that if this given number is strong without perfect power, the number is treated as Trojan Number.

Example

 Live Demo

// CPP program to check if a number is
// Trojan Number or not
#include <bits/stdc++.h>
using namespace std;
bool isPerfectPower1(int n1){
   if (n1 == 1)
      return true;
   for (int x1 = 2; x1 <= sqrt(n1); x1++) {
      int y1 = 2;
      int p1 = pow(x1, y1);
      while (p1 <= n1 && p1 > 0) {
         if (p1 == n1)
            return true;
         y1++;
         p1 = pow(x1, y1);
      }
   }
   return false;
}
bool isStrongNumber1(int n1){
   unordered_map<int, int> count1;
   while (n1 % 2 == 0) {
      n1 = n1 / 2;
      count1[2]++;
   }
   for (int i1 = 3; i1 <= sqrt(n1); i1 += 2) {
      while (n1 % i1 == 0) {
         n1 = n1 / i1;
         count1[i1]++;
      }
   }
   if (n1 > 2)
      count1[n1]++;
   int flag1 = 0;
   for (auto b : count1) {
      if (b.second == 1) {
         flag1 = 1;
         break;
      }
   }
   if (flag1 == 1)
      return false;
   else
      return true;
}
bool isTrojan1(int n1){
   if (!isPerfectPower1(n1) && isStrongNumber1(n1))
      return true;
   else
      return false;
}
// Driver Code
int main(){
   int n1 = 72;
   if (isTrojan1(n1))
      cout << "YES";
   else
      cout << "NO";
   return 0;
}

Output

Yes
raja
Published on 23-Jul-2020 07:59:17

Advertisements