ที่นี่เราจะเห็น Baum Sweet Sequence ลำดับนี้เป็นลำดับไบนารีหนึ่งลำดับ หากตัวเลข n มีเลขคี่เป็น 0 ที่ต่อเนื่องกัน ดังนั้นบิตที่ n จะเป็น 0 มิฉะนั้น บิตที่ n จะเป็น 1
เรามีจำนวนธรรมชาติ n งานของเราคือค้นหาเทอมที่ n ของลำดับ Baum Sweet ดังนั้นเราต้องตรวจสอบว่ามีบล็อกศูนย์ที่มีความยาวคี่อยู่หรือไม่
หากตัวเลขคือ 4 เทอมจะเป็น 1 เพราะ 4 คือ 100 ดังนั้นจึงมีเลขศูนย์สองตัว (คู่)
อัลกอริทึม
BaumSweetSeqTerm (G, s) -
begin define bit sequence seq of size n baum := 1 len := number of bits in binary of n for i in range 0 to len, do j := i + 1 count := 1 if seq[i] = 0, then for j in range i + 1 to len, do if seq[j] = 0, then increase count else break end if done if count is odd, then baum := 0 end if end if done return baum end
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int BaumSweetSeqTerm(int n) {
bitset<32> sequence(n); //store bit-wise representation
int len = 32 - __builtin_clz(n);
//builtin_clz() function gives number of zeroes present before the first 1
int baum = 1; // nth term of baum sequence
for (int i = 0; i < len;) {
int j = i + 1;
if (sequence[i] == 0) {
int count = 1;
for (j = i + 1; j < len; j++) {
if (sequence[j] == 0) // counts consecutive zeroes
count++;
else
break;
}
if (count % 2 == 1) //check odd or even
baum = 0;
}
i = j;
}
return baum;
}
int main() {
int n = 4;
cout << BaumSweetSeqTerm(n);
} ผลลัพธ์
1