Sum of all subsets whose sum is a Perfect Number from a given array
Last Updated :
22 Nov, 2021
Given an array arr[] consisting of N integers, the task is to find the sum of all subsets from an array, whose sum is a Perfect Number.
Examples:
Input: arr[] = {5, 4, 6}
Output: 6
Explanation:
All possible subsets from the array arr[] are:
{5} ? Sum = 5
{4} ? Sum = 4.
{6} ? Sum = 6.
{5, 4} ? Sum = 9.
{5, 6} ? Sum = 11.
{4, 6} ? Sum = 10.
{5, 4, 6} ? Sum = 15.
Out of all subset sums, only 6 sums are found to be2` a perfect number.
Input: arr[] = {28, 6, 23, 3, 3}
Output: 28 6 6
Recursive Approach: The idea is to generate all possible subsets from the given array and print the sum of those subsets whose sum is a perfect number.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check is a given number
// is a perfect number or not
int isPerfect(int x)
{
// Stores the sum of its divisors
int sum_div = 1;
// Add all divisors of x to sum_div
for (int i = 2; i <= x / 2; ++i) {
if (x % i == 0) {
sum_div += i;
}
}
// If the sum of divisors is equal
// to the given number, return true
if (sum_div == x) {
return 1;
}
// Otherwise, return false
else
return 0;
}
// Function to find sum of all
// subsets from an array whose
// sum is a perfect number
void subsetSum(int arr[], int l,
int r, int sum = 0)
{
// Print the current subset sum
// if it is a perfect number
if (l > r) {
// Check if sum is a
// perfect number or not
if (isPerfect(sum)) {
cout << sum << " ";
}
return;
}
// Calculate sum of the subset
// including arr[l]
subsetSum(arr, l + 1, r, sum + arr[l]);
// Calculate sum of the subset
// excluding arr[l]
subsetSum(arr, l + 1, r, sum);
}
// Driver Code
int main()
{
int arr[] = { 5, 4, 6 };
int N = sizeof(arr) / sizeof(arr[0]);
subsetSum(arr, 0, N - 1);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG{
// Function to check is a given number
// is a perfect number or not
static int isPerfect(int x)
{
// Stores the sum of its divisors
int sum_div = 1;
// Add all divisors of x to sum_div
for(int i = 2; i <= x / 2; ++i)
{
if (x % i == 0)
{
sum_div += i;
}
}
// If the sum of divisors is equal
// to the given number, return true
if (sum_div == x)
{
return 1;
}
// Otherwise, return false
else
return 0;
}
// Function to find sum of all
// subsets from an array whose
// sum is a perfect number
static void subsetSum(int[] arr, int l,
int r, int sum)
{
// Print the current subset sum
// if it is a perfect number
if (l > r)
{
// Check if sum is a
// perfect number or not
if (isPerfect(sum) != 0)
{
System.out.print(sum + " ");
}
return;
}
// Calculate sum of the subset
// including arr[l]
subsetSum(arr, l + 1, r, sum + arr[l]);
// Calculate sum of the subset
// excluding arr[l]
subsetSum(arr, l + 1, r, sum);
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 5, 4, 6 };
int N = arr.length;
subsetSum(arr, 0, N - 1, 0);
}
}
// This code is contributed by code_hunt
Python3
# Python3 program for the above approach
import math
# Function to check is a given number
# is a perfect number or not
def isPerfect(x) :
# Stores the sum of its divisors
sum_div = 1
# Add all divisors of x to sum_div
for i in range(2, (x // 2) + 1) :
if (x % i == 0) :
sum_div += i
# If the sum of divisors is equal
# to the given number, return true
if (sum_div == x) :
return 1
# Otherwise, return false
else :
return 0
# Function to find sum of all
# subsets from an array whose
# sum is a perfect number
def subsetSum(arr, l,
r, sum) :
# Print current subset sum
# if it is a perfect number
if (l > r) :
# Check if sum is a
# perfect number or not
if (isPerfect(sum) != 0) :
print(sum, end = " ")
return
# Calculate sum of the subset
# including arr[l]
subsetSum(arr, l + 1, r, sum + arr[l])
# Calculate sum of the subset
# excluding arr[l]
subsetSum(arr, l + 1, r, sum)
# Driver Code
arr = [ 5, 4, 6 ]
N = len(arr)
subsetSum(arr, 0, N - 1, 0)
# This code is contributed by sanjoy_62.
C#
// C# program for the above approach
using System;
class GFG{
// Function to check is a given number
// is a perfect number or not
static int isPerfect(int x)
{
// Stores the sum of its divisors
int sum_div = 1;
// Add all divisors of x to sum_div
for(int i = 2; i <= x / 2; ++i)
{
if (x % i == 0)
{
sum_div += i;
}
}
// If the sum of divisors is equal
// to the given number, return true
if (sum_div == x)
{
return 1;
}
// Otherwise, return false
else
return 0;
}
// Function to find sum of all
// subsets from an array whose
// sum is a perfect number
static void subsetSum(int[] arr, int l,
int r, int sum = 0)
{
// Print the current subset sum
// if it is a perfect number
if (l > r)
{
// Check if sum is a
// perfect number or not
if (isPerfect(sum) != 0)
{
Console.Write(sum + " ");
}
return;
}
// Calculate sum of the subset
// including arr[l]
subsetSum(arr, l + 1, r, sum + arr[l]);
// Calculate sum of the subset
// excluding arr[l]
subsetSum(arr, l + 1, r, sum);
}
// Driver code
static void Main()
{
int[] arr = { 5, 4, 6 };
int N = arr.Length;
subsetSum(arr, 0, N - 1);
}
}
// This code is contributed by divyeshrabadiya07
JavaScript
<script>
// javascript program for the above approach
// Function to check is a given number
// is a perfect number or not
function isPerfect(x) {
// Stores the sum of its divisors
var sum_div = 1;
// Add all divisors of x to sum_div
for (i = 2; i <= x / 2; ++i) {
if (x % i == 0) {
sum_div += i;
}
}
// If the sum of divisors is equal
// to the given number, return true
if (sum_div == x) {
return 1;
}
// Otherwise, return false
else
return 0;
}
// Function to find sum of all
// subsets from an array whose
// sum is a perfect number
function subsetSum(arr , l , r , sum) {
// Print the current subset sum
// if it is a perfect number
if (l > r) {
// Check if sum is a
// perfect number or not
if (isPerfect(sum) != 0) {
document.write(sum + " ");
}
return;
}
// Calculate sum of the subset
// including arr[l]
subsetSum(arr, l + 1, r, sum + arr[l]);
// Calculate sum of the subset
// excluding arr[l]
subsetSum(arr, l + 1, r, sum);
}
// Driver code
var arr = [ 5, 4, 6 ];
var N = arr.length;
subsetSum(arr, 0, N - 1, 0);
// This code contributed by gauravrajput1
</script>
Time Complexity: O(M * 2N), where M is the sum of the elements of the array arr[]
Auxiliary Space: O(1)
Iterative Approach: Since there are 2N possible subsets from an array of size N, the idea is to iterate a loop from 0 to 2N - 1 and for every number, pick all array elements which correspond to 1s in the binary representation of the current number and then check if the sum of the chosen elements is a perfect number or not. Follow the steps below to solve the problem:
- Iterate in the range[0, 2N - 1] using the variable i and perform the following steps:
- Initialize a variable, say S with 0 to store the sum of the current subset.
- Traverse the array arr[] using the variable j and perform the following steps:
- Check if S is a perfect number or not, if found to be true print the value of S as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check is a given
// number is a perfect number or not
int isPerfect(int x)
{
// Stores sum of divisors
int sum_div = 1;
// Add all divisors of x to sum_div
for (int i = 2; i <= x / 2; ++i) {
if (x % i == 0) {
sum_div += i;
}
}
// If the sum of divisors is equal
// to the given number, return true
if (sum_div == x) {
return 1;
}
// Otherwise, return false
else
return 0;
}
// Function to find the sum of all the
// subsets from an array whose sum is
// a perfect number
void subsetSum(int arr[], int n)
{
// Stores the total number of
// subsets, i.e. 2 ^ n
long long total = 1 << n;
// Consider all numbers from 0 to 2 ^ n - 1
for (long long i = 0; i < total; i++) {
long long sum = 0;
// Consider array elements from
// positions of set bits in the
// binary representation of n
for (int j = 0; j < n; j++)
if (i & (1 << j))
sum += arr[j];
// If sum of chosen elements
// is a perfect number
if (isPerfect(sum)) {
cout << sum << " ";
}
}
}
// Driver Code
int main()
{
int arr[] = { 5, 4, 6 };
int N = sizeof(arr) / sizeof(arr[0]);
subsetSum(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Function to check is a given
// number is a perfect number or not
static int isPerfect(int x)
{
// Stores sum of divisors
int sum_div = 1;
// Add all divisors of x to sum_div
for (int i = 2; i <= x / 2; ++i) {
if (x % i == 0) {
sum_div += i;
}
}
// If the sum of divisors is equal
// to the given number, return true
if (sum_div == x) {
return 1;
}
// Otherwise, return false
else
return 0;
}
// Function to find the sum of all the
// subsets from an array whose sum is
// a perfect number
static void subsetSum(int arr[], int n)
{
// Stores the total number of
// subsets, i.e. 2 ^ n
long total = 1 << n;
// Consider all numbers from 0 to 2 ^ n - 1
for (long i = 0; i < total; i++) {
int sum = 0;
// Consider array elements from
// positions of set bits in the
// binary representation of n
for (int j = 0; j < n; j++)
if ((i & (1 << j)) != 0)
sum += arr[j];
// If sum of chosen elements
// is a perfect number
if (isPerfect(sum) != 0) {
System.out.print(sum + " ");
}
}
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 5, 4, 6 };
int N = arr.length;
subsetSum(arr, N);
}
}
// This code is contributed by souravghosh0416.
Python3
# Python3 program for the above approach
# Function to check is a given
# number is a perfect number or not
def isPerfect(x):
# Stores sum of divisors
sum_div = 1
# Add all divisors of x to sum_div
for i in range(2, int(x/2 + 1)):
if (x % i == 0):
sum_div = sum_div + i
# If the sum of divisors is equal
# to the given number, return true
if (sum_div == x):
return 1
# Otherwise, return false
else:
return 0
# Function to find the sum of all the
# subsets from an array whose sum is
# a perfect number
def subsetSum(arr, n):
# Stores the total number of
# subsets, i.e. 2 ^ n
total = 1 << n
# Consider all numbers from 0 to 2 ^ n - 1
for i in range(total):
sum = 0
# Consider array elements from
# positions of set bits in the
# binary representation of n
for j in range(n):
if (i & (1 << j) != 0):
sum = sum + arr[j]
# If sum of chosen elements
# is a perfect number
if (isPerfect(sum)):
print(sum, " ")
# Driver Code
arr = [5, 4, 6]
N = len(arr)
subsetSum(arr, N)
# This code is contributed by Dharanendra L V.
C#
// C# program for the above approach
using System;
class GFG{
// Function to check is a given
// number is a perfect number or not
static int isPerfect(int x)
{
// Stores sum of divisors
int sum_div = 1;
// Add all divisors of x to sum_div
for (int i = 2; i <= x / 2; ++i) {
if (x % i == 0) {
sum_div += i;
}
}
// If the sum of divisors is equal
// to the given number, return true
if (sum_div == x) {
return 1;
}
// Otherwise, return false
else
return 0;
}
// Function to find the sum of all the
// subsets from an array whose sum is
// a perfect number
static void subsetSum(int[] arr, int n)
{
// Stores the total number of
// subsets, i.e. 2 ^ n
long total = 1 << n;
// Consider all numbers from 0 to 2 ^ n - 1
for (long i = 0; i < total; i++) {
int sum = 0;
// Consider array elements from
// positions of set bits in the
// binary representation of n
for (int j = 0; j < n; j++)
if ((i & (1 << j)) != 0)
sum += arr[j];
// If sum of chosen elements
// is a perfect number
if (isPerfect(sum) != 0) {
Console.Write(sum + " ");
}
}
}
// Driver Code
static public void Main()
{
int[] arr = { 5, 4, 6 };
int N = arr.Length;
subsetSum(arr, N);
}
}
// This code is contributed by splevel62.
JavaScript
<script>
// javascript program for the above approach
// Function to check is a given
// number is a perfect number or not
function isPerfect(x)
{
// Stores sum of divisors
var sum_div = 1;
// Add all divisors of x to sum_div
for (var i = 2; i <= parseInt(x / 2); ++i) {
if (x % i == 0) {
sum_div += i;
}
}
// If the sum of divisors is equal
// to the given number, return true
if (sum_div == x) {
return 1;
}
// Otherwise, return false
else
return 0;
}
// Function to find the sum of all the
// subsets from an array whose sum is
// a perfect number
function subsetSum(arr , n)
{
// Stores the total number of
// subsets, i.e. 2 ^ n
var total = 1 << n;
// Consider all numbers from 0 to 2 ^ n - 1
for (i = 0; i < total; i++) {
var sum = 0;
// Consider array elements from
// positions of set bits in the
// binary representation of n
for (j = 0; j < n; j++)
if ((i & (1 << j)) != 0)
sum += arr[j];
// If sum of chosen elements
// is a perfect number
if (isPerfect(sum) != 0) {
document.write(sum + " ");
}
}
}
// Driver Code
var arr = [ 5, 4, 6 ];
var N = arr.length;
subsetSum(arr, N);
// This code is contributed by 29AjayKumar
</script>
Time Complexity: O((N + M) * 2N), where M is the sum of the elements of the array, arr[]
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read