查找系列 0、1、1、2、5、29、841 的第 N 项...
给定一个正整数N ,任务是找到系列0、1、1、2、5、29、841中的第N项
例子:
Input: N = 6
Output: 29
Explanation: The 6th term of the given series is 29.
Input: N = 1
Output: 1
Input: N = 8
Output: 750797
方法:给定的问题是一个基于数学的基本问题,其中 A i = A i-1 2 + A i-2 2 。 因此,创建变量a = 0和b = 1 。使用[2, N]范围内的变量i进行迭代,对于每个i ,计算第i项并将a和b的值分别更新为第 i – 1项和i – 2项。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find N-th term
// of the given series
int getNthTerm(int N)
{
if (N < 3)
return N - 1;
// Initialize Variables repre-
// senting 1st and 2nd term
long int a = 0, b = 1;
// Loop to iterate through the
// range [3, N] using variable i
for (int i = 3; i <= N; i++) {
// pow((i - 2)th term, 2) +
// pow((i - 1)th term, 2)
long int c = a * a + b * b;
// Update a and b
a = b;
b = c;
}
// Return Answer
return b;
}
// Driver Code
int main()
{
int N = 8;
cout << getNthTerm(N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to find N-th term
// of the given series
static int getNthTerm(int N)
{
if (N < 3)
return N - 1;
// Initialize Variables repre-
// senting 1st and 2nd term
int a = 0, b = 1;
// Loop to iterate through the
// range [3, N] using variable i
for (int i = 3; i <= N; i++) {
// Math.pow((i - 2)th term, 2) +
// Math.pow((i - 1)th term, 2)
int c = a * a + b * b;
// Update a and b
a = b;
b = c;
}
// Return Answer
return b;
}
// Driver Code
public static void main(String[] args)
{
int N = 8;
System.out.print(getNthTerm(N));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python code for the above approach
# Function to find N-th term
# of the given series
def getNthTerm(N):
if (N < 3):
return N - 1
# Initialize Variables repre-
# senting 1st and 2nd term
a = 0
b = 1
# Loop to iterate through the
# range [3, N] using variable i
for i in range(3, N + 1):
# pow((i - 2)th term, 2) +
# pow((i - 1)th term, 2)
c = a * a + b * b
# Update a and b
a = b
b = c
# Return Answer
return b
# Driver Code
N = 8
print(getNthTerm(N))
# This code is contributed by Saurabh Jaiswal
C#
// C# program for the above approach
using System;
class GFG
{
// Function to find N-th term
// of the given series
static int getNthTerm(int N)
{
if (N < 3)
return N - 1;
// Initialize Variables repre-
// senting 1st and 2nd term
long a = 0, b = 1;
// Loop to iterate through the
// range [3, N] using variable i
for (int i = 3; i <= N; i++) {
// pow((i - 2)th term, 2) +
// pow((i - 1)th term, 2)
long c = a * a + b * b;
// Update a and b
a = b;
b = c;
}
// Return Answer
return (int)b;
}
// Driver Code
public static void Main()
{
int N = 8;
Console.Write(getNthTerm(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
750797
时间复杂度: O(N)
辅助空间: O(1)