令n为数字序列,由递归关系a 1 = 1和n + 1 / a n = 2 n定义。任务是找到给定n的log 2 (a n )的值。
例子:
Input: 5
Output: 10
Explanation:
log2(an) = (n * (n - 1)) / 2
= (5*(5-1))/2
= 10
Input: 100
Output: 4950
,我们将以上所有内容相乘以达到
自从 。然后
。
用n + 1代替n:
所以,
下面是上述方法的实现。
C++
// C++ program to find nth term of
// a given recurrence relation
#include
using namespace std;
// function to return required value
int sum(int n)
{
// Get the answer
int ans = (n * (n - 1)) / 2;
// Return the answer
return ans;
}
// Driver program
int main()
{
// Get the value of n
int n = 5;
// function call to print result
cout << sum(n);
return 0;
}
Java
// Java program to find nth term
// of a given recurrence relation
import java.util.*;
class solution
{
static int sum(int n)
{
// Get the answer
int ans = (n * (n - 1)) / 2;
// Return the answer
return ans;
}
// Driver code
public static void main(String arr[])
{
// Get the value of n
int n = 5;
// function call to print result
System.out.println(sum(n));
}
}
//This code is contributed byte
//Surendra_Gangwar
Python3
# Python3 program to find nth
# term of a given recurrence
# relation
# function to return
# required value
def sum(n):
# Get the answer
ans = (n * (n - 1)) / 2;
# Return the answer
return ans
# Driver Code
# Get the value of n
n = 5
# function call to prresult
print(int(sum(n)))
# This code is contributed by Raj
C#
// C# program to find nth term
// of a given recurrence relation
using System;
class GFG
{
static int sum(int n)
{
// Get the answer
int ans = (n * (n - 1)) / 2;
// Return the answer
return ans;
}
// Driver code
public static void Main()
{
// Get the value of n
int n = 5;
// function call to print result
Console.WriteLine(sum(n));
}
}
// This code is contributed byte
// inder_verma
PHP
Javascript
输出:
10
时间复杂度:O(1)