Write a program using a recursive call to get a natural number n and express it as a sum of natural numbers less than n

Asked 2 years ago, Updated 2 years ago, 34 views

There's a question, "How to take a natural number n and express it as a sum of natural numbers less than n. Write a program that outputs an index using a recursive call."Please give me a clear answer in languageㅠ<

ex)n=4

1+1+1+1

1+1+2

1+1+2

1+2+1

2+1+1

2+2

3+1

1+3

Therefore, please tell me the c language code that says '7 types' in the outputㅜㅜ Please I beg you. Programmers!

c

2022-09-22 20:05

1 Answers

#include <stdio.h>

void f(int* a, int s, int n, int idx){
    int i;
    if(s==0){
        for(i=0; i<idx-1; i++)
            printf("%d+", a[i]);
        printf("%d\n", a[i]);
        return;
    }
    for(int i=1; i<n; i++)
        if(s-i>=0){
            a[idx]=i;
            f(a, s-i, n, idx+1);
        }
}

int main(){
    int n, *a;
    scanf("%d", &n);
    a[0]=0;
    f(a, n, n, 0);
}

Recursive call has been enabled.

I don't need to sort it like the example above, right?


2022-09-22 20:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.