Given a positive integer N, the task is to find the height of the Factor Tree of the given integer N.
Examples:
Input: N = 20
Output: 3
Explanation: The height of the Factor Tree of 20 shown in the image below is 3.

Input: N = 48
Output: 5
Approach: The given problem can be solved by using the steps discussed below:
- Initialize a variable, say height as 0 that stores the height of the Factor Tree of the given integer N.
- Iterate over all the values of i in the range [2, ?N] and perform the following steps:
- Find the smallest divisor of N and if it exists, then increment the value of height by 1.
- If a divisor i exists, then repeat the above step by updating the value of N to N / i, until N > 1.
- If no divisors of N exist break the loop.
- After completing the above steps, print the value of height as the answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int factorTree(int N)
{
int height = 0;
while (N > 1) {
bool flag = false;
for (int i = 2; i <= sqrt(N); i++) {
if (N % i == 0) {
N = N / i;
flag = true;
break;
}
}
height++;
if (!flag) {
break;
}
}
return height;
}
int main()
{
int N = 48;
cout << factorTree(N);
return 0;
}
|
Java
public class Main
{
static int factorTree(int N)
{
int height = 0;
while (N > 1)
{
boolean flag = false;
for (int i = 2; i <= Math.sqrt(N); i++)
{
if (N % i == 0) {
N = N / i;
flag = true;
break;
}
}
height++;
if (!flag) {
break;
}
}
return height;
}
public static void main(String[] args) {
int N = 48;
System.out.println(factorTree(N));
}
}
|
Python3
from math import sqrt
def factorTree(N):
height = 0
while (N > 1):
flag = False
for i in range(2,int(sqrt(N))+1,1):
if (N % i == 0):
N = N // i
flag = True
break
height += 1
if (flag==False):
break
return height
if __name__ == '__main__':
N = 48
print(factorTree(N))
|
C#
using System;
class GFG {
static int factorTree(int N)
{
int height = 0;
while (N > 1) {
bool flag = false;
for (int i = 2; i <= Math.Sqrt(N); i++) {
if (N % i == 0) {
N = N / i;
flag = true;
break;
}
}
height++;
if (!flag) {
break;
}
}
return height;
}
static void Main() {
int N = 48;
Console.Write(factorTree(N));
}
}
|
Javascript
<script>
function factorTree(N)
{
let height = 0;
while (N > 1)
{
let flag = false;
for (let i = 2; i <= Math.sqrt(N); i++)
{
if (N % i == 0) {
N = Math.floor(N / i);
flag = true;
break;
}
}
height++;
if (!flag) {
break;
}
}
return height;
}
let N = 48;
document.write(factorTree(N));
</script>
|
Time Complexity: O(?N*log N)
Auxiliary Space: O(1)
Last Updated :
08 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...