cppAcademy
FROM LEARNING TO COMPETING

Real problems.
Your next challenge.

Explore the Group C Olympiad archive.
Choose a topic. Find a challenge. Build your solution.

213 tasks across the Municipal, Regional, and National rounds (2009–2026), plus 4 previously featured problems. 146 tasks have independently written English summaries, analyses, and C++17 solutions; the remaining entries link to Arena. Topic tags are from Arena or our reviewed explanations. Difficulty labels are learning estimates, not official ratings.
GROUP C2013 · MediumRecurrences

Recovering a Fibonacci-type sequence

National Olympiad — Municipal round

Submission name: fibseq.cpp

Problem summary

A sequence obeys a[i]=a[i−1]+a[i−2] for i≥3. Given n, a[n], and a[n+1], recover a[1] and a[2].

Input

n a[n] a[n+1].

Output

a[1] a[2], separated by a space.

Constraints

1 ≤ n ≤ 30; the statement bounds sequence elements above by 2·10^9.

Worked example

An independently prepared example for this explanation.

Input

4 8 13

Output

2 3

Solution analysis

  1. Reverse the recurrence: a[i−1]=a[i+1]−a[i].
  2. Replace the known adjacent pair with the preceding adjacent pair n−1 times.

Why it works

Each reverse step is the unique pair consistent with the recurrence. After n−1 steps its indices are 1 and 2.

Complexity: O(n) time and O(1) space.

Watch out. n=1 needs no updates. Do not assume the sequence starts with 1,1.

Commented C++17 solution

An independently written complete program with standard headers.

// Key idea: Each reverse step is the unique pair consistent with the recurrence. After n−1 steps its
// indices are 1 and 2.
#include<iostream>
#include<algorithm>
#include<utility>
#include<iterator>
using namespace std;
int main(){
    int n;
    long long a,b;
    cin>>n>>a>>b;
    while(--n){
        long long prev=b-a;
        b=a;
        a=prev;
    }
    cout<<a<<' '<<b<<'\n';
}

Source: Arena Olimpiici ↗