VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-sequence-2-22-222/

⇱ Sum of the sequence 2, 22, 222, ......... - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of the sequence 2, 22, 222, .........

Last Updated : 12 Dec, 2024

Given an integer n. The task is to find the sum of the following sequence: 2, 22, 222, ......... to n terms. 

Examples :

Input: n = 2
Output: 24
Explanation: For n = 2, the sum of first 2 terms are 2 + 22 = 24

Input: 3
Output: 246
Explanation: For n = 3, the sum of first 3 terms are 2 + 22 + 222 = 246

Using Recursion - O(n) Time and O(n) Space

The idea is to use recursion to compute the sum by breaking the problem into smaller parts. Start with the first term (2) and repeatedly append 2 to generate the next term while reducing the count of terms (n). The base case is when no terms are left (n == 0), returning 0. Each recursive step adds the current term to the result of the smaller problem.


Output
246

Using Iteration - O(n) Time and O(1) Space

The idea starts with initializing term as 0 and iteratively appending 2 to form each term of the sequence (e.g., 2, 22, 222). After generating each term, it is directly added to the cumulative sum. This method ensures step-by-step construction and summation of the sequence up to n terms.


Output
246

Using Mathematical Formula - O(1) Time and O(1) Space

A simple solution is to compute terms individually and add to the result.

Sn = 2 + 22 + 222 + 2222 + ... + 2222...(n 2's)

Taking 2 common

= 2 [1 + 11 + 111 + 1111 +...+ 1111...(n1′s) ]

Multiply and divide by 9

= 2/9 [9 + 99 + 999 + 9999 +...+ 9999...(n9′s) ]

= 2/9 [(10 - 1) + (100 - 1) + (1000 - 1) + ... + (10^n - 1)]

= 2/9 [(10^1 - 1) + (10^2 - 1) + (10^3 - 1) + ... + (10^n - 1)]

= 2/9 [(10 + 10^2 + 10^3 + 10^4 + ... ) - (1 + 1 + 1 + 1 + ... n 1's)]

Clearly above is a geometric series with first term 10 and common ratio 10.

2/9 [{(10 × (10^n - 1) / (10 - 1)} - n]

= 2/9 [ {10 × (10^n - 1) / 9} - n]

= 2/81 [{(10 × (10^n - 1)} - 9n]


Output
246
Comment
Article Tags: