Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Problem: Get the sum of 1 + (2 + 3 * 4) + (5 + 6 * 7 + 8 * 9 * 10) + .... + nth term
- /*
- * while n = 10, sum is 782
- * while n = 6, sum is 26
- * while n = 19, sum is 10123
- * while n = 2, sum is 3
- */
- #include <iostream>
- using namespace std;
- int main() {
- int n; cout << "Input: "; cin >> n; // getting nth term
- int sum = 0, loop = 1 /*for first inner loop*/, num = 1 /*number initializtion*/;
- bool run = true; // to run the outer loop
- while (run) {
- int inner_sum = 0; // for taking the value of each closed bracket
- for (int x = 1; x <= loop; x++) /*inner loop for the sum of bracket*/ {
- int mult = 1;
- for (int y = 1; y <= x; y++) /*inner loop for product*/ {
- mult *= num;
- if (num == n) { // if num crosses n then stop multiplying
- run = false;
- break;
- }
- num++; // number increment by 1
- }
- inner_sum += mult; // sum of each product of a bracket
- if (num == n) // if num crosses n then stop next loop
- break;
- }
- sum += inner_sum; // sum of participated brackets
- loop++; // increment of repeatation of inner loop
- }
- cout << "\nSum: " << sum << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement