cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2021 · MediumFactorization & simulation

Largest-Prime-Factor Sequence

National Olympiad — National round (2021 season)

Submission name: seq.cpp

Problem summary

A sequence starts at 2. Each next term equals the preceding term plus its largest prime divisor. Find the N-th term.

Input

One integer N.

Output

The N-th sequence term.

Constraints

1 ≤ N ≤ 80,000.

Worked example

An independently prepared example for this explanation.

Input

10

Output

35

Solution analysis

  1. Compute each next term directly. To find the largest prime factor of the current term, trial-divide a temporary copy, removing all copies of each divisor.
  2. When divisor² exceeds the remaining copy, any remainder above 1 is prime and is the largest factor. Otherwise the last divisor removed was the largest. Use 64-bit arithmetic for safe multiplication in the loop condition.
  3. The terms through position ten are 2,4,6,9,12,15,20,25,30,35. For example, 12 has largest prime factor 3, giving 15; 15 has largest prime factor 5, giving 20. Only N−1 updates are needed.

Why it works

Trial division removes factors in increasing order. Once the remaining value has no divisor at most its square root, it is prime, so the helper returns exactly the largest prime divisor. Starting at term 1 and applying the recurrence N−1 times therefore returns term N.

Complexity: O(N√A) time as a conservative bound, where A is the largest generated term, and O(1) space. Removing factors reduces the practical trial range substantially.

Watch out. Do not use the largest proper divisor; it must be prime. Remove repeated factors completely. N = 1 returns 2.

Commented C++17 solution

An independently written complete program with standard headers.

#include <iostream>
using namespace std;
long long largestPrimeFactor(long long value) {
    long long largest = 1;
    for (long long divisor = 2; divisor <= value / divisor; divisor++) {
        while (value % divisor == 0) {
            largest = divisor;
            value /= divisor;
        }
    }
    // Once trial division stops, any leftover factor is prime.
    if (value > 1) {
        largest = value;
    }
    return largest;
}
int main() {
    int n;
    cin >> n;
    long long term = 2;
    for (int index = 1; index < n; index++) {
        term += largestPrimeFactor(term);
    }
    cout << term << '\n';
}

Source: Arena Olimpiici ↗