找到系列 5、10、20、40 的第 N 项…
给定一个正整数N ,任务是找到序列的第 N项
5, 10, 20, 40….till N terms
例子:
Input: N = 5
Output: 80
Input: N = 3
Output: 20
方法:
1st term = 5 * (2 ^ (1 – 1)) = 5
2nd term = 5 * (2 ^ (2 – 1)) = 10
3rd term = 5 * (2 ^ (3 – 1)) = 20
4th term = 5 * (2 ^ (4 – 1)) = 40
.
.
Nth term = 5 * (2 ^ (N – 1))
给定系列的第 N 项可以概括为-
TN = (a * (r ^ (N – 1))
可以按照以下步骤推导出公式-
The series 5, 10, 20, 40….till N terms
is in G.P. with
first term a = 5
common ratio r = 2 because each term is double the one before it.
The Nth term of a G.P. is
TN = (a * (r ^ (N – 1))
插图:
Input: N = 5
Output: 80
Explanation:
TN = (a * (r ^ (N – 1))
= (5 * (2 ^ (5 – 1))
= (5 * 16)
= 80
以下是上述方法的实现 -
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to calculate nth term
int nTerm(int a, int r, int n)
{
return a * pow(r, n - 1);
}
// Driver code
int main()
{
// Value of N
int N = 5;
// First term of the series
int a = 5;
// Common ratio
int r = 2;
cout << nTerm(a, r, N);
return 0;
}
C
// C program to implement
// the above approach
#include
#include
// Function to calculate nth term
int nTerm(int a, int r, int n)
{
return a * pow(r, n - 1);
}
// Driver code
int main()
{
// Value of N
int N = 5;
// First term
int a = 5;
// Common ratio
int r = 2;
printf("%d", nTerm(a, r, n));
return 0;
}
Java
// Java program to implement
// the above approach
import java.io.*;
class GFG {
// Driver code
public static void main(String[] args)
{
// Value of N
int N = 5;
// First term
int a = 5;
// Common ratio
int r = 2;
System.out.println(nTerm(a, r, N));
}
// Function to calculate nth term
public static int nTerm(int a, int r, int n)
{
return a * ((int)Math.pow(r, n - 1));
}
}
Python3
# python3 program to implement
# the above approach
# Function to calculate nth term
def nTerm(a, r, n):
return a * pow(r, n - 1)
# Driver code
if __name__ == "__main__":
# Value of N
N = 5
# First term of the series
a = 5
# Common ratio
r = 2
print(nTerm(a, r, N))
# This code is contributed by rakeshsahni
C#
using System;
public class GFG
{
// Function to calculate nth term
public static int nTerm(int a, int r, int n)
{
return a * ((int)Math.Pow(r, n - 1));
}
static public void Main()
{
// Code
// Value of N
int N = 5;
// First term
int a = 5;
// Common ratio
int r = 2;
Console.Write(nTerm(a, r, N));
}
}
// This code is contributed by Potta Lokesh
Javascript
80
时间复杂度: O(1)
辅助空间: O(1)