Recursive algorithm for integer division problem-c language, integer division problem (recursive algorithm)

Problem description: Represent a positive integer n as the sum of a series of positive integers, and find out how many division methods there are. For example, the positive integer 6 has the following division methods:

When the maximum addend is 6, there is one division: 6;

When the maximum addend is 5, there is 1 division: 5 + 1;

When the maximum addend is 4, there are 2 divisions: 4 + 2, 4 + 1 + 1;

When the maximum addend is 3, there are 3 divisions: 3 + 3, 3 + 2 + 1, 3 + 1 + 1 + 1;

When the maximum addend is 2, there are 3 divisions: 2 + 2 + 2, 2 + 2 + 1 + 1, 2 + 1 + 1 + 1 + 1;

When the maximum addend is 1, there is one division: 1 + 1 + 1 + 1 + 1 + 1;

Idea: Among all the different divisions of a positive integer n, the number of divisions whose maximum addend n1 is not greater than m is recorded as q(n,m).

1. Because it is a positive integer division, when n < 1 or m < 1, the number of divisions is 0;

2. When n == 1, the number of divisions is only 1, namely {1};

3. When m == 1, the number of divisions is only 1, that is, n 1s are added;

4. When n < m, since negative numbers cannot appear in the division number, q(n,m) == q(n,m), such as q(6,7) == q(6,6)

5. When n == m: if n is included in the largest addend, there is only one case {n}

If n is not included in the largest addend, then q(n,m) = q(n,n-1)

6. When n > m, if m is included in the division number, then q(n,m) = q(nm,m)

If m is not included in the division number, then q(n,m) = q(n,m-1)

In summary:

q(n,m)                                  n,m

1                                    n=1,m=1

q(n,n)                                   n

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

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

The code is as follows: #include

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, n - 1) + 1;

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

}

int main()

{

printf("%d\n", q(6, 6));

return 0;

}

Guess you like

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