title: Trying to find the number of x's that satisfies n + x = n ^ x fails with timeout
body: <p>I'm trying to solve the following problem from the section <em>Bit Manipulation</em> at the <a href="https://www.hackerrank.com/challenges/sum-vs-xor" rel="noreferrer">Hacker Rank site</a> using new features of Java 8 such as <code>Stream</code>s.</p>
  <p><strong>The problem description:</strong></p>
  <blockquote>
  <p>Given an integer, n, find each x such that:</p>
  <ul>
  <li>0 &lt;= x &lt;= n</li>
  <li>n + x = n ^ x</li>
  </ul>
  <p>where ^ denotes the bitwise XOR operator. Then print an integer denoting the total number of x's satisfying the criteria above.</p>
  <p><strong>Constraints</strong></p>
  <ul>
  <li>0 &lt;= n &lt;= 10<sup>15</sup></li>
  </ul>
  <p><strong>Sample Input:</strong> 5</p>
  <p><strong>Sample Output:</strong> 2</p>
  <p><strong>Explanation:</strong></p>
  <p>For <em>n = 5</em>, the <em>x</em> values <em>0</em> and <em>2</em> satisfy the conditions:</p>
  <ul>
  <li>5 + 0 = 5 ^ 0 = 5</li>
  <li>5 + 2 = 5 ^ 2 = 7</li>
  </ul>
  <p>Thus, we print <em>2</em> as our answer.</p>
  <p><strong>Sample Input:</strong> 10</p>
  <p><strong>Sample Output:</strong> 4</p>
  <p><strong>Explanation:</strong>
  For <em>n = 10</em>, the <em>x</em> values <em>0</em>, <em>1</em>, <em>4</em>, and <em>5</em> satisfy the conditions:</p>
  <ul>
  <li>10 + 0 = 10 ^ 0 = 10</li>
  <li>10 + 1 = 10 ^ 1 = 11</li>
  <li>10 + 4 = 10 ^ 4 = 14</li>
  <li>10 + 5 = 10 ^ 5 = 15</li>
  </ul>
  <p>Thus, we print <em>4</em> as our answer.</p>
  </blockquote>
  <p><strong>My code is as follows:</strong></p>
  <pre><code>public class SumVsXor 
  {
      public static void main(String[] args) 
      {
          Scanner in = new Scanner(System.in);
          long n = in.nextLong();
          long count = LongStream.rangeClosed(0, n)
                                 .filter(k -&gt; k + n == (k ^ n))
                                 .count();
          System.out.println(count);  
      }
  }
  </code></pre>
  <p>The problem is this code doesn't pass all the test cases.</p>
  <p>It works for small values of <code>n</code>, but for large values such as <code>1000000000000000</code> it fails due to timeout.</p>
  <p>I wonder whether <code>LongStream</code> can't handle <code>Stream</code>s with that many elements.</p>