The Wayback Machine - https://web.archive.org/web/20240804081609/https://www.geeksforgeeks.org/find-first-k-characters-in-nth-term-of-the-thue-morse-sequence/
Open In App

Find first K characters in Nth term of the Thue-Morse sequence

Last Updated : 23 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given two integers N and K, the task is to print the first K bits of the Nth term of the Thue-Morse sequence. The Thue-Morse sequence is a binary sequence. It starts with a “0” as its first term. And then after the next term is generated by replacing “0” with “01” and “1” with “10”.

Examples:

Input: N = 3, K = 2
Output: 01
Explanation: The 1st term is “0”.
The 2nd term is obtained by replacing “0” with “01” i.e. 2nd term is “01”.
The 3rd term in the sequence is obtained by replacing “0” with “01” and “1” with “10”.
So the 3rd term becomes “0110”. Hence, the 1st 2 characters of the 3rd term is “01”.

Input: N = 4, K = 7
Output: 0110100

 

Approach: The basic approach to solve this problem is to generate the Nth term of the sequence and print the first K characters of that term. This can be done using the algorithm discussed here.

Time Complexity: O(N * 2N)
Auxiliary Space: O(1) 

Efficient Approach: The above approach can be optimized by observing that the ith term is the concatenation of (i – 1)th term and the inverse of (i – 1)th term where inverse means changing the polarity of all bits in a binary integer. Hence, xth term, Ai[x] = Ai-1[x – 1] if (x < 2i-1), otherwise Ai[x] = !Ai-1[x – 2i-1]. Therefore, using this relation, a recursive function can be created to calculate the value of each bit in the Nth term.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to find the
// value of the kth bit in Nth term
int findDig(int N, long K,  int curr)
{
   
  // Base Case
  if (N == 0) {
    return curr;
  }
 
  // Stores the middle index
  long middle = (long)pow(2, N) / 2;
 
  // If K lies in 1st part
  if (K <= middle) {
 
    // Recursive Call
    return findDig(N - 1, K, curr);
  }
 
  // If K lies in 2nd part
  // having inverted value
  else {
    if (curr == 0) {
      curr = 1;
    }
    else {
      curr = 0;
    }
 
    // Recursive Call
    return findDig(N - 1,
                   K - middle, curr);
  }
}
 
// Function to find first K characters
// in Nth term of Thue-Morse sequence
void firstKTerms(int N, int K)
{
   
  // Loop to iterate all K bits
  for (int i = 1; i <= K; ++i)
  {
 
    // Print value of ith bit
    cout << (findDig(N, i, 0));
  }
}
 
// Driver Code
int main() {
 
  int N = 4;
  int K = 7;
 
  firstKTerms(N, K);
  return 0;
}
 
// This code is contributed by hrithikgarg03188.


Java




// Java Implementation of the above approach
import java.io.*;
import java.util.*;
class GFG {
 
    // Recursive function to find the
    // value of the kth bit in Nth term
    public static int findDig(int N, long K,
                              int curr)
    {
        // Base Case
        if (N == 0) {
            return curr;
        }
 
        // Stores the middle index
        long middle = (long)Math.pow(2, N) / 2;
 
        // If K lies in 1st part
        if (K <= middle) {
 
            // Recursive Call
            return findDig(N - 1, K, curr);
        }
 
        // If K lies in 2nd part
        // having inverted value
        else {
            if (curr == 0) {
                curr = 1;
            }
            else {
                curr = 0;
            }
 
            // Recursive Call
            return findDig(N - 1,
                           K - middle, curr);
        }
    }
 
    // Function to find first K characters
    // in Nth term of Thue-Morse sequence
    public static void firstKTerms(int N, int K)
    {
        // Loop to iterate all K bits
        for (int i = 1; i <= K; ++i) {
 
            // Print value of ith bit
            System.out.print(findDig(N, i, 0));
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int N = 4;
        int K = 7;
 
        firstKTerms(N, K);
    }
}


Python3




# Recursive function to find the
# value of the kth bit in Nth term
def findDig(N, K, curr):
 
    # Base Case
    if (N == 0):
        return curr
 
