Tutorialspoint
Problem
Solution
Submissions

Sum of the Series `1 + x + x^2 + x^3 + ... + x^n`

Certification: Basic Level Accuracy: 60% Submissions: 5 Points: 5

Write a C++ program that calculates the sum of the series `1 + x + x^2 + x^3 + ... + x^n`, where `x` is a real number and `n` is a positive integer provided by the user.

Example 1
  • Input: x = 2, n = 3
  • Output: 15
  • Explanation:
    • Step 1: Calculate each term in the series: 1 + x + x^2 + x^3.
    • Step 2: With x = 2 and n = 3: 1 + 2 + 2^2 + 2^3 = 1 + 2 + 4 + 8 = 15.
    • Step 3: Return 15 as the final sum.
Example 2
  • Input: x = 1.5, n = 4
  • Output: 13.5625
  • Explanation:
    • Step 1: Calculate each term in the series: 1 + x + x^2 + x^3 + x^4.
    • Step 2: With x = 1.5 and n = 4: 1 + 1.5 + 1.5^2 + 1.5^3 + 1.5^4 = 1 + 1.5 + 2.25 + 3.375 + 5.0625 = 13.5625.
    • Step 3: Return 13.5625 as the final sum.
Constraints
  • 1 ≤ n ≤ 10^6
  • -100 ≤ x ≤ 100
  • Time Complexity: O(n)
  • Space Complexity: O(1)
Variables and Data TypesControl StructuresGoldman SachsZomato
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a loop to iterate from 0 to `n`.
  • In each iteration, calculate `x^i` and add it to the sum.
  • Handle edge cases where `x` is 1 separately.

Steps to solve by this approach:

 Step 1: Define a function sum_of_series that takes a double x and an integer n.

 Step 2: Initialize a sum variable to 0.0.
 Step 3: Use a for loop from i=0 to i=n.
 Step 4: For each iteration, add x^i to the sum using pow(x, i).
 Step 5: Return the final sum.

Submitted Code :