📜  标尺函数系列的第N个术语

📅  最后修改于: 2021-05-25 07:19:42             🧑  作者: Mango

给定正整数N ,任务是找到标尺函数系列的N项。

例子:

天真的方法:解决给定问题的最简单方法是生成序列,直到第N,然后打印第N项。

时间复杂度: O(N)
辅助空间: O(N)

高效方法:还可以根据以下观察结果对上述方法进行优化,即观察到标尺函数系列中的N元素等于(N ^(N – 1))中的设置位数,如下所示:

  • 0和1 = 1的按位XOR设置位的数目
  • 1和2的按位XOR设置位的位数= 2
  • 2和3的按位XOR设置位的位数
  • 3和4的按位XOR设置位的位数= 3
  • 4和5的按位XOR设置位的位数= 1
  • 5和6的按位XOR设置位的位数= 2
  • 6和7的按位XOR设置位的位数= 1
  • 7和8的按位XOR设置位的位数= 4
  • 等等…

因此,根据上述观察,标尺函数系列的N项由N(N – 1)的按位XOR给出。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count the number
// of set bits in the number N
int setBits(long n)
{
    // Store the number of setbits
    int count = 0;
 
    while (n > 0) {
 
        // Upate the value of n
        n = n & (n - 1);
 
        // Update the count
        count++;
    }
 
    // Return the total count
    return count;
}
 
// Function to find the Nth term of
// the Ruler Function Series
void findNthTerm(int N)
{
    // Store the result
    int x = setBits(N ^ (N - 1));
 
    // Print the result
    cout << x;
}
 
// Driver Code
int main()
{
    int N = 8;
    findNthTerm(N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to count the number
// of set bits in the number N
static int setBits(long n)
{
     
    // Store the number of setbits
    int count = 0;
 
    while (n > 0)
    {
         
        // Upate the value of n
        n = n & (n - 1);
 
        // Update the count
        count++;
    }
 
    // Return the total count
    return count;
}
 
// Function to find the Nth term of
// the Ruler Function Series
static void findNthTerm(int N)
{
     
    // Store the result
    int x = setBits(N ^ (N - 1));
 
    // Print the result
    System.out.println(x);
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 8;
     
    findNthTerm(N);
}
}
 
// This code is contributed by Kingash


Python3
# Python3 program for the above approach
 
# Function to count the number
# of set bits in the number N
def setBits(n):
     
    # Store the number of setbits
    count = 0
 
    while (n > 0):
         
        # Upate the value of n
        n = n & (n - 1)
 
        # Update the count
        count += 1
         
    # Return the total count
    return count
 
# Function to find the Nth term of
# the Ruler Function Series
def findNthTerm(N):
     
    # Store the result
    x = setBits(N ^ (N - 1))
 
    # Print the result
    print(x)
 
# Driver Code
N = 8
 
findNthTerm(N)
 
# This code is contributed by Ankita saini


Javascript


输出:
4

时间复杂度: O(log N)
辅助空间: O(1)