    # Stores the middle index
    middle = pow(2, N) // 2
 
    # If K lies in 1st part
    if (K <= middle):
 
        # Recursive Call
        return findDig(N - 1, K, curr)
 
    # If K lies in 2nd part
    # having inverted value
    else:
        if (curr == 0):
            curr = 1
 
        else:
            curr = 0
 
        # Recursive Call
        return findDig(N - 1, K - middle, curr)
 
# Function to find first K characters
# in Nth term of Thue-Morse sequence
def firstKTerms(N, K):
 
    # Loop to iterate all K bits
    for i in range(1, K+1):
 
     # Print value of ith bit
        print(findDig(N, i, 0), end="")
 
# Driver Code
if __name__ == "__main__":
 
    N = 4
    K = 7
 
    firstKTerms(N, K)
 
    # This code is contributed by rakeshsahni


C#




// C# Implementation of the above approach
using System;
class GFG
{
 
  // Recursive function to find the
  // value of the kth bit in Nth term
  public static int findDig(int N, long K, int curr)
  {
     
    // Base Case
    if (N == 0)
    {
      return curr;
    }
 
    // Stores the middle index
    long middle = (long)Math.Pow(2, N) / 2;
 
    // If K lies in 1st part
    if (K <= middle)
    {
 
      // Recursive Call
      return findDig(N - 1, K, curr);
    }
 
    // If K lies in 2nd part
    // having inverted value
    else
    {
      if (curr == 0)
      {
        curr = 1;
      }
      else
      {
        curr = 0;
      }
 
      // Recursive Call
      return findDig(N - 1,
                     K - middle, curr);
    }
  }
 
  // Function to find first K characters
  // in Nth term of Thue-Morse sequence
  public static void firstKTerms(int N, int K)
  {
     
    // Loop to iterate all K bits
    for (int i = 1; i <= K; ++i)
    {
 
      // Print value of ith bit
      Console.Write(findDig(N, i, 0));
    }
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 4;
    int K = 7;
 
    firstKTerms(N, K);
  }
}
 
// This code is contributed by saurabh_jaiswal.


Javascript




<script>
       // JavaScript code for the above approach
 
       // Recursive function to find the
       // value of the kth bit in Nth term
       function findDig(N, K, curr)
       {
           // Base Case
           if (N == 0) {
               return curr;
           }
 
           // Stores the middle index
           let middle = Math.floor(Math.pow(2, N) / 2);
 
           // If K lies in 1st part
           if (K <= middle) {
 
               // Recursive Call
               return findDig(N - 1, K, curr);
           }
 
           // If K lies in 2nd part
           // having inverted value
           else {
               if (curr == 0) {
                   curr = 1;
               }
               else {
                   curr = 0;
               }
 
               // Recursive Call
               return findDig(N - 1,
                   K - middle, curr);
           }
       }
 
       // Function to find first K characters
       // in Nth term of Thue-Morse sequence
       function firstKTerms(N, K) {
           // Loop to iterate all K bits
           for (let i = 1; i <= K; ++i) {
 
               // Print value of ith bit
               document.write(findDig(N, i, 0));
           }
       }
 
       // Driver Code
       let N = 4;
       let K = 7;
 
       firstKTerms(N, K);
 
