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 D2009 · MediumDecimal convolution

Square of a Million-Digit Repunit

National Olympiad — National round (2009 season)

Submission name: ones.cpp

Problem summary

Print the exact square of the integer consisting of n ones.

Input

One integer n.

Output

The complete decimal square.

Constraints

1 ≤ n ≤1000000.

Worked example

Input and output for the worked example discussed below.

Input

9

Output

12345678987654321

Solution analysis

  1. Before carrying, product position k receives one contribution for every digit-position pair i+j=k. The coefficient counts form1,2,…,n−1,n,n−1,…,2,1.
  2. Generate coefficients from the units upward. Add incoming carry, emit the remainder modulo10, and forward the quotient. This remains valid even when a coefficient exceeds9.
  3. For n=9 no carry is needed and the familiar12345678987654321 appears. For n≥10 the coefficients are counts rather than digits, so carry propagation is essential. Reverse the emitted digits before printing.

Why it works

The triangular coefficients count every term of the product’s digit convolution. Standard carry propagation preserves its represented value while producing valid decimal digits. Reversal therefore yields the exact square.

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

Watch out. Do not print the triangle literally for n≥10 or attempt quadratic big-integer multiplication for a million digits.

Commented C++17 solution

An independently written complete program with standard headers.

#include<algorithm>
#include<iostream>
#include<string>
using namespace std;
int main(){
    int n;
    cin>>n;
    string reversed;
    reversed.reserve(2*n);
    int carry=0;
    for(int place=0;place<2*n-1;place++){
        // Count digit pairs contributing to this decimal position.
        int coefficient=min(place+1,2*n-1-place);
        int value=coefficient+carry;
        reversed+=char('0'+value%10);
        carry=value/10;
    }
    while(carry>0){
        reversed+=char('0'+carry%10);
        carry/=10;
    }
    reverse(reversed.begin(),reversed.end());
    cout<<reversed<<'\n';
}

Source: Arena Olimpiici ↗