Java implementation of integer division

Problems integer division: n a positive integer represented as a series of positive and integer, n = n1 + n2 + ... + nk, where n1> = n2> = ...> = nk> = 1, k> = 1.
As a simple example of
division of 6:
6;
5 + 1;
4 + 1 + 1 + 2, 4;
3 + 3,3 + 1,3 + 2 + 1 + 1;
2 + 2 + 2, 2 + 2 + 1 + 2 + 1 + 1 + 1 + 1;
1 + 1 + 1 + 1 + 1 + 1;

By writing this example is easy to detect recurrence relations
each a semicolon the group largest addend is m, the third row m = 4, all the different classification positive integer n, the maximum plus dividing number m is not larger than the number n1 denoted q (n, m).
We require a few numbers that is divided, i.e. find Q (n-, n-)
Q (6,4) is the following:
4 + 1 + 1 + 2, 4;
3 + 3,3 + 2 + 1, 3 + 1 + 1;
2 + 2 + 2, 2 + 2 + 2 + 1 + 1 + 1 + 1 + 1;
1 + 1 + 1 + 1 + 1 + 1;

Now, about the recursion relations:
(1) when n = 1, or when m = 1, Q (n-, m) = 1
(2) when n <m, it is clear that this is not correct, we set m is the largest addend, m can only be less than equal to n, so this case is equivalent to q (n, n-)
(. 3) when n = m, that is, q (n, n), then if the return q (n, n) then not go recurrence, for example can be appreciated at this time at
q (6,6) is equal to q (6,5) plus the individual figures 6, i.e. in solving division number written : q (6,6) = q ( 6,5) +1
promotion obtained: Q (n-, m) +. 1 = Q (n-,. 1-m)
(. 4) which is used in most cases, n> m, the example is understood that
q (6,4) which:
4 + 1 + 1 + 2, 4;
3 + 3,3 + 1,3 + 2 + 1 + 1;
2 + 2 + 2,2 + 2 + 1 + 1 + 2 + 1 + 1 + 1;
1 + 1 + 1 + 1 + 1 + 1;
can be divided into these two parts, is q (6,3), part of q ( 2,4)
Q (6,3):
. 3 l, 3 + 3,3 + 2 + + +. 1. 1;
2 + 2 + 2 + 2,2 & 1,2 + + +. 1. 1. 1 + + +. 1. 1 ;
. 1. 1 + + +. 1. 1. 1 + +. 1;
Q (2,4):
. 4. 1 + + + 2,4. 1;
obtained recursion formulas : Q (n-, m) = Q (n-,. 1-m) + q (nm, m)
This is not very clear, why not put q (2,4) wrote q (2,2) it? I.e. Q (n-, m) = Q (n-,. 1-m) + Q (nm, nm )
another example: q (6,2) = q ( 6,1) + q (5,2)
if this written q (6,2) = q (6,1 ) + q (5,5), it is clear that the largest addend is 2, indeed appears behind formula q (5,5), this is wrong , and will count a lot more than the number of division

Analysis clearly, the code is very simple, is recursion on the line

public class Main_1 {
    public static void main(String[] args) {
        System.out.println(split(6));
    }
    public static int split(int n) {
        return p(n,n);
    }
    public static int p(int n,int m) {
        if(n==1 || m==1) {
            return 1;
        } else if(n<m) {
            return p(n,n);
        } else if(n==m) {
            return p(n,n-1)+1;
        } else if(n>m) {
            return  p(n,m-1) + p(n-m,m);
        }
        return -1;
    }
}

Guess you like

Origin blog.csdn.net/weixin_42220532/article/details/92786004