        // This code is contributed by Potta Lokesh
   </script>


 
 

Output

0110100

 

Time Complexity: O(K*log N)
Auxiliary Space: O(1) 

 



Similar Reads

Thue-Morse sequence
Thue–Morse sequence, or Prouhet–Thue–Morse sequence, is an infinite binary sequence of 0s and 1s. The sequence is obtained by starting with 0 and successively appending the Boolean complement of the sequence obtained so far. First few steps : Start with 0 Append complement of 0, we get 01 Append complement of 01, we get 0110 Append complement of 01
6 min read
Nth term where K+1th term is product of Kth term with difference of max and min digit of Kth term
Given two integers N and D, the task is to find the value of F(N) where the value of F(1) is D, where F(K) is given as: [Tex]F(K+1) = F(K) * (Max_{Digit}(F(K)) - Min_{Digit}(F(K)))[/Tex] Examples: Input: N = 3, D = 487 Output: 15584 Explanation: As F(1) = 487, F(2) = 487 * (maxDigit(487) - minDigit(487)) = 487 * 4 = 1948 F(3) = 1948 * (maxDigit(194
6 min read
Nth term of a sequence formed by sum of current term with product of its largest and smallest digit
Given two numbers N and K, where K represents the starting term of the sequence. The task is to find the Nth term of a sequence formed by sum of current term with product of largest and smallest digit of current term, i.e., AN+1 = AN + max(digits of AN) * min(digits of AN) Examples: Input: K = 1, N = 5 Output: 50 Explanation: A1 = 1 A2 = A1 + minDi
6 min read
First term from given Nth term of the equation F(N) = (2 * F(N - 1)) % 10^9 + 7
Given an integer N and an integer FN which denotes the Nth term of the linear equation F(N) = (2 * F(N - 1)) % M, where M is 109 + 7, the task is to find the value of F(1). Examples: Input : N = 2, FN = 6 Output:3 Explanation: If F(1) = 3, F(2) = (2 * F(1)) % M = (2 * 3) % M = 6. For F(1) = 3 the given linear equation satisfies the value of F(2). T
8 min read
Count the occurrence of Nth term in first N terms of Van Eck's sequence
Prerequisite: Van Eck's sequence Given a positive integer N, the task is to count the occurrences of Nth term in the first N terms of Van Eck's sequence. Examples: Input: N = 5 Output: 1 Explanation: First 5 terms of Van Eck's Sequence 0, 0, 1, 0, 2 Occurrence of 5th term i.e 2 = 1 Input: 11 Output: 5 Explanation: First 11 terms of Van Eck's Sequen
15 min read
Find Nth term of the series where each term differs by 6 and 2 alternately
Given a number N, the task is to find the Nth term of the series where each term differs by 6 and 2 alternately.Examples: Input: N = 6 Output: 24 Explanation: The Nth term is 0 + 6 + 2 + 6 + 2 + 6 + 2 = 24Input: N = 3 Output: 14 Explanation: The Nth term is 0 + 6 + 2 + 6 = 14 Naive Approach: The idea is to iterate from 1 with an increment of 6 and
7 min read
Find the Nth term of the series where each term f[i] = f[i - 1] - f[i - 2]
Given three integers X, Y and N, the task is to find the Nth term of the series f[i] = f[i - 1] - f[i - 2], i &gt; 1 where f[0] = X and f[1] = Y.Examples: Input: X = 2, Y = 3, N = 3 Output: -2 The series will be 2 3 1 -2 -3 -1 2 and f[3] = -2Input: X = 3, Y = 7, N = 8 Output: 4 Approach: An important observation here is that there will be atmost 6
10 min read
Nth term of given recurrence relation having each term equal to the product of previous K terms
Given two positive integers N and K and an array F[] consisting of K positive integers. The Nth term of the recurrence relation is given by: FN = FN - 1 * FN - 2 * FN - 3 *.......* FN - K The task is to find the Nth term of the given recurrence relation. As the Nth term can be very large, print the Nth term modulo 109 + 7. Examples: Input: N = 5, K
15+ min read
Find nth term of the Dragon Curve Sequence
Dragon Curve Sequence is an infinite binary sequence of 0's and 1's. The first term of the sequence is 1. From the next term, we alternately insert 1 and 0 between each element of the previous term. To understand better refer the following explanations: 1 (starts with 1) "1" 1 "0" 1 and 0 are inserted alternately to the left and right of the previo
9 min read
Program to find Nth term of the Van Eck's Sequence
Given a positive integer N, the task is to print Nth term of the Van Eck's sequence.In mathematics, Van Eck's sequence is an integer sequence which is defined recursively as follows: Let the first term be 0 i.e a0 = 0.Then for n &gt;= 0, if there exists an m &lt; n such thatam = antake the largest such m and set an+1 = n − m;Otherwise an+1 = 0.Star
9 min read
Practice Tags :
three90RightbarBannerImg