简体   繁体   中英

Recursive function in C to find arithmetic combinations for any number N

I am in the process of learning C. My question is the following: Given a series of number

1 *+ 2 *+ 3 *+ 5 .... *+ 9

or

Where a number n can be created by any combination any of the digits 1 to 9 via either adding, multiplying, or both, for example:

1 + 2 + 3 + 4 * 5 * 6 * 7 * 8 * 9 = 60486

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

Obviously, there are a collection of numbers which can be represented through various combinations of the above. My recursive function should return how many different unique representations a number N has in the above format.

Thus far, I have been working around the solution like this:

int recCheckSolutions(int n, int idx, int tree[], int cnt, int sum)
{
    if (n == sum)
        return 1;
    if (idx > 9)
        return 0;
    if (sum >= n)
        return 0;
    cnt += recCheckSolutions(n, idx + 1, tree, cnt, sum += idx);
    cnt += recCheckSolutions(n, idx + 1, tree, cnt, sum *= idx);
    return cnt;
}

Function is called as such:

int solutions = recCheckSolutions(n, 0, tree, 0, 0);

where n is the desired number we want to find combinations for sum is the integer variable used to see where we are at in our calculations and tree[] is an implementation of a tree I was using to check which numbers have been calculated (obviously no longer relevant in this implementation, but still could be useful?)

It has some of the correct behavior, I've done a stack trace/debug and it seems to have some of the solution, however, it isn't terminating with the correct result. It's very possible I'm barking up the wrong tree .

Thank you very much for your feedback and help.

You have got the most of the things right except the return conditions:

int recCheckSolutions(int n, int idx, int tree[], int cnt, int sum)
{
    if (idx == 9)
        return 1;
    cnt += recCheckSolutions(n, idx + 1, tree, cnt, sum += idx);
    cnt += recCheckSolutions(n, idx + 1, tree, cnt, sum *= idx);
    return cnt;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM