Given two numbers A and B where 1 <= A <= B. The task is to count the number of pairs whose elements are co-prime where pairs are formed from the sum of the digits of the elements in the given range.
Note: Two pairs are counted as distinct if at least one of the number in the pair is different. It may be assumed that the maximum digit sum can be 162.
Input: 12 15 Output: 4 12 = 1+2 = 3 13 = 1+3 = 4 14 = 1+4 = 5 15 = 1+5 = 6 Thus pairs who are co-prime to each other are (3, 4), (3, 5), (4, 5), (5, 6) i.e the answer is 4. Input: 7 10 Output: 5
- Consider each and every element from a to b.
- Find the sum of the digits of every element and store it into a vector.
- Consider each and every pair one by one and check if the gcd of the elements of that pair is 1.
- If yes, count that pair as it is co-prime.
- Print the count of pairs that are co-prime.
Below is the implementation of above approach:
As mentioned in the question, the maximum sum can be 162. So, find out the frequency of numbers having their digit sum from 1 to 162 in range A to B and store the frequency in the array. Later, find the answer using this frequency.
Thus Number of gcd pairs = freq(3)*freq(4) + freq(3)*freq(5) + freq(4)*freq(5) + freq(5)* freq(6)
Thus pairs who are co-prime to each other are (3,4), (3,5), (4,5), (5,6) i.e the answer is 4.
Below is the required implementation:
- Water Jug Problem using Memoization
- Sum of elements of all partitions of number such that no element is less than K
- Largest Sum Contiguous Subarray
- Longest Increasing Subsequence Size (N log N)
- Palindrome Partitioning | DP-17
- Maximum sum in circular array such that no two elements are adjacent
- Edit Distance | DP using Memoization
- Coin Change | DP-7
- 0-1 Knapsack Problem | DP-10
- Find the longest path in a matrix with given constraints
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : andrew1234