Answer the question
In order to leave comments, you need to log in
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);
}
int main() {
int n;
cin >> n;
int result = n_fibonacci_num(n);
cout << result;
return 0;
}
cin >> n;
to accept a parameter cout << result;
to send a response. Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question