3

I want to store the values produced by a recursive function in a string, but I am not sure how to keep after each iteration of the loop. Im not necessarily looking for you to solve it particular to the attached code, but I figured it would give it some context. Simply commenting resources where I can learn this is, of course, welcome. Thanks

int HailstoneNumbers(int N)
{
    vector <char> sequence;
    static int c;

    cout << N << " ";

    if (N == 1 && c == 0) {

        // N is initially 1.
        return c;
    }
    else if (N == 1 && c != 0) {

        // N is reduced to 1.
        c++;
        return c;
    }
    else if (N % 2 == 0) {

        // If N is Even.
        c++;
        HailstoneNumbers(N / 2);
    }
    else if (N % 2 != 0) {

        // N is Odd.
        c++;
        HailstoneNumbers(3 * N + 1);
    }
}
3
  • Hint: You don't want the sequence to be automatically destructed every time this function returns. Commented Jan 15, 2020 at 22:58
  • 1
    Huh. I've never heard the Collatz Conjecture sequence called "Hailstone" before. I'd advise looking up C++ collatz examples. In 99% of cases, if you have a static variable in your recursion, it means you're trying to force the recursion the wrong way. Commented Jan 15, 2020 at 22:58
  • first it seems your recursive calls need to be return HailstoneNumbers... second pass the vector by reference Commented Jan 15, 2020 at 23:01

1 Answer 1

2

If you want to store N values, you can store them in a vector as follows

int HailstoneNumbers(int N, vector<int>& sequence)
{
    int c;

    sequence.push_back(N);

    if (N == 1 && c == 0) {

        // N is initially 1.
        return c;
    }
    else if (N == 1 && c != 0) {

        // N is reduced to 1.
        c++;
        return c;
    }
    else if (N % 2 == 0) {

        // If N is Even.
        c++;
        HailstoneNumbers(N / 2, sequence);
    }
    else if (N % 2 != 0) {

        // N is Odd.
        c++;
        HailstoneNumbers(3 * N + 1, sequence);
    }
}

declare a vector before calling your function as vector<int> sequence; then call your function using your N and this vector

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.