Skip to content
Related Articles

Related Articles

Subsets of size K with product equal to difference of two perfect squares

View Discussion
Improve Article
Save Article
  • Last Updated : 02 Aug, 2022
View Discussion
Improve Article
Save Article

Given a distinct integers array arr[] of size N and an integer K, the task is to count the number of subsets of size K of array whose product of elements can be represented as a2 – b2. Examples:

Input: arr[] = {1, 2, 3} K = 2 Output: 2 Explanation: All possible subsets of length 2 with their products are given below: {1, 2} = 2 {2, 3} = 6 {1, 3} = 3 Since, only 3 can be expressed as (22 – 12, therefore only one such subset exists. Input: arr[] = {2, 5, 6} K = 2 Output: 2 Explanation: All possible contiguous sub-sequences with their products given below: {2, 5} = 10 {2, 6} = 12 {5, 6} = 30 Since, only 12 can be expressed as (42 – 22), only one such subset exists.

Approach:

  1. Generate all subsets of size K.
  2. Calculate the products of all subsets.
  3. A number can be represented as the difference of square of two numbers only if it is odd or divisible by 4.
  4. Hence, count all subsets with product that satisfies this condition.

Below is the implementation of the above approach: 

Python3




# Python3 implementation of the approach
 
import itertools
 
# Function to return the
# Count of required sub-sequences
def count_seq(arr, n, k):
 
    # ans is Count variable
    ans = 0
 
    for seq in itertools.combinations(arr, k):
 
        # product of seq
        pro = 1
     
        for ele in seq:
            pro *= ele
     
        # checking form of a2-b2
        if ((pro % 4) != 2):
            ans += 1
    return ans
 
# Driver code
if __name__ == "__main__":
    arr = [2, 5, 6]
    n = len(arr)
    k = 2
    print(count_seq(arr, n, k))

Output:

1
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!