Bitwise xor Operator Problem

Mar 19, 2011 at 11:31pm
I'm having problems with this short code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>

using namespace std;

int main()
{
    int count = 0, a;
    for (int i = 1; i <= 1073741824; i++)
        if (i^(2*i)^(3*i) == 0)
        {
            a = i^(2*i)^(3*i);
            cout << a;
            cin.get();
            count++;
        }
    cout << count;
    cin.get();
    return 0;
}
0
0
12
0
0
24
28
0
0
0
60
48
48
56
60
...


I don't think you'll require explanation as to what's going wrong. If you do, then please ask.
Mar 19, 2011 at 11:47pm
operator precedence.

== has a higher precedence than ^. So what's actually happening is this:

if( i ^ (2*i) ^ ((3*i) == 0) )

Just another reason to avoid compound statements and to not be stingy with parenthesis.

Solutions:

1
2
3
4
5
6
for(...)
{
    a = i^(2*i)^(3*1);
    if(a == 0)
    {
        ...


or
1
2
3
4
5
for(...)
{
    if( (i^(i*2)^(i*3)) == 0 )
    {
        ...



The first solution here is better anyway because then you don't have to duplicate the algorithm.

Don't try to cram too much on one line. New lines don't cost anything.
Last edited on Mar 19, 2011 at 11:48pm
Mar 19, 2011 at 11:51pm
Hm... I thought it might have something to do with operator precedence. Thank you, it works now.

It seems wierd in my opinion that == takes precedence over ^.
Mar 19, 2011 at 11:52pm
I don't think that the ^ sign is supported.

Edit:
Never mind, I was thinking something else.
Last edited on Mar 19, 2011 at 11:54pm
Mar 19, 2011 at 11:58pm
What are you trying to accomplish?
Mar 19, 2011 at 11:59pm
Disch wrote:
The first solution here is better anyway because then you don't have to duplicate the algorithm.


No, lines 11-13 are just to check my output, so I won't be duplicating anything. The second solution should be better because it doesn't use an unnecessary variable. Thanks again anyways.

@ne555: It's Euler problem 301. I can think of a much faster way to get the answer, but this was very easy and it runs in just under a second.
Last edited on Mar 20, 2011 at 12:04am
Mar 20, 2011 at 12:22am
Without regard to the problem you are trying to solve, if int is 32 bits, the expression (3*i) on line 9 and 11 will overflow for larger values of i. Perhaps you need to use unsigned long. Or perhaps I'm missing something.
Last edited on Mar 20, 2011 at 12:23am
Mar 20, 2011 at 12:31am
The second solution should be better because it doesn't use an unnecessary variable.


You don't have to worry about such trivial things. The compiler will optimize away stuff like that.

Clarity first.
Topic archived. No new replies allowed.