A
A
Anton Baryshev2021-05-29 12:10:36
Algorithms
Anton Baryshev, 2021-05-29 12:10:36

How should an Olympiad task accept and return data?

Hello. I was sent to a course where they study algorithms and olympiad programming in C ++ (I study C # myself, but I had to study C ++ at least a little). Before that, I did not take part in Olympiad programming and did not work with automatic task checking systems.
After watching the tutorial video, I had to write a program to find the nth Fibonacci number. I have implemented a recursive function in C++:

int n_fibonacci_num(int n) {
    if (n < 2) return n;
    return n_fibonacci_num(n - 1) + n_fibonacci_num(n - 2);
}


Now I use the following main() method code:
int main() {
    int n;
    cin >> n;

    int result = n_fibonacci_num(n);

    cout << result;
    return 0;
}


Everything works correctly on my computer, but when I upload the code to the verification system, I get the following message:
60b1ff4d4e439112915970.png

I have a suspicion that this is due to the input stream from the console.
In my program, I use cin >> n;to accept a parameter
AND cout << result;to send a response.
It seems to me that the automatic system does not know how to work with a console stream. Explain how to work with such automatic systems when solving Olympiad problems. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lynn "Coffee Man", 2021-05-29
@AVollane

Usually in the conditions or rules it is written where the input is taken from and how to return the result.
Most often this is stdin/stdout or (more rarely) some files with standard names like INPUT.TXT / OUTPUT.TXT .
But in your case, your program takes a really long time to execute because you have implemented the most non-optimal algorithm for calculating Fibonacci numbers that you can think of.

A
Anton Baryshev, 2021-05-30
@AVollane

You were absolutely right! My program was really just too long due to the recursive algorithm. I used a different algorithm and it worked. If anyone is interested, here is the function code:

int n_fibonacci_num(int n) {
    if (n <= 2) return 1;
    int x = 1;
    int y = 1;
    int ans = 0;
    for (int i = 2; i < n; i++)
    {
        ans = x + y;
        x = y;
        y = ans;
    }
    return ans;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question