cppAcademy
FROM LEARNING TO COMPETING

Intermediate.
Put your skills to the test.

Bulgarian Informatics Group D · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group D also includes challenging national-level problems. The six 2017 National tasks shared by Groups C and D use their existing permanent URLs. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP D2011 · MediumDivisors and formulas

First Appearance in a Multiplication Triangle

National Olympiad — National round (2011 season)

Submission name: triangle.cpp

Problem summary

Row r of a triangular arrangement contains j(r−j+1) at column j, for 1≤j≤r. Find the sum of the first row containing a given value a.

Input

One integer a.

Output

The sum of the earliest row containing a.

Constraints

1 < a < 1000000.

Worked example

Input and output for the worked example discussed below.

Input

6

Output

20

Solution analysis

  1. Reading the columns in the diagram gives column j as j,2j,3j,… starting at row j. Therefore cell (r,j) is j(r−j+1). If it equals a, then j and r−j+1 are a factor pair of a.
  2. A factor pair d and a/d places a in row d+a/d−1. Enumerate divisors d≤√a and take the smallest such row. This is much faster than constructing all rows up to a.
  3. The row sum is Σ j(r+1−j) = r(r+1)(r+2)/6. For a=6, factor pairs (1,6) and (2,3) give rows 6 and 4. Row 4 is [4,6,6,4], and its sum is 20.

Why it works

Every occurrence of a corresponds to one positive factor pair, and every factor pair creates an occurrence in its derived row. The minimum over all pairs is therefore the earliest row. Summing the closed cell formula yields the displayed cubic expression.

Complexity: O(√a) time and O(1) auxiliary space.

Watch out. Do not confuse the row with the factor itself. The answer can exceed int even though a is small; promote before multiplying the three row factors.

Commented C++17 solution

An independently written complete program with standard headers.

#include<algorithm>
#include<iostream>
using namespace std;
int main(){
    long long value;
    cin>>value;
    long long row=value;
    // Factor pairs enumerate all possible appearances of the value.
    for(long long divisor=1;divisor*divisor<=value;divisor++){
        if(value%divisor==0){
            row=min(row,divisor+value/divisor-1);
        }
    }
    cout<<row*(row+1)*(row+2)/6<<'\n';
}

Source: Arena Olimpiici ↗