Equal Sum and XOR - GeeksforGeeks

04 Oct, 2021
Given a positive integer n, find count of positive integers i such that 0 <= i <= n and n+i = n^i 
Examples : 
Input  : n = 7
Output : 1
Explanation:
7^i = 7+i holds only for only for i = 0
7+0 = 7^0 = 7

Input: n = 12
Output: 4
12^i = 12+i hold only for i = 0, 1, 2, 3
for i=0, 12+0 = 12^0 = 12
for i=1, 12+1 = 12^1 = 13
for i=2, 12+2 = 12^2 = 14
for i=3, 12+3 = 12^3 = 15
Method 1 (Simple) : One simple solution is to iterate over all values of i 0<= i <= n and count all satisfying values.  
C++
Java
Python3
C#
PHP
Javascript
/* C++ program to print count of values such   that n+i = n^i */#include <iostream>using namespace std; // function to count number of values less than// equal to n that satisfy the given conditionint countValues (int n){    int countV = 0;     // Traverse all numbers from 0 to n and    // increment result only when given condition    // is satisfied.    for (int i=0; i<=n; i++ )        if ((n+i) == (n^i) )            countV++;     return countV;} // Driver programint main(){    int n = 12;    cout << countValues(n);    return 0;}
/* Java program to print count of values such that n+i = n^i */import java.util.*; class GFG {         // function to count number of values    // less than equal to n that satisfy    // the given condition    public static int countValues (int n)    {        int countV = 0;              // Traverse all numbers from 0 to n        // and increment result only when        // given condition is satisfied.        for (int i = 0; i <= n; i++ )            if ((n + i) == (n ^ i) )                countV++;              return countV;    }         /* Driver program to test above function */    public static void main(String[] args)    {        int n = 12;        System.out.println(countValues(n));             }} // This code is contributed by Arnav Kr. Mandal.
# Python3 program to print count# of values such that n+i = n^i # function to count number# of values less than# equal to n that satisfy# the given conditiondef countValues (n):    countV = 0;     # Traverse all numbers    # from 0 to n and    # increment result only    # when given condition    # is satisfied.    for i in range(n + 1):        if ((n + i) == (n ^ i)):            countV += 1;     return countV; # Driver Coden = 12;print(countValues(n)); # This code is contributed by mits
/* C# program to print count of valuessuch that n+i = n^i */using System; class GFG {         // function to count number of values    // less than equal to n that satisfy    // the given condition    public static int countValues (int n)    {        int countV = 0;             // Traverse all numbers from 0 to n        // and increment result only when        // given condition is satisfied.        for (int i = 0; i <= n; i++ )            if ((n + i) == (n ^ i) )                countV++;             return countV;    }         /* Driver program to test above function */    public static void Main()    {        int n = 12;        Console.WriteLine(countValues(n));             }} // This code is contributed by anuj_67.
<?php// PHP program to print count// of values such that n+i = n^i // function to count number// of values less than// equal to n that satisfy// the given conditionfunction countValues ($n){    $countV = 0;     // Traverse all numbers    // from 0 to n and    // increment result only    // when given condition    // is satisfied.    for ($i = 0; $i <= $n; $i++ )        if (($n + $i) == ($n^$i) )            $countV++;     return $countV;}     // Driver Code    $n = 12;    echo countValues($n); // This code is contributed by m_kit?>
<script> /* JavaScript program to print count of values suchthat n+i = n^i */ // function to count number of values less than// equal to n that satisfy the given conditionfunction countValues (n){    let countV = 0;     // Traverse all numbers from 0 to n and    // increment result only when given condition    // is satisfied.    for (let i=0; i<=n; i++ )        if ((n+i) == (n^i) )            countV++;     return countV;} // Driver program     let n = 12;    document.write(countValues(n)); // This code is contributed by Surbhi Tyagi. </script>
Output: 
4
Time Complexity: O(n)
Space Complexity: O(1)
Method 2 (Efficient) : An efficient solution is as follows
we know that (n+i)=(n^i)+2*(n&i)So n + i = n ^ i implies n & i = 0Hence our problem reduces to finding values of i such that n & i = 0. How to find count of such pairs? We can use the count of unset-bits in the binary representation of n. For n & i to be zero, i must unset all set-bits of n. If the kth bit is set at a particular in n, kth bit in i must be 0 always, else kth bit of i can be 0 or 1Hence, total such combinations are 2^(count of unset bits in n)For example, consider n = 12 (Binary representation : 1 1 0 0). All possible values of i that can unset all bits of n are 0 0 0/1 0/1 where 0/1 implies either 0 or 1. Number of such values of i are 2^2 = 4. 
The following is the program following the above idea.  
C++
Java
C#
Python3
PHP
Javascript
/* c++ program to print count of values such  that n+i = n^i */#include <bits/stdc++.h>using namespace std; // function to count number of values less than// equal to n that satisfy the given conditionint countValues(int n){    // unset_bits keeps track of count of un-set    // bits in binary representation of n    int unset_bits=0;    while (n)    {        if ((n & 1) == 0)            unset_bits++;        n=n>>1;    }     // Return 2 ^ unset_bits    return 1 << unset_bits;} // Driver codeint main(){    int n = 12;    cout << countValues(n);    return 0;}
/* Java program to print count of values  such that n+i = n^i */import java.util.*; class GFG {         // function to count number of values    // less than equal to n that satisfy    // the given condition    public static int countValues(int n)    {        // unset_bits keeps track of count        // of un-set bits in binary        // representation of n        int unset_bits=0;        while (n > 0)        {            if ((n & 1) == 0)                unset_bits++;            n=n>>1;        }              // Return 2 ^ unset_bits        return 1 << unset_bits;    }         /* Driver program to test above    function */    public static void main(String[] args)    {        int n = 12;        System.out.println(countValues(n));               }}   // This code is contributed by Arnav Kr. Mandal.
/* C# program to print count of values  such that n+i = n^i */using System;public class GFG {         // function to count number of values    // less than equal to n that satisfy    // the given condition    public static int countValues(int n)    {               // unset_bits keeps track of count        // of un-set bits in binary        // representation of n        int unset_bits=0;        while (n > 0)        {            if ((n & 1) == 0)                unset_bits++;            n=n>>1;        }              // Return 2 ^ unset_bits        return 1 << unset_bits;    }         /* Driver program to test above    function */    public static void Main(String[] args)    {        int n = 12;        Console.WriteLine(countValues(n));               }} // This code is contributed by umadevi9616
# Python3 program to print count of values such# that n+i = n^i # function to count number of values less than# equal to n that satisfy the given conditiondef countValues(n):         # unset_bits keeps track of count of un-set    # bits in binary representation of n    unset_bits = 0         while(n):        if n & 1 == 0:            unset_bits += 1        n = n >> 1             # Return 2 ^ unset_bits        return 1 << unset_bits # Driver codeif __name__=='__main__':    n = 12    print(countValues(n)) # This code is contributed by rutvik
<?php/* PHP program to print countof values such that n+i = n^i */  // function to count number of// values less than equal to n// that satisfy the given// conditionfunction countValues( $n){         // unset_bits keeps track    // of count of un-set bits    // in binary representation    // of n    $unset_bits = 0;    while ($n)    {        if (($n & 1) == 0)            $unset_bits++;        $n = $n >> 1;    }     // Return 2 ^ unset_bits    return 1 << $unset_bits;} // Driver code     $n = 12;    echo countValues($n); // This code is contributed// by Anuj_67.?>
<script> // Javascript program to print count of values// such that n+i = n^i // Function to count number of values// less than equal to n that satisfy// the given conditionfunction countValues(n){         // unset_bits keeps track of count    // of un-set bits in binary    // representation of n    let unset_bits = 0;         while (n > 0)    {        if ((n & 1) == 0)            unset_bits++;                     n = n >> 1;    }       // Return 2 ^ unset_bits    return 1 << unset_bits;}   // Driver Codelet n = 12; document.write(countValues(n));     // This code is contributed by susmitakundugoaldanga     </script>
Output : 
4
Time Complexity: O(log(n))
Space Complexity: O(1)
YouTubeGeeksforGeeks500K subscribersEqual Sum and XOR | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=zhu605v9KOI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Nikhil Chakravartula. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
jit_t
vt_m
Mithun Kumar
rutvik_56
utkarshpandey1610
surbhityagi15
mohanyash73
susmitakundugoaldanga
umadevi9616
ashutoshsinghgeeksforgeeks
Bitwise-XOR
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Add two numbers without using arithmetic operators
Binary representation of a given number
Program to find whether a given number is power of 2
Find the element that appears once
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
Josephus problem | Set 1 (A O(n) Solution)
Write an Efficient C Program to Reverse Bits of a Number