Given an integer X, the task is to print the series and find the sum of the series 
Examples :
Input: X = 2, N = 5
Output: Sum = 31
1 2 4 8 16
Input: X = 1, N = 10
Output: Sum = 10
1 1 1 1 1 1 1 1 1 1
Approach: The idea is to traverse over the series and compute the sum of the N terms of the series. The Nth term of the series can be computed as:
Nth Term = (N-1)th Term * X
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
double sum( int x, int n)
{
double i, total = 1.0, multi = x;
cout << total << " " ;
for (i = 1; i < n; i++) {
total = total + multi;
cout << multi << " " ;
multi = multi * x;
}
cout << "\n" ;
return total;
}
int main()
{
int x = 2;
int n = 5;
cout << fixed
<< setprecision(2)
<< sum(x, n);
return 0;
}
|
C
#include <math.h>
#include <stdio.h>
double sum( int x, int n)
{
double i, total = 1.0, multi = x;
printf ( "1 " );
for (i = 1; i < n; i++) {
total = total + multi;
printf ( "%.1f " , multi);
multi = multi * x;
}
printf ( "\n" );
return total;
}
int main()
{
int x = 2;
int n = 5;
printf ( "%.2f" , sum(x, n));
return 0;
}
|
Java
class GFG {
static double sum( int x, int n)
{
double i, total = 1.0 , multi = x;
System.out.print( "1 " );
for (i = 1 ; i < n; i++) {
total = total + multi;
System.out.print(multi);
System.out.print( " " );
multi = multi * x;
}
System.out.println();
return total;
}
public static void main(String[] args)
{
int x = 2 ;
int n = 5 ;
System.out.printf(
"%.2f" , sum(x, n));
}
}
|
Python3
def sum (x, n):
total = 1.0
multi = x
print ( 1 , end = " " )
for i in range ( 1 , n):
total = total + multi
print ( '%.1f' % multi, end = " " )
multi = multi * x
print ( '\n' )
return total;
x = 2
n = 5
print ( '%.2f' % sum (x, n))
|
C#
using System;
class GFG{
static double sum( int x, int n)
{
double i, total = 1.0, multi = x;
Console.Write( "1 " );
for (i = 1; i < n; i++)
{
total = total + multi;
Console.Write(multi);
Console.Write( " " );
multi = multi * x;
}
Console.WriteLine();
return total;
}
public static void Main(String[] args)
{
int x = 2;
int n = 5;
Console.Write( "{0:F2}" , sum(x, n));
}
}
|
Javascript
<script>
function sum(x, n)
{
let i, total = 1.0, multi = x;
document.write(total + " " );
for (i = 1; i < n; i++) {
total = total + multi;
document.write(multi + " " );
multi = multi * x;
}
document.write( "<br>" );
return total;
}
let x = 2;
let n = 5;
document.write(sum(x, n).toFixed(2));
</script>
|
Output: 1 2.0 4.0 8.0 16.0
31.00
Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.