Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Programming for Sum of sequence 2, 22, 222, .........
Given is a sequence: 2, 22, 222, 2222… and we need to find the sum of this sequence. We need to derive a mathematical formula to calculate the sum efficiently.
Syntax
sum = 2 * (pow(10, n) - 1 - (9 * n)) / 81;
Mathematical Derivation
The formula derivation follows these steps −
sum = [2 + 22 + 222 + 2222 + ...] sum = 2 * [1 + 11 + 111 + 1111 + ...] sum = 2/9 * [9 + 99 + 999 + 9999 + ...] sum = 2/9 * [(10-1) + (100-1) + (1000-1) + (10000-1) + ...] sum = 2/9 * [10 + 10² + 10³ + 10? + ... - n] sum = 2/9 * [(10^(n+1) - 10)/9 - n] sum = 2 * (10^(n+1) - 10 - 9n) / 81
Example
Here's a complete program to calculate the sum of the sequence for the first n terms −
#include <stdio.h>
#include <math.h>
int main() {
int n = 3;
float sum = 2 * (pow(10, n + 1) - 10 - (9 * n)) / 81;
printf("Sum of first %d terms: %.0f<br>", n, sum);
// Verify by calculating manually
printf("Manual verification: 2 + 22 + 222 = %d<br>", 2 + 22 + 222);
return 0;
}
Sum of first 3 terms: 246 Manual verification: 2 + 22 + 222 = 246
Example with User Input
Here's an interactive version that accepts user input −
#include <stdio.h>
#include <math.h>
int main() {
int n = 5;
float sum = 2 * (pow(10, n + 1) - 10 - (9 * n)) / 81;
printf("Sequence: ");
for(int i = 1; i <= n; i++) {
int term = 2 * (pow(10, i) - 1) / 9;
printf("%d", term);
if(i < n) printf(" + ");
}
printf("<br>");
printf("Sum of first %d terms: %.0f<br>", n, sum);
return 0;
}
Sequence: 2 + 22 + 222 + 2222 + 22222 Sum of first 5 terms: 24690
Key Points
- The formula uses geometric series properties to derive an efficient O(1) solution.
- Each term in the sequence follows the pattern:
2 * (10^i - 1) / 9for the i-th term. - The
pow()function frommath.his used for exponentiation.
Conclusion
The mathematical formula 2 * (10^(n+1) - 10 - 9n) / 81 provides an efficient way to calculate the sum of the sequence 2, 22, 222, ... without iterating through each term individually.
Advertisements
