Suppose we have a number n, we have to check whether n is a Trojan Number or not. As we know that the Trojan Number is a number that is a strong number without a perfect power. A number n is a strong number when for every prime divisor or factor p of n, p^2 is also a divisor. In other words, every prime factor appears at least twice. Trojan numbers are strong. But the reverse is not true. So it means, not all strong numbers are Trojan numbers: only those that cannot be represented as a^b.
So, if the input is like 72, then the output will be True, as 72 can be represented as (6*6*2) = (6^2 * 2). Strong Number but without perfect power.
To solve this, we will follow these steps −
- Define a function check_perfect_pow() . This will take n
- if n is same as 1, then
- return True
- for x in range 2 to integer part of (square root of n) + 1, do
- y := 2
- p = x^y
- while p <= n and p > 0, do
- if p is same as n, then
- return True
- y := y + 1
- p = x^y
- if p is same as n, then
- return False
- Define a function check_strong_num() . This will take n
- count := a map to hold frequency of numbers, initially all are 0
- while n mod 2 is same as 0, do
- n := n / 2 (integer division)
- count[2] := count[2] + 1
- for i in range 3 to integer part of (square root of n) + 1, increase by 2, do
- while n mod i is same as 0, do
- n := n / i (integer division)
- count[i] := count[i] + 1
- while n mod i is same as 0, do
- if n > 2 is non-zero, then
- count[n] := count[n] + 1
- flag := 0
- for each key,value in items() of count, do
- if value is same as 1, then
- flag := 1
- break
- if value is same as 1, then
- if flag is same as 1, then
- return False
- return True
- From the main method do the following −
- return true when check_perfect_pow(n) is False and check_strong_num(n) is true, otherwise return false
Example
Let us see the following implementation to get better understanding −
from math import sqrt, pow
def check_perfect_pow(n):
if n == 1:
return True
for x in range(2, int(sqrt(n)) + 1):
y = 2
p = x**y
while p <= n and p > 0:
if p == n:
return True
y += 1
p = x**y
return False
def check_strong_num(n):
count = {i:0 for i in range(n)}
while n % 2 == 0:
n = n // 2
count[2] += 1
for i in range(3,int(sqrt(n)) + 1, 2):
while n % i == 0:
n = n // i
count[i] += 1
if n > 2:
count[n] += 1
flag = 0
for key,value in count.items():
if value == 1:
flag = 1
break
if flag == 1:
return False
return True
def isTrojan(n):
return check_perfect_pow(n) == False and check_strong_num(n)
n = 72
print(isTrojan(n))Input
72
Output
True