在這裡我們將看到 Baum Sweet 序列。該序列是一個二進制序列。如果數字n有奇數個連續的0,則第n位將為0,否則第n位將為1。
我們有一個自然數n。我們的任務是找到 Baum Sweet 序列的第 n 項。所以我們必須檢查它是否有奇數長度的連續零塊。
如果數字是 4,則該項將為 1,因為 4 是 100。所以它有兩個(偶數)個0。
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
以上是在C程式中,將Baum Sweet序列翻譯的詳細內容。更多資訊請關注PHP中文網其他相關文章!