The Wayback Machine - https://web.archive.org/web/20240804080110/https://www.geeksforgeeks.org/baum-sweet-sequence/
Open In App

Baum Sweet Sequence

Last Updated : 28 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Baum Sweet Sequence is an infinite binary sequence of 0s and 1s. The nth term of the sequence is 1 if the number n has no odd number of contiguous zeroes in its binary representation, else the nth term is 0.

The first few terms of the sequence are:
b1 = 1 (binary of 1 is 1)
b2 = 0 (binary of 2 is 10)
b3 = 1 (binary of 3 is 11)
b4 = 1 (binary of 4 is 100)
b5 = 0 (binary of 5 is 101)
b6 = 0 (binary of 6 is 110)

Given a natural number n. The task is to find the nth term of the Baum Sweet sequence, i.e, check whether it contains any consecutive block of zeroes of odd length.

Input: n = 8
Output: 0
Explanations:
Binary representation of 8 is 1000. It 
contains odd length block of consecutive 0s. 
Therefore B8 is 0.

Input: n = 5
Output: 0

Input: n = 7
Output: 1

The idea is to run a loop through the binary representation of n and count the length of all the consecutive zero blocks present. If there is at-least one odd length zero block, then the nth term for the given input n is 0 else it is 1. 

CPP




// CPP code to find the nth term of the
// Baum Sweet Sequence
#include <bits/stdc++.h>
using namespace std;
   
int nthBaumSweetSeq(int n)
{
    // bitset stores bitwise representation
    bitset<32> bs(n);
   
    // len stores the number of bits in the
    // binary of n. builtin_clz() function gives
    // number of zeroes present before the
    // leading 1 in binary of n
    int len = 32 - __builtin_clz(n);
   
    int baum = 1; // nth term of baum sequence
    for (int i = 0; i < len;) {
        int j = i + 1;
   
        // enter into a zero block
        if (bs[i] == 0) {
            int cnt = 1;
   
            // loop to run through each zero block
            // in binary representation of n
            for (j = i + 1; j < len; j++) {
   
                // counts consecutive zeroes
                if (bs[j] == 0)                  
                    cnt++;
                else
                    break;
            }
   
            // check if the number of consecutive
            // zeroes is odd
            if (cnt % 2 == 1)
                baum = 0;
        }
        i = j;
    }
   
    return baum;
}
   
// Driver Code
int main()
{
    int n = 8;
    cout << nthBaumSweetSeq(n);
    return 0;
}


Java




// Java code to find the nth term of the
// Baum Sweet Sequence
class GFG {
  static int nthBaumSweetSeq(int n)
  {
 
    // bitset stores bitwise representation
    char[] bs
      = (Integer.toBinaryString(n)).toCharArray();
 
    int baum = 1; // nth term of baum sequence
 
    for (int i = 0; i < bs.length;) {
      int j = i + 1;
 
      // enter into a zero block
      if (bs[i] == '0') {
        int cnt = 1;
 
        // loop to run through each zero block
        // in binary representation of n
        for (j = i + 1; j < bs.length; j++) {
          // counts consecutive zeroes
          if (bs[j] == '0')
            cnt += 1;
          else
            break;
        }
 
        // check if the number of consecutive
        // zeroes is odd
        if (cnt % 2 == 1)
          baum = 0;
      }
 
      i = j;
    }
 
    return baum;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int n = 8;
 
    // Function call
    System.out.println(nthBaumSweetSeq(n));
  }
}
 
// This code is contributed by phasing17


Python3




# Python3 code to find the nth term of the
# Baum Sweet Sequence
def nthBaumSweetSeq(n):
 
    # bitset stores bitwise representation
    bs = list(bin(n)[2::])
 
    baum = 1 # nth term of baum sequence
    for i in range(len(bs)):
        j = i + 1
         
        # enter into a zero block
        if (bs[i] == '0'):
            cnt = 1
   
            # loop to run through each zero block
            # in binary representation of n
            for j in range(i + 1, len(bs)):
   
                # counts consecutive zeroes
                if (bs[j] == 0):                  
                    cnt += 1
                else:
                    break
             
            # check if the number of consecutive
            # zeroes is odd
            if (cnt % 2 == 1):
                baum = 0
         
        i = j
    return baum
   
# Driver Code
n = 8
print(nthBaumSweetSeq(n))
 
# This code is contributed by phasing17


C#




using System;
 
public class GFG {
  static int nthBaumSweetSeq(int n)
  {
    // bitset stores bitwise representation
    char[] bs
      = (Convert.ToString(n, 2)).ToCharArray();
 
    int baum = 1; // nth term of baum sequence
 
    for (int i = 0; i < bs.Length;) {
      int j = i + 1;
 
      // enter into a zero block
      if (bs[i] == '0') {
        int cnt = 1;
 
        // loop to run through each zero block
        // in binary representation of n
        for (j = i + 1; j < bs.Length; j++) {
          // counts consecutive zeroes
          if (bs[j] == '0')
            cnt += 1;
          else
            break;
        }
 
        // check if the number of consecutive
        // zeroes is odd
        if (cnt % 2 == 1)
          baum = 0;
      }
 
      i = j;
    }
 
    return baum;
  }
 
