鮑姆甜美序列在 C 程式中?
這裡我們將瞭解鮑姆甜美序列。此序列是一個二進位制序列。如果數字 n 有奇數個連續的 0,則第 n 位將為 0,否則第 n 位將為 1。
我們有一個自然數字 n。我們的任務是找出鮑姆甜美序列的第 n 項。因此,我們必須檢查它是否具有任何連續的奇數長度的零塊。
如果這個數字是 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP