Check if is possible to get given sum from a given set of elements - GeeksforGeeks

16 Jun, 2021
Given array of numbers and a integer x. Find whether it is possible or not to get x by adding elements of given array, we may pick a single element multiple times. For a given array, there can be many sum queries.Examples:  
Input : arr[] = { 2, 3}
         q[]  = {8, 7}
Output : Yes Yes
Explanation : 
2 + 2 + 2 + 2 = 8
2 + 2 + 3 = 7
 
The idea is to first sort the given array and then use the concept similar to Sieve of Eratosthenes. First take a large sized array ( which is maximum size of x). Initially keep zero in all it’s indexes. Make 1 at zero index ( we can get zero whatever the array is) . Now, traverse through the whole array and make all possible values as 1. 
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find if we can get given// sum using elements of given array.#include <bits/stdc++.h>using namespace std; // maximum size of xconst int MAX = 1000; // to check whether x is possible or notint ispossible[MAX]; void check(int arr[], int N){    ispossible[0] = 1;    sort(arr, arr + N);     for (int i = 0; i < N; ++i) {        int val = arr[i];         // if it is already possible        if (ispossible[val])            continue;         // make 1 to all it's next elements        for (int j = 0; j + val < MAX; ++j)            if (ispossible[j])                ispossible[j + val] = 1;    }} // Driver codeint main(){    int arr[] = { 2, 3 };    int N = sizeof(arr) / sizeof(arr[0]);    check(arr, N);    int x = 7;    if (ispossible[x])        cout << x << " is possible.";    else        cout << x << " is not possible.";    return 0;}
// Java program to find if we can get given// sum using elements of given array.import java.util.*; class solution{ // maximum size of xint MAX = 1000; // to check whether x is possible or notstatic int []ispossible = new int[1000];static void check(int[] arr, int N){         ispossible[0] = 1;    Arrays.sort(arr);     for (int i = 0; i < N; ++i) {        int val = arr[i];         // if it is already possible        if (ispossible[val] == 1)            continue;         // make 1 to all it's next elements        for (int j = 0; j + val < 1000; ++j)            if (ispossible[j]== 1)                ispossible[j + val] = 1;    }} // Driver codepublic static void main(String args[]){    int[] arr = { 2, 3 };    int N = arr.length;    check(arr, N);    int x = 7;    if (ispossible[x]== 1)        System.out.println(x+" is possible.");    else        System.out.println(x+" is not possible."); }}// This code is contributed by// Shashank_Sharma
# Python3 program to find if we can get given# sum using elements of the given array.def check(arr, N):     ispossible[0] = 1    arr.sort()     for i in range(0, N):        val = arr[i]         # if it is already possible        if ispossible[val]:            continue         # make 1 to all it's next elements        for j in range(0, MAX - val):            if ispossible[j]:                ispossible[j + val] = 1 # Driver codeif __name__ == "__main__":     arr = [2, 3]    N = len(arr)         # maximum size of x    MAX = 1000         # to check whether x is possible or not    ispossible = [0] * MAX     check(arr, N)    x = 7         if ispossible[x]:        print(x, "is possible.")    else:        print(x, "is not possible.")     # This code is contributed by# Rituraj Jain
// C# program to find if we can get given// sum using elements of given array.using System; class GFG{     // to check whether x is possible or notstatic int []ispossible = new int[1000];static void check(int[] arr, int N){         ispossible[0] = 1;    Array.Sort(arr);     for (int i = 0; i < N; ++i)    {        int val = arr[i];         // if it is already possible        if (ispossible[val] == 1)            continue;         // make 1 to all it's next elements        for (int j = 0; j + val < 1000; ++j)            if (ispossible[j] == 1)                ispossible[j + val] = 1;    }} // Driver codepublic static void Main(){    int[] arr = { 2, 3 };    int N = arr.Length;    check(arr, N);    int x = 7;    if (ispossible[x]== 1)        Console.WriteLine(x + " is possible.");    else        Console.WriteLine(x + " is not possible.");}} // This code is contributed by// Akanksha Rai
<?php// PHP program to find if we can get given// sum using elements of given array. // maximum size of x$MAX = 1000; // to check whether x is possible or not$ispossible[$MAX] = array(); function check($arr, $N){    global $MAX;    $ispossible[0] = 1;    sort($arr, 0);     for ($i = 0; $i < $N; ++$i)    {        $val = $arr[$i];         // if it is already possible        if ($ispossible[$val])            continue;         // make 1 to all it's next elements        for ($j = 0; $j + $val < $MAX; ++$j)            if ($ispossible[$j])                $ispossible[$j + $val] = 1;    }} // Driver code$arr = array( 2, 3 );$N = sizeof($arr);check($arr, $N);$x = 7;if (ispossible[$x])    echo $x . " is possible.";else    echo $x . " is not possible."; // This code is contributed// by Akanksha Rai?>
<script>// Javascript program to find if we can get given// sum using elements of given array. // maximum size of xlet MAX = 1000; // to check whether x is possible or notlet ispossible = new Array(MAX); function check(arr, N){    ispossible[0] = 1;    arr.sort();     for (let i = 0; i < N; ++i)    {        val = arr[i];         // if it is already possible        if (ispossible[val])            continue;         // make 1 to all it's next elements        for (let j = 0; j + val < MAX; ++j)            if (ispossible[j])                ispossible[j + val] = 1;    }} // Driver codelet arr = new Array( 2, 3 );let N = arr.length;check(arr, N);let x = 7;if (ispossible[x])    document.write(x + " is possible.");else    document.write(x + " is not possible."); // This code is contributed// by _sauraahb_jaiswal</script>
Output:  
7 is possible.
 
Shashank_Sharma
rituraj_jain
Akanksha_Rai
_saurabh_jaiswal
sieve
Arrays
Arrays
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Building Heap from Array
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Find duplicates in O(n) time and O(1) extra space | Set 1
Count pairs with given sum
Next Greater Element
Sliding Window Maximum (Maximum of all subarrays of size k)