![]() |
Given a Binary Tree, the task is to print all the co-prime paths of this tree.
Examples: Input: 1 / \ 12 11 / / \ 3 4 13 \ / 15 3 Output: 1 11 4 15 1 11 13 3 Explanation: {1, 11, 4, 15} and {1, 11, 13, 3} are coprimes because their GCD is 1. Input: 5 / \ 21 77 / \ \ 61 16 16 \ / 10 3 / 23 Output: 5 21 61 5 77 16 3 Explanation: {5, 21, 61} and {5, 77, 16, 3} are coprimes because their GCD is 1. Approach: The idea is to traverse the tree and check if all the elements in that path are coprime or not. So, an efficient solution is to generate all the prime factors of the integers by using the Sieve of Eratosthenes. Using hash, store the count of every element which is a prime factor of any of the number in the array. If the element does not contain any common prime factor with other elements, it always forms a co-prime pair with other elements. Below is the implementation of the above approach: C++
Java
Python3
C#
Javascript
Output:
10 3 11 7 10 3 11 29 10 3 37 19 7
Time Complexity: O(n*log(log(n))) Auxiliary Space: O(n) |
Reffered: https://www.geeksforgeeks.org
Tree |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |