Java – divides integers into sums and products

This is what I need to do: write an algorithm to decompose a given integer into sum products, but each subsequent number must be greater than the previous one, that is:

6 = 1+5;
6 = 1+2+3;
6 = 1*2+4;
6 = 2+4;
6 = 2*3;

A basic partition integer algorithm does not work because it returns numbers in a different order

I'm not asking for the final code, I'm just asking for some tips and suggestions, so I can do it myself Thank you in advance!

Solution

public class Perms {
public class Perms {

/**
 * @param args
 */
public static int x;
public static void main(String[] args) {
    // TODO Auto-generated method stub

    x = 6;
    rec(x,new int[1000],new String[1000],0);
}

public static void rec(int n,int all[],String operator[],int size)
{
       if (n==0)
       {
          if (size==1)return;
          System.out.print(x + " =");
          for (int i=0;i<size;i++)
          {
             System.out.print(" " + all[i]);
             if (i!=size-1)
                 System.out.print(" " + operator[i]);
          }
          System.out.println();
          return;
       }
       int i=1;
       if (size>0)
          i = all[size-1]+1;
       for ( ;i<=n;i++)
       {
          operator[size] = "+";
          all[size] = i;
          rec(n-i,all,operator,size+1);
       }

       i=1;
       if (size>0)
          i = all[size-1]+1;
       for (;i<=n;i++)
       {
          float r = n/(float)i;
          if (r == (int)r)
          {
             operator[size] = "*";
             all[size] = i;
             rec(n/i,size+1);
          }
       }
    }
}

Output:

6 = 1 + 2 + 3
6 = 1 + 5
6 = 2 + 4
6 = 1 * 2 + 4
6 = 1 * 6
6 = 1 * 2 * 3
6 = 2 * 3

Note: operations have priority (evaluation operations from right to left)

Example: 20 = 2 * 3 7 = (2 * (3 7)) = 2 * 10 = 20

It's easy to add these parentheses But the output will look ugly Just notice that it's better

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>