C++ Practice Problem – Calculate s = a + aa + aaa + aaaa + … + a

Time Limit: 2s Memory Limit: 192MB

Problem Description

Calculate s = a + aa + aaa + aaaa + … + a, where a is a single-digit integer.

For example, 2 + 22 + 222 + 2222 + 22222 (in this case, there are 5 numbers being added)

Input Format

Integer a and n (n numbers to be added, 1 <= n, a <= 9)

Output Format

The value of s

Sample Input

2 2

Sample Output

24

Code

#include <iostream>
using namespace std;
int main() {
    int a, n;
    cin >> a >> n;
    int term = 0;
    int sum = 0;
    for (int i = 0; i < n; i++) {
        term = term * 10 + a;
        sum += term;
    }
    cout << sum << endl;
    return 0;
}

Output Result

C++ Practice Problem - Calculate s = a + aa + aaa + aaaa + ... + a

Problem Analysis

The problem requires calculating s = a + aa + aaa + … + aa…a (n times a), where a is an integer from 1 to 9, and n indicates the number of terms to be added.

Methodology

  1. Generate Each Term: Each term can be viewed as the previous term multiplied by 10 plus a.

  2. Accumulate the Sum: Initialize the current term to 0, then loop n times, generating a new term each time and adding it to the total sum.

Code Explanation

  1. Input Handling: Read integers a and n.

  2. Initialization: <span>term</span> represents the current term, initialized to 0; <span>sum</span> represents the total sum, initialized to 0.

  3. Loop to Generate Terms: In each iteration, the current term <span>term</span> is updated to the previous term multiplied by 10 plus a, then added to <span>sum</span>.

  4. Output Result: Print the total sum <span>sum</span>.

Validation Example

  • Input: 2 2

  • Calculation Process:

    • First term: 0*10+2=2, sum=2

    • Second term: 2*10+2=22, sum=2+22=24

  • Output: 24

This method efficiently calculates the result by iteratively generating each term and accumulating the sum.

C++ Practice Problem - Calculate s = a + aa + aaa + aaaa + ... + a

C++ Basic Tutorial Collection

C++ Practice Problem - Calculate s = a + aa + aaa + aaaa + ... + aC++ Basic Materials

1. C++ Output

2. C++ Variables

3. C++ Input

4. C++ Expressions

5. IF Statements

6. IF Applications

7. WHILE Loop Statements

8. FOR Loop Statements

9. Arrays

10. One-Dimensional Arrays

11. Two-Dimensional Arrays

12. C++ Functions

13. C++ File Operations – Writing Files

If you find it interesting, please click on me

C++ Practice Problem - Calculate s = a + aa + aaa + aaaa + ... + aC++ Practice Problem - Calculate s = a + aa + aaa + aaaa + ... + aC++ Practice Problem - Calculate s = a + aa + aaa + aaaa + ... + aC++ Practice Problem - Calculate s = a + aa + aaa + aaaa + ... + a

Leave a Comment