Integer division (recursive)

Integer division refers to writing a positive integer n as the sum of multiple numbers, of which the maximum value does not exceed m, then it belongs to an m division of n.
It is different from the division of numbers, especially the meaning of m:
https://blog.csdn.net/qq_38786209/article/details/80111311

Example: Division of 6:
6;
5+1;
4+2; 4+1+1;
3+3; 3+2+1; 3+1+1+1;
2+2+2; 2+2+ 1+1; 2+1+1+1+1
1+1+1+1+1+1;

According to the relationship between n and m, consider the following situations:

(1) When n=1, no matter what the value of m is (m>0), there is only one division, namely {1};
(2) When m=1, no matter what the value of n is, there is only one division That is, n 1s, {1,1,1,…,1};
(3) When n=m, according to whether n is included in the division, it can be divided into two cases:

  • (a) In the case where n is included in the division, there is only one, namely {n};
  • (b) In the case where n is not included in the division, the largest number in the division must also be smaller than n, that is, all (n-1) divisions of n. So q(n,n) =1 + q(n,n-1);

(4) When n < m, since there is no negative number in the division, it is equivalent to q(n,n);
(5) But when n > m, according to whether the maximum value m is included in the division, it can be divided into two case:

  • (a) The case where m is included in the division, ie {m, {x1,x2,…xi}}, where the sum of {x1,x2,…xi} is nm, so in this case it is q(nm,m)
  • (b) In the case where m is not included in the division, all the values ​​in the division are smaller than m, that is, the (m-1) division of n, the number of which is q(n, m-1);

So q(n, m) = q(nm, m)+q(n,m-1);
To sum up:

q(n, m) = 1; (n=1 or m=1)

q(n,m) = q(n, n); (n < m)

1+ q(n, m-1); (n = m)

q(n-m,m)+q(n,m-1); (n > m)

#include<iostream>  
using namespace std;  
int q(int n,int m)  
{  
    if((n<1)||(m<1))  
        return 0;  
    if((n == 1)||(m == 1))  
        return 1;  
    if(n < m)  
        return q(n,n);  
    if(n == m)  
        return q(n,m-1)+1;  
    return q(n,m-1)+q(n-m,m);  
}  
int main()  
{  
    int n,m;
    while(cin>>n>>m)
    {
        cout<<q(n,m)<<endl;
    }
    return 0;
}  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325699121&siteId=291194637