Find the sum of the series x(x+y) + x^2(x^2+y^2) +x^3(x^3+y^3)+ … + x^n(x^n+y^n)
Last Updated :
30 Aug, 2022
Given a series where x, y and n take integral values. The task is to Find the sum till nth term of the given series.
Examples:
Input: x = 2, y = 2, n = 2
Output: 40
Input: x = 2, y = 4, n = 2
Output: 92
Approach: Given series is :
.
Thus our problem reduces to finding sum of two GP series.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sum( int x, int y, int n)
{
int sum1 = ( pow (x, 2) * ( pow (x, 2 * n) - 1))
/ ( pow (x, 2) - 1);
int sum2 = (x * y * ( pow (x, n) * pow (y, n) - 1))
/ (x * y - 1);
return sum1 + sum2;
}
int main()
{
int x = 2, y = 2, n = 2;
cout << sum(x, y, n);
return 0;
}
|
Java
public class GFG {
static int sum( int x, int y, int n)
{
int sum1 = ( int ) (( Math.pow(x, 2 ) * (Math.pow(x, 2 * n) - 1 ))
/ (Math.pow(x, 2 ) - 1 ));
int sum2 = ( int ) ((x * y * (Math.pow(x, n) * Math.pow(y, n) - 1 ))
/ (x * y - 1 ));
return sum1 + sum2;
}
public static void main (String args[]){
int x = 2 , y = 2 , n = 2 ;
System.out.println(sum(x, y, n));
}
}
|
Python3
def sum (x,y,n):
sum1 = ((x * * 2 ) * (x * * ( 2 * n) - 1 )) / / (x * * 2 - 1 )
sum2 = (x * y * (x * * n * y * * n - 1 )) / / (x * y - 1 )
return (sum1 + sum2)
if __name__ = = '__main__' :
x = 2
y = 2
n = 2
print ( sum (x, y, n))
|
C#
using System;
class GFG
{
static int sum( int x, int y, int n)
{
int sum1 = ( int ) ((Math.Pow(x, 2) *
(Math.Pow(x, 2 * n) - 1)) /
(Math.Pow(x, 2) - 1));
int sum2 = ( int ) ((x * y * (Math.Pow(x, n) *
Math.Pow(y, n) - 1)) / (x * y - 1));
return sum1 + sum2;
}
public static void Main ()
{
int x = 2, y = 2, n = 2;
Console.Write(sum(x, y, n));
}
}
|
PHP
<?php
function sum( $x , $y , $n )
{
$sum1 = (pow( $x , 2) *
(pow( $x , 2 * $n ) - 1)) /
(pow( $x , 2) - 1);
$sum2 = ( $x * $y * (pow( $x , $n ) *
pow( $y , $n ) - 1)) /
( $x * $y - 1);
return $sum1 + $sum2 ;
}
$x = 2;
$y = 2;
$n = 2;
echo sum( $x , $y , $n );
?>
|
Javascript
<script>
function sum(x, y, n)
{
sum1 = (Math.pow(x, 2) *
(Math.pow(x, 2 * n) - 1)) /
(Math.pow(x, 2) - 1);
sum2 = (x * y * (Math.pow(x, n) *
Math.pow(y, n) - 1)) /
(x * y - 1);
return sum1 + sum2;
}
let x = 2;
let y = 2;
let n = 2;
document.write(sum(x, y, n));
</script>
|
Time Complexity: O(log(n))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...