  // Driver Code
  public static void Main()
  {
    int n = 8;
 
    // Function call
    Console.WriteLine(nthBaumSweetSeq(n));
  }
}


Javascript




// JavaScript code to find the nth term of the
// Baum Sweet Sequence
function nthBaumSweetSeq(n)
{
 
    // bitset stores bitwise representation
    let bs = n.toString(2).split("");
 
    let baum = 1; // nth term of baum sequence
     
    for (let i = 0; i < bs.length;)
    {
        let j = i + 1;
         
        // enter into a zero block
        if (bs[i] == '0')
        {
            let cnt = 1;
   
            // loop to run through each zero block
            // in binary representation of n
            for (j = i + 1; j < bs.length; j++)
            {
                // counts consecutive zeroes
                if (bs[j] == '0')
                    cnt += 1;
                else
                    break;
            }
             
            // check if the number of consecutive
            // zeroes is odd
            if (cnt % 2 == 1)
                baum = 0;
        }
         
         
        i = j;
    }
     
    return baum;
}
   
// Driver Code
let n = 8;
console.log(nthBaumSweetSeq(n));
 
// This code is contributed by phasing17


Output:

0


Similar Reads

Minimum cost to buy N kilograms of sweet for M persons
Given an array of n sizes, it includes the cost of sweets in such a way that sweet[i] is the cost of i sweets. The task is to find the minimum cost to spend to buy exactly 'n' kilograms of sweets for the 'm' people. Since sweets are available in packets, you have to buy at most a 'm' packet of sweets for your 'm' relatives. You cannot buy more than
15+ min read
Minimum operations required to transform a sequence of numbers to a sequence where a[i]=a[i+2]
Given a sequence of integers of even length 'n', the task is to find the minimum number of operations required to convert the sequence to follow the rule a[i]=a[i+2] where 'i' is the index. The operation here is to replace any element of the sequence with any element. Examples: Input : n=4 ; Array : 3, 1, 3, 2 Output : 1 If we change the last eleme
11 min read
Convert an unbalanced bracket sequence to a balanced sequence
Given an unbalanced bracket sequence of '(' and ')', convert it into a balanced sequence by adding the minimum number of '(' at the beginning of the string and ')' at the end of the string. Examples: Input: str = ")))()" Output: "((()))()" Input: str = "())())(())())" Output: "(((())())(())())" Method 1: Approach: Initialize an empty stack.Iterate
13 min read
Find original sequence from Array containing the sequence merged many times in order
Given a number N and an array arr[] that consist of merging N length sequence of distinct integers any number of times maintaining the relative order of elements in the initial sequence. The task is to find the initial sequence of length N maintaining the right order. Examples: Input: N = 4, arr[] = {1, 13, 1, 24, 13, 24, 2, 2}Output: 1 13 24 2 Exp
10 min read
Find a valid parenthesis sequence of length K from a given valid parenthesis sequence
Given a string S of valid parentheses sequence of length N and an even integer K, the task is to find the valid parentheses sequence of length K which is also a subsequence of the given string. Note: There can be more than one valid sequence, print any of them. Examples: Input: S = "()()()", K = 4Output: ()()Explanation:The string "()()" is a subse
7 min read
Generate a sequence X from given sequence Y such that Yi = gcd(X1, X2 , ... , Xi)
Given a sequence Y of size N where: Yi = gcd(X1, X2, X3, . . ., Xi ) of some sequence X. The task is to find such a sequence X if any such X is possible. Note: If X exists there can be multiple value possible for X. Generating any one is sufficient. Examples: Input: N = 2, Y = [4, 2]Output: [4, 2]Explanation: Y0 = gcd(X0) = X0 = 4. And gcd(4, 2) =
7 min read
k-th missing element in increasing sequence which is not present in a given sequence
Given two sequences, one is increasing sequence a[] and another a normal sequence b[], find the K-th missing element in the increasing sequence which is not present in the given sequence. If no k-th missing element is there output -1 Examples: Input: a[] = {0, 2, 4, 6, 8, 10, 12, 14, 15}; b[] = {4, 10, 6, 8, 12}; k = 3 Output: 14 Explanation : The
6 min read
Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array
Given an array of 0s and 1s, find the position of 0 to be replaced with 1 to get longest continuous sequence of 1s. Expected time complexity is O(n) and auxiliary space is O(1). Example: Input: arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1} Output: Index 9 Assuming array index starts from 0, replacing 0 with 1 at index 9 causes the maximum continu
9 min read
Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array | Set-2
Given an array of 0s and 1s, find the position of 0 to be replaced with 1 to get longest continuous sequence of 1s. Expected time complexity is O(n) and auxiliary space is O(1). Examples: Input : arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1} Output : Index 9 Assuming array index starts from 0, replacing 0 with 1 at index 9 causes the maximum cont
15+ min read
Juggler Sequence | Set 2 (Using Recursion)
Juggler Sequence is a series of integer number in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation : [Tex]a_{k+1}=\begin{Bmatrix} \lfloor a_{k}^{1/2} \rfloor &amp; for \quad even \quad a_k\\ \lfloor a_{k}^{3/2} \rfloor &amp; for \q
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg