本文主要是介绍C/C++,数字序列——查找第n个鲍姆甜序列(Baum Sweet Sequence)的计算方法与源程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1 文本格式
// 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;
}
2 代码格式
// 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 representationbitset<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 nint len = 32 - __builtin_clz(n);int baum = 1; // nth term of baum sequencefor (int i = 0; i < len;) {int j = i + 1;// enter into a zero blockif (bs[i] == 0) {int cnt = 1;// loop to run through each zero block// in binary representation of nfor (j = i + 1; j < len; j++) {// counts consecutive zeroes if (bs[j] == 0)cnt++;elsebreak;}// check if the number of consecutive// zeroes is oddif (cnt % 2 == 1)baum = 0;}i = j;}return baum;
}// Driver Code
int main()
{int n = 8;cout << nthBaumSweetSeq(n);return 0;
}
这篇关于C/C++,数字序列——查找第n个鲍姆甜序列(Baum Sweet Sequence)的计算方法与源程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!