how to describe this series in code?
i would like to find a formula describing this series. i need to set a boolean depending on a positive integer. i开发者_开发百科t's pretty simple but i am stuck and feel a bit stupid.
0 false
1 true
2 true
3 false
4 false
5 true
6 true
7 false
8 false
9 true
10 true
11 false
12 false
...
so the flag changes at every odd number
Well, for the flag changing at every odd number, it looks like your boolean should be true if and only if (n+3)%4 <= 1
, where %
is the modulo operator:
n (n+3)%4 Boolean
-- ------- -------
0 3 false
1 0 true
2 1 true
3 2 false
4 3 false
5 0 true
6 1 true
7 2 false
8 3 false
9 0 true
10 1 true
11 2 false
12 3 false
:: : : :
I've deliberately added three instead of subtracting one, since some languages have different ideas of what the modulo operator should do for negative numbers. And keep in mind that this is language-agnostic. If you're specifically looking for a C or C-like language solution, see the excellent answer here from Christoffer Hammarström ((n + 1) & 2
just in case it ever disappears) - this is far more succinct in those particular languages.
In C and other languages where non-zero is true: (n + 1) & 2
, and in other languages: (n + 1) & 2 != 0
.
You can first divide the int value by 2 and then check if it is even or odd.
boolean flag = ((i+1)/2)%2!=0;
Maybe there is an off-by-one error, so check this.
N (N+1)/2 ((N+1)/2)%2 compare != 0
0 0 0 false
1 1 1 true
2 1 1 true
3 2 0 false
4 2 0 false
5 3 1 true
6 3 1 true
7 4 0 false
8 4 0 false
9 5 1 true
...
Flag changes at every odd number, means the last bit is set to 1.
1 => 01, 3 => 11, ... 9 => 1001, 11 => 1011 and so on.. so, u can just check the last bit at each step and whenever it is 1, flip the flag.
精彩评论