找到系列 2、2、4、4、6、8、8 中缺失的第 N 项。
给定一个数N,找出序列2、2、4、4、6、8、8……中的第 N 项
例子:
Input: N = 1
Output: 2
Input: N = 2
Output: 2
Input: N = 5
Output: 6
方法:仔细观察给定的系列,可以看出它由两个不同的系列组成,在不同的位置梳理在一起。
Original Series: 2, 2, 4, 4, 6, 8, 8, …
—————————————————————–
Considering only even places:
=> 2, 2, 4, 4, 6, 8, 8, …
=> 2, _, 4, _, 6, _, 8, … (considering 0-based indexing)
=> 2, 4, 6, 8, … (an AP series)
As it can be seen, the numbers at even places forms an Arithmetic Progression in itself.
—————————————————————–
Similarly, Considering only odd places:
=> 2, 2, 4, 4, 6, 8, 8, …
=> _, 2, _, 4, _, 8, … (considering 0-based indexing)
=> 2, 4, 8, … (a GP series)
As it can be seen, the numbers at odd places forms a Geometric Progression in itself.
因此,可以说给定序列是 2 个不同序列的混合,其中 AP 的所有项都位于偶数位置,而 GP 的所有项都位于奇数位置。
因此,在上述观察的基础上,按照以下步骤找到给定序列的第 N 个缺失项:
- 如果 n 是奇数:
- 所需的项是 AP [2, 4, 6, 8 …] 的 ( n +1)/2 项。
- AP的第n项可以计算为a + (n – 1)d。
- 如果 n 是偶数:
- 所需项是 GP [2, 4, 8 ...] 的第 n /2 项。
- GP的第n项可以计算为a*r n-1
下面是上述方法的实现:
C++
// C++ code to find the n-th term
// of series 2, 2, 4, 4, 6, 8, 8...
#include
#include
using namespace std;
// Driver code
int main()
{
int n = 15;
int term;
// If n is even
if (n % 2 == 0) {
term = n / 2;
// a(first term) = 2
// r(common ratio) = 2
cout << 2 * pow(2, term - 1);
}
// If n is odd
else {
term = (n + 1) / 2;
// a(first term) = 2
// d(common ratio) = 2
cout << 2 + (term - 1) * 2;
}
}
Java
// Java code for the above approach
import java.io.*;
class GFG {
public static void main(String[] args)
{
int n = 15;
int term;
// If n is even
if (n % 2 == 0) {
term = n / 2;
// a(first term) = 2
// r(common ratio) = 2
System.out.println(2 * Math.pow(2, term - 1));
}
// If n is odd
else {
term = (n + 1) / 2;
// a(first term) = 2
// d(common ratio) = 2
System.out.println(2 + (term - 1) * 2);
}
}
}
// This code is contributed by Potta Lokesh
Python
# Python code to find the n-th term
# of series 2, 2, 4, 4, 6, 8, 8...
# Driver code
n = 15;
term = 0;
# If n is even
if (n % 2 == 0):
term = n / 2;
# a(first term) = 2
# r(common ratio) = 2
print(2 * int(pow(2, term - 1)));
# If n is odd
else:
term = (n + 1) / 2;
# a(first term) = 2
# d(common ratio) = 2
print(2 + int((term - 1) * 2));
# This code is contributed by Samim Hossain Mondal.
C#
// C# code for the above approach
using System;
class GFG {
public static void Main(string[] args)
{
int n = 15;
int term;
// If n is even
if (n % 2 == 0) {
term = n / 2;
// a(first term) = 2
// r(common ratio) = 2
Console.WriteLine(2 * Math.Pow(2, term - 1));
}
// If n is odd
else {
term = (n + 1) / 2;
// a(first term) = 2
// d(common ratio) = 2
Console.WriteLine(2 + (term - 1) * 2);
}
}
}
// This code is contributed by ukasp.
Javascript
16
时间复杂度: O(1)
辅助空间: O(1)