Search code examples
javarecursionsumsubsetstack-overflow

Find if a given number is a sum of a given set (with repetitons allowed) using recursion (java)


Im trying to find if a given number is a sum of a given set, for example: the number 12 is a sum of the set s{3,2}, because:

3+3+3+3=12
or
2+2+2+2+2+2=12

but 14 is not a sum of s{8,10} because you can't create the number 14 with sums of s. I'm trying to write the code in java using only recursion, and without loops. here is the code:

   public static boolean isSumOf(int[]s,int n)
   {
     return isSumOf(s,n,0,0,0);
   }


   private static boolean isSumOf(int[]s,int n,int i,int sum,int m)
   {
       boolean with=false;
       boolean without=false;

       if(i==s.length)
        return false;

       if(sum==n)   
        return true;

       if(m<=n)
        {
            with=isSumOf(s,n,i,sum+s[i]*m,m++);
            without=isSumOf(s,n,i,sum,m++);            
        }
       else
        {
            i=i++;
            m=0;
            isSumOf(s,n,i,sum,m);
        }

       return (with||without); 

   }

The code is compiled ok, but I get a stackOverFlowError when i run a test on it. here is the code for the test:

  public static void main(String[]args)
  {  
      int[]a={18,10,6};
      int x=18+10+6;
      System.out.println(Ex14.isSumOf(a,x));
  }

please help!!!


Solution

  • this looks bad:

    with=isSumOf(s,n,i,sum+s[i]*m,m++);
    without=isSumOf(s,n,i,sum,m++);
    

    use

    with=isSumOf(s,n,i,sum+s[i]*m,++m);
    without=isSumOf(s,n,i,sum,++m);
    

    if you want to have m one higher in the called method.

    Other than that, I have no clue what the code does due to poor variable naming.

    Also this line:

    i=i++;
    

    has no effect, replace it with one of the following if you want to increment i:

    i++;
    i += 1;
    i = i + 1;
    i = ++i;
    

    And if you don't use the result of the call

    isSumOf(s,n,i,sum,m); 
    

    there is no point in calling it.