text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Zeckendorf 's Theorem (Non | C ++ program for Zeckendorf 's theorem. It finds representation of n as sum of non-neighbouring Fibonacci Numbers. ; Returns the greatest Fibonacci Number smaller than or equal to n . ; Corner cases ; Find the greatest Fibonacci Number smaller than n . ; Prints Fibonacci Representation of n using greedy algorithm ; Find the greates Fibonacci Number smaller than or equal to n ; Print the found fibonacci number ; Reduce n ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nearestSmallerEqFib ( int n ) { if ( n == 0 n == 1 ) return n ; int f1 = 0 , f2 = 1 , f3 = 1 ; while ( f3 <= n ) { f1 = f2 ; f2 = f3 ; f3 = f1 + f2 ; } return f2 ; } void printFibRepresntation ( int n ) { while ( n > 0 ) { int f = nearestSmallerEqFib ( n ) ; cout << f << " β " ; n = n - f ; } } int main ( ) { int n = 30 ; cout << " Non - neighbouring β Fibonacci β Representation β of β " << n << " β is β STRNEWLINE " ; printFibRepresntation ( n ) ; return 0 ; } |
Count number of ways to divide a number in 4 parts | A Dynamic Programming based solution to count number of ways to represent n as sum of four numbers ; " parts " is number of parts left , n is the value left " nextPart " is starting point from where we start trying for next part . ; Base cases ; If this subproblem is already solved ; Count number of ways for remaining number n - i remaining parts " parts - 1" , and for all part varying from ' nextPart ' to ' n ' ; Store computed answer in table and return result ; This function mainly initializes dp table and calls countWaysUtil ( ) ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 5001 ] [ 5001 ] [ 5 ] ; int countWaysUtil ( int n , int parts , int nextPart ) { if ( parts == 0 && n == 0 ) return 1 ; if ( n <= 0 parts <= 0 ) return 0 ; if ( dp [ n ] [ nextPart ] [ parts ] != -1 ) return dp [ n ] [ nextPart ] [ parts ] ; for ( int i = nextPart ; i <= n ; i ++ ) ans += countWaysUtil ( n - i , parts - 1 , i ) ; return ( dp [ n ] [ nextPart ] [ parts ] = ans ) ; } int countWays ( int n ) { memset ( dp , -1 , sizeof ( dp ) ) ; return countWaysUtil ( n , 4 , 1 ) ; } int main ( ) { int n = 8 ; cout << countWays ( n ) << endl ; return 0 ; } |
Segmented Sieve | C ++ program to print print all primes smaller than n using segmented sieve ; This functions finds all primes smaller than ' limit ' using simple sieve of eratosthenes . It also stores found primes in vector prime [ ] ; Create a boolean array " mark [ 0 . . n - 1 ] " and initialize all entries of it as true . A value in mark [ p ] will finally be false if ' p ' is Not a prime , else true . ; If p is not changed , then it is a prime ; Update all multiples of p ; Print all prime numbers and store them in prime ; Prints all prime numbers smaller than ' n ' ; Compute all primes smaller than or equal to square root of n using simple sieve ; Divide the range [ 0. . n - 1 ] in different segments We have chosen segment size as sqrt ( n ) . ; While all segments of range [ 0. . n - 1 ] are not processed , process one segment at a time ; To mark primes in current range . A value in mark [ i ] will finally be false if ' i - low ' is Not a prime , else true . ; Use the found primes by simpleSieve ( ) to find primes in current range ; Find the minimum number in [ low . . high ] that is a multiple of prime [ i ] ( divisible by prime [ i ] ) For example , if low is 31 and prime [ i ] is 3 , we start with 33. ; Mark multiples of prime [ i ] in [ low . . high ] : We are marking j - low for j , i . e . each number in range [ low , high ] is mapped to [ 0 , high - low ] so if range is [ 50 , 100 ] marking 50 corresponds to marking 0 , marking 51 corresponds to 1 and so on . In this way we need to allocate space only for range ; Numbers which are not marked as false are prime ; Update low and high for next segment ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void simpleSieve ( int limit , vector < int > & prime ) { vector < bool > mark ( limit + 1 , true ) ; for ( int p = 2 ; p * p < limit ; p ++ ) { if ( mark [ p ] == true ) { for ( int i = p * p ; i < limit ; i += p ) mark [ i ] = false ; } } for ( int p = 2 ; p < limit ; p ++ ) { if ( mark [ p ] == true ) { prime . push_back ( p ) ; cout << p << " β " ; } } } void segmentedSieve ( int n ) { int limit = floor ( sqrt ( n ) ) + 1 ; vector < int > prime ; prime . reserve ( limit ) ; simpleSieve ( limit , prime ) ; int low = limit ; int high = 2 * limit ; while ( low < n ) { if ( high >= n ) high = n ; bool mark [ limit + 1 ] ; memset ( mark , true , sizeof ( mark ) ) ; for ( int i = 0 ; i < prime . size ( ) ; i ++ ) { int loLim = floor ( low / prime [ i ] ) * prime [ i ] ; if ( loLim < low ) loLim += prime [ i ] ; for ( int j = loLim ; j < high ; j += prime [ i ] ) mark [ j - low ] = false ; } for ( int i = low ; i < high ; i ++ ) if ( mark [ i - low ] == true ) cout << i << " β " ; low = low + limit ; high = high + limit ; } } int main ( ) { int n = 100000 ; cout << " Primes β smaller β than β " << n << " : n " ; segmentedSieve ( n ) ; return 0 ; } |
Find the smallest twins in given range | C ++ program to find the smallest twin in given range ; Create a boolean array " prime [ 0 . . high ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Look for the smallest twin ; If p is not marked , then it is a prime ; Update all multiples of p ; Now print the smallest twin in range ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printTwins ( int low , int high ) { bool prime [ high + 1 ] , twin = false ; memset ( prime , true , sizeof ( prime ) ) ; prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p <= floor ( sqrt ( high ) ) + 1 ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= high ; i += p ) prime [ i ] = false ; } } for ( int i = low ; i <= high ; i ++ ) { if ( prime [ i ] && prime [ i + 2 ] ) { cout << " Smallest β twins β in β given β range : β ( " << i << " , β " << i + 2 << " ) " ; twin = true ; break ; } } if ( twin == false ) cout << " No β such β pair β exists " << endl ; } int main ( ) { printTwins ( 10 , 100 ) ; return 0 ; } |
Check if a given number is Fancy | C ++ program to find if a given number is fancy or not . ; To store mappings of fancy pair characters . For example 6 is paired with 9 and 9 is paired with 6. ; Find number of digits in given number ; Traverse from both ends , and compare characters one by one ; If current characters at both ends are not fancy pairs ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isFancy ( string & num ) { map < char , char > fp ; fp [ '0' ] = '0' ; fp [ '1' ] = '1' ; fp [ '6' ] = '9' ; fp [ '8' ] = '8' ; fp [ '9' ] = '6' ; int n = num . length ( ) ; int l = 0 , r = n - 1 ; while ( l <= r ) { if ( fp . find ( num [ l ] ) == fp . end ( ) fp [ num [ l ] ] != num [ r ] ) return false ; l ++ ; r -- ; } return true ; } int main ( ) { string str = "9088806" ; isFancy ( str ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Find Next Sparse Number | C ++ program to find next sparse number ; Find binary representation of x and store it in bin [ ] . bin [ 0 ] contains least significant bit ( LSB ) , next bit is in bin [ 1 ] , and so on . ; There my be extra bit in result , so add one extra bit ; The position till which all bits are finalized ; Start from second bit ( next to LSB ) ; If current bit and its previous bit are 1 , but next bit is not 1. ; Make the next bit 1 ; Make all bits before current bit as 0 to make sure that we get the smallest next number ; Store position of the bit set so that this bit and bits before it are not changed next time . ; Find decimal equivalent of modified bin [ ] ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nextSparse ( int x ) { vector < bool > bin ; while ( x != 0 ) { bin . push_back ( x & 1 ) ; x >>= 1 ; } bin . push_back ( 0 ) ; int last_final = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( bin [ i ] == 1 && bin [ i - 1 ] == 1 && bin [ i + 1 ] != 1 ) { bin [ i + 1 ] = 1 ; for ( int j = i ; j >= last_final ; j -- ) bin [ j ] = 0 ; last_final = i + 1 ; } } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans += bin [ i ] * ( 1 << i ) ; return ans ; } int main ( ) { int x = 38 ; cout << " Next β Sparse β Number β is β " << nextSparse ( x ) ; return 0 ; } |
Count number of subsets of a set with GCD equal to a given number | C ++ program to count number of subsets with given GCDs ; n is size of arr [ ] and m is sizeof gcd [ ] ; Map to store frequency of array elements ; Map to store number of subsets with given gcd ; Initialize maximum element . Assumption : all array elements are positive . ; Find maximum element in array and fill frequency map . ; Run a loop from max element to 1 to find subsets with all gcds ; Run a loop for all multiples of i ; Sum the frequencies of every element which is a multiple of i ; Excluding those subsets which have gcd > i but not i i . e . which have gcd as multiple of i in the subset for ex : { 2 , 3 , 4 } considering i = 2 and subset we need to exclude are those having gcd as 4 ; Number of subsets with GCD equal to ' i ' is pow ( 2 , add ) - 1 - sub ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void ccountSubsets ( int arr [ ] , int n , int gcd [ ] , int m ) { unordered_map < int , int > freq ; unordered_map < int , int > subsets ; int arrMax = 0 ; for ( int i = 0 ; i < n ; i ++ ) { arrMax = max ( arrMax , arr [ i ] ) ; freq [ arr [ i ] ] ++ ; } for ( int i = arrMax ; i >= 1 ; i -- ) { int sub = 0 ; int add = freq [ i ] ; for ( int j = 2 ; j * i <= arrMax ; j ++ ) { add += freq [ j * i ] ; sub += subsets [ j * i ] ; } subsets [ i ] = ( 1 << add ) - 1 - sub ; } for ( int i = 0 ; i < m ; i ++ ) cout << " Number β of β subsets β with β gcd β " << gcd [ i ] << " β is β " << subsets [ gcd [ i ] ] << endl ; } int main ( ) { int gcd [ ] = { 2 , 3 } ; int arr [ ] = { 9 , 6 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int m = sizeof ( gcd ) / sizeof ( gcd [ 0 ] ) ; ccountSubsets ( arr , n , gcd , m ) ; return 0 ; } |
Sum of bit differences among all pairs | C ++ program to compute sum of pairwise bit differences ; traverse over all bits ; count number of elements with i 'th bit set ; Add " count β * β ( n β - β count ) β * β 2" to the answer ; Driver prorgram | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumBitDifferences ( int arr [ ] , int n ) { for ( int i = 0 ; i < 32 ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) if ( ( arr [ j ] & ( 1 << i ) ) ) count ++ ; ans += ( count * ( n - count ) * 2 ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 } ; int n = sizeof arr / sizeof arr [ 0 ] ; cout << sumBitDifferences ( arr , n ) << endl ; return 0 ; } |
Print all non | C ++ program to generate all non - increasing sequences of sum equals to x ; Utility function to print array arr [ 0. . n - 1 ] ; Recursive Function to generate all non - increasing sequences with sum x arr [ ] -- > Elements of current sequence curr_sum -- > Current Sum curr_idx -- > Current index in arr [ ] ; If current sum is equal to x , then we found a sequence ; Try placing all numbers from 1 to x - curr_sum at current index ; The placed number must also be smaller than previously placed numbers and it may be equal to the previous stored value , i . e . , arr [ curr_idx - 1 ] if there exists a previous number ; Place number at curr_idx ; Recur ; Try next number ; A wrapper over generateUtil ( ) ; Array to store sequences on by one ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; cout << endl ; } void generateUtil ( int x , int arr [ ] , int curr_sum , int curr_idx ) { if ( curr_sum == x ) { printArr ( arr , curr_idx ) ; return ; } int num = 1 ; while ( num <= x - curr_sum && ( curr_idx == 0 num <= arr [ curr_idx - 1 ] ) ) { arr [ curr_idx ] = num ; generateUtil ( x , arr , curr_sum + num , curr_idx + 1 ) ; num ++ ; } } void generate ( int x ) { int arr [ x ] ; generateUtil ( x , arr , 0 , 0 ) ; } int main ( ) { int x = 5 ; generate ( x ) ; return 0 ; } |
Perfect Number | C ++ program to check if a given number is perfect or not ; Returns true if n is perfect ; To store sum of divisors ; Find all divisors and add them ; If sum of divisors is equal to n , then n is a perfect number ; Driver program | #include <iostream> NEW_LINE using namespace std ; bool isPerfect ( long long int n ) { long long int sum = 1 ; for ( long long int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { if ( i * i != n ) sum = sum + i + n / i ; else sum = sum + i ; } } if ( sum == n && n != 1 ) return true ; return false ; } int main ( ) { cout << " Below β are β all β perfect β numbers β till β 10000 STRNEWLINE " ; for ( int n = 2 ; n < 10000 ; n ++ ) if ( isPerfect ( n ) ) cout << n << " β is β a β perfect β number STRNEWLINE " ; return 0 ; } |
Check if a given number can be represented in given a no . of digits in any base | C ++ program to check if a given number can be represented in given number of digits in any base ; Returns true if ' num ' can be represented usind ' dig ' digits in ' base ' ; Base case ; If there are more than 1 digits left and number is more than base , then remove last digit by doing num / base , reduce the number of digits and recur ; return true of num can be represented in ' dig ' digits in any base from 2 to 32 ; Check for all bases one by one ; Driver program | #include <iostream> NEW_LINE using namespace std ; bool checkUtil ( int num , int dig , int base ) { if ( dig == 1 && num < base ) return true ; if ( dig > 1 && num >= base ) return checkUtil ( num / base , -- dig , base ) ; return false ; } bool check ( int num , int dig ) { for ( int base = 2 ; base <= 32 ; base ++ ) if ( checkUtil ( num , dig , base ) ) return true ; return false ; } int main ( ) { int num = 8 ; int dig = 3 ; ( check ( num , dig ) ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
How to compute mod of a big number ? | C ++ program to compute mod of a big number represented as string ; Function to compute num ( mod a ) ; Initialize result ; One by one process all digits of ' num ' ; Driver program | #include <iostream> NEW_LINE using namespace std ; int mod ( string num , int a ) { int res = 0 ; for ( int i = 0 ; i < num . length ( ) ; i ++ ) res = ( res * 10 + ( int ) num [ i ] - '0' ) % a ; return res ; } int main ( ) { string num = "12316767678678" ; cout << mod ( num , 10 ) ; return 0 ; } |
Modular multiplicative inverse | C ++ program to find modular inverse of a under modulo m ; A naive method to find modular multiplicative inverse of ' a ' under modulo ' m ' ; Driver code ; Function call | #include <iostream> NEW_LINE using namespace std ; int modInverse ( int a , int m ) { for ( int x = 1 ; x < m ; x ++ ) if ( ( ( a % m ) * ( x % m ) ) % m == 1 ) return x ; } int main ( ) { int a = 3 , m = 11 ; cout << modInverse ( a , m ) ; return 0 ; } |
Modular multiplicative inverse | Iterative C ++ program to find modular inverse using extended Euclid algorithm ; Returns modulo inverse of a with respect to m using extended Euclid Algorithm Assumption : a and m are coprimes , i . e . , gcd ( a , m ) = 1 ; q is quotient ; m is remainder now , process same as Euclid 's algo ; Update y and x ; Make x positive ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int modInverse ( int a , int m ) { int m0 = m ; int y = 0 , x = 1 ; if ( m == 1 ) return 0 ; while ( a > 1 ) { int q = a / m ; int t = m ; m = a % m , a = t ; t = y ; y = x - q * y ; x = t ; } if ( x < 0 ) x += m0 ; return x ; } int main ( ) { int a = 3 , m = 11 ; cout << " Modular β multiplicative β inverse β is β " << modInverse ( a , m ) ; return 0 ; } |
Euler 's Totient Function | A simple C ++ program to calculate Euler 's Totient Function ; Function to return gcd of a and b ; A simple method to evaluate Euler Totient Function ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int phi ( unsigned int n ) { unsigned int result = 1 ; for ( int i = 2 ; i < n ; i ++ ) if ( gcd ( i , n ) == 1 ) result ++ ; return result ; } int main ( ) { int n ; for ( n = 1 ; n <= 10 ; n ++ ) cout << " phi ( " << n << " ) β = β " << phi ( n ) << endl ; return 0 ; } |
Euler 's Totient Function | C ++ program to calculate Euler ' s β Totient β Function β using β Euler ' s product formula ; Initialize result as n ; Consider all prime factors of n and for every prime factor p , multiply result with ( 1 - 1 / p ) ; Check if p is a prime factor . ; If yes , then update n and result ; If n has a prime factor greater than sqrt ( n ) ( There can be at - most one such prime factor ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int phi ( int n ) { float result = n ; for ( int p = 2 ; p * p <= n ; ++ p ) { if ( n % p == 0 ) { while ( n % p == 0 ) n /= p ; result *= ( 1.0 - ( 1.0 / ( float ) p ) ) ; } } if ( n > 1 ) result *= ( 1.0 - ( 1.0 / ( float ) n ) ) ; return ( int ) result ; } int main ( ) { int n ; for ( n = 1 ; n <= 10 ; n ++ ) { cout << " Phi " << " ( " << n << " ) " << " β = β " << phi ( n ) << endl ; } return 0 ; } |
Program to find remainder without using modulo or % operator | C ++ implementation of the approach ; Function to return num % divisor without using % ( modulo ) operator ; While divisor is smaller than n , keep subtracting it from num ; Driver code | #include <iostream> NEW_LINE using namespace std ; int getRemainder ( int num , int divisor ) { while ( num >= divisor ) num -= divisor ; return num ; } int main ( ) { int num = 100 , divisor = 7 ; cout << getRemainder ( num , divisor ) ; return 0 ; } |
Efficient Program to Compute Sum of Series 1 / 1 ! + 1 / 2 ! + 1 / 3 ! + 1 / 4 ! + . . + 1 / n ! | A simple C ++ program to compute sum of series 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; Utility function to find ; A Simple Function to return value of 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; Driver program to test above functions | #include <iostream> NEW_LINE using namespace std ; int factorial ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res *= i ; return res ; } double sum ( int n ) { double sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += 1.0 / factorial ( i ) ; return sum ; } int main ( ) { int n = 5 ; cout << sum ( n ) ; return 0 ; } |
Find the number of valid parentheses expressions of given length | C ++ program to find valid paranthesisations of length n The majority of code is taken from method 3 of https : www . geeksforgeeks . org / program - nth - catalan - number / ; Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Function to find possible ways to put balanced parenthesis in an expression of length n ; If n is odd , not possible to create any valid parentheses ; Otherwise return n / 2 'th Catalan Number ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long int binomialCoeff ( unsigned int n , unsigned int k ) { unsigned long int res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } unsigned long int catalan ( unsigned int n ) { unsigned long int c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } unsigned long int findWays ( unsigned n ) { if ( n & 1 ) return 0 ; return catalan ( n / 2 ) ; } int main ( ) { int n = 6 ; cout << " Total β possible β expressions β of β length β " << n << " β is β " << findWays ( 6 ) ; return 0 ; } |
Program to evaluate simple expressions | C ++ program to evaluate a given expression ; A utility function to check if a given character is operand ; utility function to find value of and operand ; This function evaluates simple expressions . It returns - 1 if the given expression is invalid . ; Base Case : Given expression is empty ; The first character must be an operand , find its value ; Traverse the remaining characters in pairs ; The next character must be an operator , and next to next an operand ; If next to next character is not an operand ; Update result according to the operator ; If not a valid operator ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; bool isOperand ( char c ) { return ( c >= '0' && c <= '9' ) ; } int value ( char c ) { return ( c - '0' ) ; } int evaluate ( char * exp ) { if ( * exp == ' \0' ) return -1 ; int res = value ( exp [ 0 ] ) ; for ( int i = 1 ; exp [ i ] ; i += 2 ) { char opr = exp [ i ] , opd = exp [ i + 1 ] ; if ( ! isOperand ( opd ) ) return -1 ; if ( opr == ' + ' ) res += value ( opd ) ; else if ( opr == ' - ' ) res -= value ( opd ) ; else if ( opr == ' * ' ) res *= value ( opd ) ; else if ( opr == ' / ' ) res /= value ( opd ) ; else return -1 ; } return res ; } int main ( ) { char expr1 [ ] = "1 + 2*5 + 3" ; int res = evaluate ( expr1 ) ; ( res == -1 ) ? cout << expr1 << " β is β " << " Invalid STRNEWLINE " : cout << " Value β of β " << expr1 << " β is β " << res << endl ; char expr2 [ ] = "1 + 2*3" ; res = evaluate ( expr2 ) ; ( res == -1 ) ? cout << expr2 << " β is β " << " Invalid STRNEWLINE " : cout << " Value β of β " << expr2 << " β is β " << res << endl ; char expr3 [ ] = "4-2 + 6*3" ; res = evaluate ( expr3 ) ; ( res == -1 ) ? cout << expr3 << " β is β " << " Invalid STRNEWLINE " : cout << " Value β of β " << expr3 << " β is β " << res << endl ; char expr4 [ ] = "1 + + 2" ; res = evaluate ( expr4 ) ; ( res == -1 ) ? cout << expr4 << " β is β " << " Invalid STRNEWLINE " : cout << " Value β of β " << expr4 << " β is β " << res << endl ; return 0 ; } |
Program to print first n Fibonacci Numbers | Set 1 | C ++ program to print first n Fibonacci numbers ; Function to print first n Fibonacci Numbers ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printFibonacciNumbers ( int n ) { int f1 = 0 , f2 = 1 , i ; if ( n < 1 ) return ; cout << f1 << " β " ; for ( i = 1 ; i < n ; i ++ ) { cout << f2 << " β " ; int next = f1 + f2 ; f1 = f2 ; f2 = next ; } } int main ( ) { printFibonacciNumbers ( 7 ) ; return 0 ; } |
Program to find LCM of two numbers | C ++ program to find LCM of two numbers ; Recursive function to return gcd of a and b ; Function to return LCM of two numbers ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; long long gcd ( long long int a , long long int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } long long lcm ( int a , int b ) { return ( a / gcd ( a , b ) ) * b ; } int main ( ) { int a = 15 , b = 20 ; cout << " LCM β of β " << a << " β and β " << b << " β is β " << lcm ( a , b ) ; return 0 ; } |
Program to find sum of elements in a given array | C ++ Program to find sum of elements in a given array ; Driver code ; calling accumulate function , passing first , last element and initial sum , which is 0 in this case . | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int arr [ ] = { 12 , 3 , 4 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Sum β of β given β array β is β " << accumulate ( arr , arr + n , 0 ) ; return 0 ; } |
To find sum of two numbers without using any operator | ; Driver code | #include <iostream> NEW_LINE using namespace std ; int add ( int x , int y ) { return printf ( " % * c % * c " , x , ' β ' , y , ' β ' ) ; } int main ( ) { printf ( " Sum β = β % d " , add ( 3 , 4 ) ) ; return 0 ; } |
Check if a number is multiple of 5 without using / and % operators | Assuming that integer takes 4 bytes , there can be maximum 10 digits in a integer ; Check the last character of string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; # define MAX 11 NEW_LINE bool isMultipleof5 ( int n ) { char str [ MAX ] ; int len = strlen ( str ) ; if ( str [ len - 1 ] == '5' str [ len - 1 ] == '0' ) return true ; return false ; } int main ( ) { int n = 19 ; if ( isMultipleof5 ( n ) == true ) cout << n << " β is β multiple β of β 5" << endl ; else cout << n << " β is β not β multiple β of β 5" << endl ; return 0 ; } |
Check if there are T number of continuous of blocks of 0 s or not in given Binary Matrix | C ++ program for the above approach ; Stores the moves in the matrix ; Function to find if the current cell lies in the matrix or not ; Function to perform the DFS Traversal ; Iterate over the direction vector ; DFS Call ; Function to check if it satisfy the given criteria or not ; Keeps the count of cell having value as 0 ; If condition doesn 't satisfy ; Keeps the track of unvisted cell having values 0 ; Increasing count of black_spot ; Find the GCD of N and M ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const long long M = 1e9 + 7 ; vector < pair < int , int > > directions = { { 0 , 1 } , { -1 , 0 } , { 0 , -1 } , { 1 , 0 } , { 1 , 1 } , { -1 , -1 } , { -1 , 1 } , { 1 , -1 } } ; bool isInside ( int i , int j , int N , int M ) { if ( i >= 0 && i < N && j >= 0 && j < M ) { return true ; } return false ; } void DFS ( vector < vector < int > > mat , int N , int M , int i , int j , vector < vector < bool > > & visited ) { if ( visited [ i ] [ j ] == true ) { return ; } visited [ i ] [ j ] = true ; for ( auto it : directions ) { int I = i + it . first ; int J = j + it . second ; if ( isInside ( I , J , N , M ) ) { if ( mat [ I ] [ J ] == 0 ) { DFS ( mat , N , M , I , J , visited ) ; } } } } void check ( int N , int M , vector < vector < int > > & mat ) { int black = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( mat [ i ] [ j ] == 0 ) { black ++ ; } } } if ( black < 2 * ( max ( N , M ) ) ) { cout << " NO " << endl ; return ; } vector < vector < bool > > visited ; for ( int i = 0 ; i < N ; i ++ ) { vector < bool > temp ; for ( int j = 0 ; j < M ; j ++ ) { temp . push_back ( false ) ; } visited . push_back ( temp ) ; } int black_spots = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( visited [ i ] [ j ] == false && mat [ i ] [ j ] == 0 ) { black_spots ++ ; DFS ( mat , N , M , i , j , visited ) ; } } } int T = __gcd ( N , M ) ; cout << ( black_spots >= T ? " Yes " : " No " ) ; } int main ( ) { int N = 3 , M = 3 ; vector < vector < int > > mat = { { 0 , 0 , 1 } , { 1 , 1 , 1 } , { 0 , 0 , 1 } } ; check ( M , N , mat ) ; return 0 ; } |
Count subsequences having odd Bitwise OR values in an array | C ++ implementation for the above approach ; Function to count the subsequences having odd bitwise OR value ; Stores count of odd elements ; Stores count of even elements ; Traverse the array arr [ ] ; If element is odd ; Return the final answer ; Driver Code ; Given array arr [ ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubsequences ( vector < int > arr ) { int odd = 0 ; int even = 0 ; for ( int x : arr ) { if ( x & 1 ) odd ++ ; else even ++ ; } return ( ( 1 << odd ) - 1 ) * ( 1 << even ) ; } int main ( ) { vector < int > arr = { 2 , 4 , 1 } ; cout << countSubsequences ( arr ) ; } |
Bitwise OR of Bitwise AND of all subsets of an Array for Q queries | C ++ program for the above approach ; Function to find the OR of AND of all subsets of the array for each query ; An array to store the bits ; Itearte for all the bits ; Iterate over all the numbers and store the bits in bits [ ] array ; Itearte over all the queries ; Replace the bits of the value at arr [ queries [ p ] [ 0 ] ] with the bits of queries [ p ] [ 1 ] ; Substitute the value in the array ; Find OR of the bits [ ] array ; Print the answer ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void Or_of_Ands_for_each_query ( int arr [ ] , int n , int queries [ ] [ 2 ] , int q ) { int bits [ 32 ] = { 0 } ; for ( int i = 0 ; i < 32 ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( ( 1 << i ) & arr [ j ] ) { bits [ i ] ++ ; } } } for ( int p = 0 ; p < q ; p ++ ) { for ( int i = 0 ; i < 32 ; i ++ ) { if ( ( 1 << i ) & arr [ queries [ p ] [ 0 ] ] ) { bits [ i ] -- ; } if ( queries [ p ] [ 1 ] & ( 1 << i ) ) { bits [ i ] ++ ; } } arr [ queries [ p ] [ 0 ] ] = queries [ p ] [ 1 ] ; int ans = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { if ( bits [ i ] != 0 ) { ans |= ( 1 << i ) ; } } cout << ans << endl ; } } int main ( ) { int n = 3 , q = 2 ; int arr [ ] = { 3 , 5 , 7 } ; int queries [ 2 ] [ 2 ] = { { 1 , 2 } , { 2 , 1 } } ; Or_of_Ands_for_each_query ( arr , n , queries , q ) ; return 0 ; } |
Find XOR sum of Bitwise AND of all pairs from given two Arrays | C ++ algorithm for the above approach ; Function to calculate the XOR sum of all ANDS of all pairs on A [ ] and B [ ] ; variable to store anshu ; when there has been no AND of pairs before this ; Driver code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int XorSum ( int A [ ] , int B [ ] , int N , int M ) { int ans = -1 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( ans == -1 ) ans = ( A [ i ] & B [ j ] ) ; else ans ^= ( A [ i ] & B [ j ] ) ; } } return ans ; } int main ( ) { int A [ ] = { 3 , 5 } ; int B [ ] = { 2 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int M = sizeof ( B ) / sizeof ( B [ 0 ] ) ; cout << XorSum ( A , B , N , M ) << endl ; } |
Shortest path length between two given nodes such that adjacent nodes are at bit difference 2 | C ++ program for the above approach ; Function to count set bits in a number ; Stores count of set bits in xo ; Iterate over each bits of xo ; If current bit of xo is 1 ; Update count ; Update xo ; Function to find length of shortest path between the nodes a and b ; Stores XOR of a and b ; Stores the count of set bits in xorVal ; If cnt is an even number ; Driver Code ; Given N ; Given a and b ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countbitdiff ( int xo ) { int count = 0 ; while ( xo ) { if ( xo % 2 == 1 ) { count ++ ; } xo = xo / 2 ; } return count ; } void shortestPath ( int n , int a , int b ) { int xorVal = a ^ b ; int cnt = countbitdiff ( xorVal ) ; if ( cnt % 2 == 0 ) cout << cnt / 2 << endl ; else cout << " - 1" << endl ; } int main ( ) { int n = 15 ; int a = 15 , b = 3 ; shortestPath ( n , a , b ) ; return 0 ; } |
Modify a matrix by converting each element to XOR of its digits | C ++ program for the above approach ; Function to calculate Bitwise XOR of digits present in X ; Stores the Bitwise XOR ; While X is true ; Update Bitwise XOR of its digits ; Return the result ; Function to print matrix after converting each matrix element to XOR of its digits ; Traverse each row of arr [ ] [ ] ; Traverse each column of arr [ ] [ ] ; Function to convert the given matrix to required XOR matrix ; Traverse each row of arr [ ] [ ] ; Traverse each column of arr [ ] [ ] ; Store the current matrix element ; Find the xor of digits present in X ; Stores the XOR value ; Print resultant matrix ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 3 ; const int N = 3 ; int findXOR ( int X ) { int ans = 0 ; while ( X ) { ans ^= ( X % 10 ) ; X /= 10 ; } return ans ; } void printXORmatrix ( int arr [ M ] [ N ] ) { for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { cout << arr [ i ] [ j ] << " β " ; } cout << " STRNEWLINE " ; } } void convertXOR ( int arr [ M ] [ N ] ) { for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { int X = arr [ i ] [ j ] ; int temp = findXOR ( X ) ; arr [ i ] [ j ] = temp ; } } printXORmatrix ( arr ) ; } int main ( ) { int arr [ ] [ 3 ] = { { 27 , 173 , 5 } , { 21 , 6 , 624 } , { 5 , 321 , 49 } } ; convertXOR ( arr ) ; return 0 ; } |
Sum of Bitwise AND of sum of pairs and their Bitwise AND from a given array | C ++ program for the above approach ; Function to find the sum of Bitwise AND of sum of pairs and their Bitwise AND from a given array ; Stores the total sum ; Check if jth bit is set ; Stores the right shifted element by ( i + 1 ) ; Update the value of X ; Push in vector vec ; Sort the vector in ascending order ; Traverse the vector vec ; Stores the value 2 ^ ( i + 1 ) - 2 ^ ( i ) - vec [ j ] ; Stores count of numbers whose value > Y ; Update the ans ; Return the ans ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define M 1000000007 NEW_LINE using namespace std ; void findSum ( int A [ ] , int N ) { long long ans = 0 ; for ( int i = 0 ; i < 30 ; i ++ ) { vector < long long > vec ; for ( int j = 0 ; j < N ; j ++ ) { if ( ( A [ j ] >> i ) & 1 ) { long long X = ( A [ j ] >> ( i + 1 ) ) ; X = X * ( 1 << ( i + 1 ) ) ; X %= M ; vec . push_back ( A [ j ] - X ) ; } } sort ( vec . begin ( ) , vec . end ( ) ) ; for ( int j = 0 ; j < vec . size ( ) ; j ++ ) { int Y = ( 1 << ( i + 1 ) ) + ( 1 << i ) - vec [ j ] ; int idx = lower_bound ( vec . begin ( ) + j + 1 , vec . end ( ) , Y ) - vec . begin ( ) ; ans += ( vec . size ( ) - idx ) * 1ll * ( 1 << i ) ; ans %= M ; } } cout << ans % M << endl ; } int main ( ) { int arr [ ] = { 1 , 3 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findSum ( arr , N ) ; return 0 ; } |
Count subarrays made up of elements having exactly K set bits | C ++ program for the above approach ; Function to count the number of set bits in an integer N ; Stores the count of set bits ; While N is non - zero ; If the LSB is 1 , then increment ans by 1 ; Return the total set bits ; Function to count the number of subarrays having made up of elements having K set bits ; Stores the total count of resultant subarrays ; Traverse the given array ; If the current element has K set bits ; Otherwise ; Increment count of subarrays ; Return total count of subarrays ; Driver Code ; Function Call | #include <iostream> NEW_LINE using namespace std ; int countSet ( int N ) { int ans = 0 ; while ( N ) { ans += N & 1 ; N >>= 1 ; } return ans ; } int countSub ( int * arr , int k ) { int ans = 0 ; int setK = 0 ; for ( int i = 0 ; i < 5 ; i ++ ) { if ( countSet ( arr [ i ] ) == k ) setK += 1 ; else setK = 0 ; ans += setK ; } return ans ; } int main ( ) { int arr [ ] = { 4 , 2 , 1 , 5 , 6 } ; int K = 2 ; cout << ( countSub ( arr , K ) ) ; return 0 ; } |
Count subarrays having odd Bitwise XOR | C ++ program for the above approach ; Function to count the number of subarrays of the given array having odd Bitwise XOR ; Stores number of odd numbers upto i - th index ; Stores number of required subarrays starting from i - th index ; Store the required result ; Find the number of subarrays having odd Bitwise XOR values starting at 0 - th index ; Check if current element is odd ; If the current value of odd is not zero , increment c_odd by 1 ; Find the number of subarrays having odd bitwise XOR value starting at ith index and add to result ; Add c_odd to result ; Print the result ; Driver Code ; Given array ; Stores the size of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void oddXorSubarray ( int a [ ] , int n ) { int odd = 0 ; int c_odd = 0 ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] & 1 ) { odd = ! odd ; } if ( odd ) { c_odd ++ ; } } for ( int i = 0 ; i < n ; i ++ ) { result += c_odd ; if ( a [ i ] & 1 ) { c_odd = ( n - i - c_odd ) ; } } cout << result ; } int main ( ) { int arr [ ] = { 1 , 4 , 7 , 9 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; oddXorSubarray ( arr , N ) ; return 0 ; } |
XOR Linked List | C ++ program to implement the above approach ; Structure of a node in XOR linked list ; Stores data value of a node ; Stores XOR of previous pointer and next pointer ; Function to find the XOR of address of two nodes ; Function to insert a node with given value at given position ; If XOR linked list is empty ; Initialize a new Node ; Stores data value in the node ; Stores XOR of previous and next pointer ; Update pointer of head node ; If the XOR linked list is not empty ; Stores the address of current node ; Stores the address of previous node ; Initialize a new Node ; Update curr node address ; Update new node address ; Update head ; Update data value of current node ; Function to print elements of the XOR Linked List ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Traverse XOR linked list ; Print current node ; Forward traversal ; Update prev ; Update curr ; Reverse the linked list in group of K ; Stores head node ; If the XOR linked list is empty ; Stores count of nodes reversed in current group ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Reverse nodes in current group ; Forward traversal ; Update prev ; Update curr ; Update count ; Disconnect prev node from the next node ; Disconnect curr from previous node ; If the count of remaining nodes is less than K ; Update len ; Recursively process the next nodes ; Connect the head pointer with the prev ; Connect prev with the head ; Driver Code ; Create following XOR Linked List head -- > 7 < a > 6 < a > 8 < a > 11 < a > 3 < a > 1 < a > 2 < a > 0 ; Function Call ; Print the reversed list | #include <bits/stdc++.h> NEW_LINE #include <inttypes.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * nxp ; } ; struct Node * XOR ( struct Node * a , struct Node * b ) { return ( struct Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } struct Node * insert ( struct Node * * head , int value ) { if ( * head == NULL ) { struct Node * node = new Node ; node -> data = value ; node -> nxp = XOR ( NULL , NULL ) ; * head = node ; } else { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * node = new Node ( ) ; curr -> nxp = XOR ( node , XOR ( NULL , curr -> nxp ) ) ; node -> nxp = XOR ( NULL , curr ) ; * head = node ; node -> data = value ; } return * head ; } void printList ( struct Node * * head ) { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next ; while ( curr != NULL ) { cout << curr -> data << " β " ; next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; } } struct Node * RevInGrp ( struct Node * * head , int K , int len ) { struct Node * curr = * head ; if ( curr == NULL ) return NULL ; int count = 0 ; struct Node * prev = NULL ; struct Node * next ; while ( count < K && count < len ) { next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; count ++ ; } prev -> nxp = XOR ( NULL , XOR ( prev -> nxp , curr ) ) ; if ( curr != NULL ) curr -> nxp = XOR ( XOR ( curr -> nxp , prev ) , NULL ) ; if ( len < K ) { return prev ; } else { len -= K ; struct Node * dummy = RevInGrp ( & curr , K , len ) ; ( * head ) -> nxp = XOR ( XOR ( NULL , ( * head ) -> nxp ) , dummy ) ; if ( dummy != NULL ) dummy -> nxp = XOR ( XOR ( dummy -> nxp , NULL ) , * head ) ; return prev ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 0 ) ; insert ( & head , 2 ) ; insert ( & head , 1 ) ; insert ( & head , 3 ) ; insert ( & head , 11 ) ; insert ( & head , 8 ) ; insert ( & head , 6 ) ; insert ( & head , 7 ) ; head = RevInGrp ( & head , 3 , 8 ) ; printList ( & head ) ; return ( 0 ) ; } |
Sum of Bitwise OR of every array element paired with all other array elements | C ++ program for the above approach ; Function to print required sum for every valid index i ; Store the required sum for current array element ; Generate all possible pairs ( arr [ i ] , arr [ j ] ) ; Update the value of req_sum ; Print the required sum ; Driver Code ; Given array ; Size of the array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printORSumforEachElement ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int req_sum = 0 ; for ( int j = 0 ; j < N ; j ++ ) { req_sum += ( arr [ i ] arr [ j ] ) ; } cout << req_sum << " β " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printORSumforEachElement ( arr , N ) ; return 0 ; } |
XOR Linked List | C ++ program for the above approach ; Structure of a node in XOR linked list ; Stores data value of a node ; Stores XOR of previous pointer and next pointer ; Function to find the XOR of two nodes ; Function to insert a node with given value at beginning position ; If XOR linked list is empty ; Initialize a new Node ; Stores data value in the node ; Stores XOR of previous and next pointer ; Update pointer of head node ; If the XOR linked list is not empty ; Stores the address of current node ; Stores the address of previous node ; Initialize a new Node ; Update curr node address ; Update new node address ; Update head ; Update data value of current node ; Function to print elements of the XOR Linked List ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Traverse XOR linked list ; Print current node ; Forward traversal ; Update prev ; Update curr ; Function to reverse the XOR linked list ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Forward traversal ; Update prev ; Update curr ; Update the head pointer ; Driver Code ; Create following XOR Linked List head -- > 40 < -- > 30 < -- > 20 < -- > 10 ; Reverse the XOR Linked List to give head -- > 10 < -- > 20 < -- > 30 < -- > 40 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * nxp ; } ; Node * XOR ( Node * a , Node * b ) { return ( Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } Node * insert ( Node * * head , int value ) { if ( * head == NULL ) { Node * node = new Node ( ) ; node -> data = value ; node -> nxp = XOR ( NULL , NULL ) ; * head = node ; } else { Node * curr = * head ; Node * prev = NULL ; Node * node = new Node ( ) ; curr -> nxp = XOR ( node , XOR ( NULL , curr -> nxp ) ) ; node -> nxp = XOR ( NULL , curr ) ; * head = node ; node -> data = value ; } return * head ; } void printList ( Node * * head ) { Node * curr = * head ; Node * prev = NULL ; Node * next ; while ( curr != NULL ) { cout << curr -> data << " β " ; next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; } cout << endl ; } Node * reverse ( Node * * head ) { Node * curr = * head ; if ( curr == NULL ) return NULL ; else { Node * prev = NULL ; Node * next ; while ( XOR ( prev , curr -> nxp ) != NULL ) { next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; } * head = curr ; return * head ; } } int main ( ) { Node * head = NULL ; insert ( & head , 10 ) ; insert ( & head , 20 ) ; insert ( & head , 30 ) ; insert ( & head , 40 ) ; cout << " XOR β linked β list : β " ; printList ( & head ) ; reverse ( & head ) ; cout << " Reversed β XOR β linked β list : β " ; printList ( & head ) ; return 0 ; } |
Sum of Bitwise OR of each array element of an array with all elements of another array | C ++ program for the above approach ; Function to compute sum of Bitwise OR of each element in arr1 [ ] with all elements of the array arr2 [ ] ; Declaring an array of size 32 to store the count of each bit ; Traverse the array arr1 [ ] ; Current bit position ; While num exceeds 0 ; Checks if i - th bit is set or not ; Increment the count at bit_position by one ; Increment bit_position ; Right shift the num by one ; Traverse in the arr2 [ ] ; Store the ith bit value ; Total required sum ; Traverse in the range [ 0 , 31 ] ; Check if current bit is set ; Increment the Bitwise sum by N * ( 2 ^ i ) ; Right shift num by one ; Left shift valee_at_that_bit by one ; Print the sum obtained for ith number in arr1 [ ] ; Driver Code ; Given arr1 [ ] ; Given arr2 [ ] ; Size of arr1 [ ] ; Size of arr2 [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void Bitwise_OR_sum_i ( int arr1 [ ] , int arr2 [ ] , int M , int N ) { int frequency [ 32 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { int bit_position = 0 ; int num = arr1 [ i ] ; while ( num ) { if ( num & 1 ) { frequency [ bit_position ] += 1 ; } bit_position += 1 ; num >>= 1 ; } } for ( int i = 0 ; i < M ; i ++ ) { int num = arr2 [ i ] ; int value_at_that_bit = 1 ; int bitwise_OR_sum = 0 ; for ( int bit_position = 0 ; bit_position < 32 ; bit_position ++ ) { if ( num & 1 ) { bitwise_OR_sum += N * value_at_that_bit ; } else { bitwise_OR_sum += frequency [ bit_position ] * value_at_that_bit ; } num >>= 1 ; value_at_that_bit <<= 1 ; } cout << bitwise_OR_sum << ' β ' ; } return ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 3 } ; int arr2 [ ] = { 1 , 2 , 3 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int M = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; Bitwise_OR_sum_i ( arr1 , arr2 , M , N ) ; return 0 ; } |
XOR Linked List | C ++ program to implement the above approach ; Structure of a node in XOR linked list ; Stores data value of a node ; Stores XOR of previous pointer and next pointer ; Function to find the XOR of two nodes ; Function to insert a node with given value at given position ; If XOR linked list is empty ; Initialize a new Node ; Stores data value in the node ; Stores XOR of previous and next pointer ; Update pointer of head node ; If the XOR linked list is not empty ; Stores the address of current node ; Stores the address of previous node ; Initialize a new Node ; Update curr node address ; Update new node address ; Update head ; Update data value of current node ; Function to print elements of the XOR Linked List ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Traverse XOR linked list ; Print current node ; Forward traversal ; Update prev ; Update curr ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Forward traversal ; Update prev ; Update curr ; Forward traversal ; Update prev ; Update curr ; Driver Code ; Create following XOR Linked List head -- > 7 a > 6 a > 8 a > 11 a > 3 a > 1 a > 2 a > 0 | #include <bits/stdc++.h> NEW_LINE #include <inttypes.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * nxp ; } ; struct Node * XOR ( struct Node * a , struct Node * b ) { return ( struct Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } struct Node * insert ( struct Node * * head , int value ) { if ( * head == NULL ) { struct Node * node = new Node ; node -> data = value ; node -> nxp = XOR ( NULL , NULL ) ; * head = node ; } else { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * node = new Node ( ) ; curr -> nxp = XOR ( node , XOR ( NULL , curr -> nxp ) ) ; node -> nxp = XOR ( NULL , curr ) ; * head = node ; node -> data = value ; } return * head ; } void printList ( struct Node * * head ) { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next ; while ( curr != NULL ) { cout << curr -> data << " β " ; next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; } } struct Node * NthNode ( struct Node * * head , int N ) { int count = 0 ; struct Node * curr = * head ; struct Node * curr1 = * head ; struct Node * prev = NULL ; struct Node * prev1 = NULL ; struct Node * next ; struct Node * next1 ; while ( count < N && curr != NULL ) { next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; count ++ ; } if ( curr == NULL && count < N ) { cout << " Wrong β Input STRNEWLINE " ; return ( uintptr_t ) 0 ; } else { while ( curr != NULL ) { next = XOR ( prev , curr -> nxp ) ; next1 = XOR ( prev1 , curr1 -> nxp ) ; prev = curr ; prev1 = curr1 ; curr = next ; curr1 = next1 ; } cout << curr1 -> data << " β " ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 0 ) ; insert ( & head , 2 ) ; insert ( & head , 1 ) ; insert ( & head , 3 ) ; insert ( & head , 11 ) ; insert ( & head , 8 ) ; insert ( & head , 6 ) ; insert ( & head , 7 ) ; NthNode ( & head , 3 ) ; return ( 0 ) ; } |
XOR Linked List | C ++ program to implement the above approach ; Structure of a node in XOR linked list ; Stores data value of a node ; Stores XOR of previous pointer and next pointer ; Function to find the XOR of two nodes ; Function to insert a node with given value at given position ; If XOR linked list is empty ; Initialize a new Node ; Stores data value in the node ; Stores XOR of previous and next pointer ; Update pointer of head node ; If the XOR linked list is not empty ; Stores the address of current node ; Stores the address of previous node ; Initialize a new Node ; Update curr node address ; Update new node address ; Update head ; Update data value of current node ; Function to print the middle node ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Traverse XOR linked list ; Forward traversal ; Update prev ; Update curr ; If the length of the linked list is odd ; If the length of the linked list is even ; Driver Code ; Create following XOR Linked List head -- > 4 a > 7 a > 5 | #include <bits/stdc++.h> NEW_LINE #include <inttypes.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * nxp ; } ; struct Node * XOR ( struct Node * a , struct Node * b ) { return ( struct Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } struct Node * insert ( struct Node * * head , int value ) { if ( * head == NULL ) { struct Node * node = new Node ; node -> data = value ; node -> nxp = XOR ( NULL , NULL ) ; * head = node ; } else { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * node = new Node ( ) ; curr -> nxp = XOR ( node , XOR ( NULL , curr -> nxp ) ) ; node -> nxp = XOR ( NULL , curr ) ; * head = node ; node -> data = value ; } return * head ; } int printMiddle ( struct Node * * head , int len ) { int count = 0 ; struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next ; int middle = ( int ) len / 2 ; while ( count != middle ) { next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; count ++ ; } if ( len & 1 ) { cout << curr -> data << " β " ; } else { cout << prev -> data << " β " << curr -> data << " β " ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 4 ) ; insert ( & head , 7 ) ; insert ( & head , 5 ) ; printMiddle ( & head , 3 ) ; return ( 0 ) ; } |
XOR Linked List | C ++ program to implement the above approach ; Structure of a node in XOR linked list ; Stores data value of a node ; Stores XOR of previous pointer and next pointer ; Function to find the XOR of two nodes ; Function to insert a node with given value at given position ; If XOR linked list is empty ; If given position is equal to 1 ; Initialize a new Node ; Stores data value in the node ; Stores XOR of previous and next pointer ; Update pointer of head node ; If required position was not found ; If the XOR linked list is not empty ; Stores position of a node in the XOR linked list ; Stores the address of current node ; Stores the address of previous node ; Stores the XOR of next node and previous node ; Traverse the XOR linked list ; Update prev ; Update curr ; Update next ; Update Pos ; If the position of the current node is equal to the given position ; Initialize a new Node ; Stores pointer to previous Node as ( prev ^ next ^ next ) = prev ; Stores XOR of prev and new node ; Connecting new node with next ; Update pointer of next ; Connect node with curr and next curr < -- node -- > next ; Insertion node at beginning ; Initialize a new Node ; Update curr node address ; Update new node address ; Update head ; Update data value of current node ; Function to print elements of the XOR Linked List ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Traverse XOR linked list ; Print current node ; Forward traversal ; Update prev ; Update curr ; Driver Code ; Create following XOR Linked List head -- > 20 < -- > 40 < -- > 10 < -- > 30 ; Print the new list | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * nxp ; } ; struct Node * XOR ( struct Node * a , struct Node * b ) { return ( struct Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } struct Node * insert ( struct Node * * head , int value , int position ) { if ( * head == NULL ) { if ( position == 1 ) { struct Node * node = new Node ( ) ; node -> data = value ; node -> nxp = XOR ( NULL , NULL ) ; * head = node ; } else { cout << " Invalid β Position STRNEWLINE " ; } } else { int Pos = 1 ; struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next = XOR ( prev , curr -> nxp ) ; while ( next != NULL && Pos < position - 1 ) { prev = curr ; curr = next ; next = XOR ( prev , curr -> nxp ) ; Pos ++ ; } if ( Pos == position - 1 ) { struct Node * node = new Node ( ) ; struct Node * temp = XOR ( curr -> nxp , next ) ; curr -> nxp = XOR ( temp , node ) ; if ( next != NULL ) { next -> nxp = XOR ( node , XOR ( next -> nxp , curr ) ) ; } node -> nxp = XOR ( curr , next ) ; node -> data = value ; } else if ( position == 1 ) { struct Node * node = new Node ( ) ; curr -> nxp = XOR ( node , XOR ( NULL , curr -> nxp ) ) ; node -> nxp = XOR ( NULL , curr ) ; * head = node ; node -> data = value ; } else { cout << " Invalid β Position STRNEWLINE " ; } } return * head ; } void printList ( struct Node * * head ) { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next ; while ( curr != NULL ) { cout << curr -> data << " β " ; next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 10 , 1 ) ; insert ( & head , 20 , 1 ) ; insert ( & head , 30 , 3 ) ; insert ( & head , 40 , 2 ) ; printList ( & head ) ; return 0 ; } |
Count pairs from given array with Bitwise OR equal to K | C ++ program for the above approach ; Function that counts the pairs from the array whose Bitwise OR is K ; Stores the required count of pairs ; Generate all possible pairs ; Perform OR operation ; If Bitwise OR is equal to K , increment count ; Print the total count ; Driver Code ; Function Call | #include <iostream> NEW_LINE using namespace std ; void countPairs ( int arr [ ] , int k , int size ) { int count = 0 , x ; for ( int i = 0 ; i < size - 1 ; i ++ ) { for ( int j = i + 1 ; j < size ; j ++ ) { x = arr [ i ] | arr [ j ] ; if ( x == k ) count ++ ; } } cout << count ; } int main ( ) { int arr [ ] = { 2 , 38 , 44 , 29 , 62 } ; int K = 46 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , K , N ) ; return 0 ; } |
Count nodes having Bitwise XOR of all edges in their path from the root equal to K | C ++ program for the above approach ; Initialize the adjacency list to represent the tree ; Marks visited / unvisited vertices ; Stores the required count of nodes ; DFS to visit each vertex ; Mark the current node as visited ; Update the counter xor is K ; Visit adjacent nodes ; Calculate Bitwise XOR of edges in the path ; Recursive call to dfs function ; Function to construct the tree and print required count of nodes ; Add edges ; Print answer ; Driver Code ; Given K and R ; Given edges ; Number of vertices ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < pair < int , int > > adj [ 100005 ] ; int visited [ 100005 ] = { 0 } ; int ans = 0 ; void dfs ( int node , int xorr , int k ) { visited [ node ] = 1 ; if ( node != 1 && xorr == k ) ans ++ ; for ( auto x : adj [ node ] ) { if ( ! visited [ x . first ] ) { int xorr1 = xorr ^ x . second ; dfs ( x . first , xorr1 , k ) ; } } } void countNodes ( int N , int K , int R , vector < vector < int > > edges ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { int u = edges [ i ] [ 0 ] , v = edges [ i ] [ 1 ] , w = edges [ i ] [ 2 ] ; adj [ u ] . push_back ( { v , w } ) ; adj [ v ] . push_back ( { u , w } ) ; } dfs ( R , 0 , K ) ; cout << ans << " STRNEWLINE " ; } int main ( ) { int K = 0 , R = 1 ; vector < vector < int > > edges = { { 1 , 2 , 3 } , { 1 , 3 , 1 } , { 2 , 4 , 3 } , { 2 , 5 , 4 } , { 3 , 6 , 1 } , { 3 , 7 , 2 } } ; int N = edges . size ( ) ; countNodes ( N , K , R , edges ) ; return 0 ; } |
Bitwise operations on Subarrays of size K | C ++ program to find the subarray / with minimum XOR ; Function to find the minimum XOR of the subarray of size K ; K must be smaller than or equal to n ; Initialize the beginning index of result ; Compute XOR sum of first subarray of size K ; Initialize minimum XOR sum as current xor ; Traverse from ( k + 1 ) ' th β β element β to β n ' th element ; XOR with current item and first item of previous subarray ; Update result if needed ; Print the minimum XOR ; Driver Code ; Given array arr [ ] ; Given subarray size K ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinXORSubarray ( int arr [ ] , int n , int k ) { if ( n < k ) return ; int res_index = 0 ; int curr_xor = 0 ; for ( int i = 0 ; i < k ; i ++ ) curr_xor ^= arr [ i ] ; int min_xor = curr_xor ; for ( int i = k ; i < n ; i ++ ) { curr_xor ^= ( arr [ i ] ^ arr [ i - k ] ) ; if ( curr_xor < min_xor ) { min_xor = curr_xor ; res_index = ( i - k + 1 ) ; } } cout << min_xor << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 3 , 7 , 90 , 20 , 10 , 50 , 40 } ; int k = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMinXORSubarray ( arr , n , k ) ; return 0 ; } |
Maximum number of consecutive 1 s after flipping all 0 s in a K length subarray | C ++ program for the above approach ; Function to find the maximum number of consecutive 1 's after flipping all zero in a K length subarray ; Initialize variable ; Iterate unil n - k + 1 as we have to go till i + k ; Iterate in the array in left direction till you get 1 else break ; Iterate in the array in right direction till you get 1 else break ; Compute the maximum length ; Return the length ; Driver code ; Array initialization ; Size of array | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findmax ( int arr [ ] , int n , int k ) { int trav , i ; int c = 0 , maximum = 0 ; for ( i = 0 ; i < n - k + 1 ; i ++ ) { trav = i - 1 ; c = 0 ; while ( trav >= 0 && arr [ trav ] == 1 ) { trav -- ; c ++ ; } trav = i + k ; while ( trav < n && arr [ trav ] == 1 ) { trav ++ ; c ++ ; } c += k ; if ( c > maximum ) maximum = c ; } return maximum ; } int main ( ) { int k = 3 ; int arr [ ] = { 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 } ; int n = sizeof arr / sizeof arr [ 0 ] ; int ans = findmax ( arr , n , k ) ; cout << ans << ' ' ; } |
Count of elements which cannot form any pair whose sum is power of 2 | C ++ Program to count of array elements which do not form a pair with sum equal to a power of 2 with any other array element ; Function to calculate and return the count of elements ; Stores the frequencies of every array element ; Stores the count of removals ; For every element , check if it can form a sum equal to any power of 2 with any other element ; Store pow ( 2 , j ) - a [ i ] ; Check if s is present in the array ; If frequency of s exceeds 1 ; If s has frequency 1 but is different from a [ i ] ; Pair possible ; If no pair possible for the current element ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int powerOfTwo ( int a [ ] , int n ) { map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ a [ i ] ] ++ ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { bool f = false ; for ( int j = 0 ; j < 31 ; j ++ ) { int s = ( 1 << j ) - a [ i ] ; if ( mp . count ( s ) && ( mp [ s ] > 1 || mp [ s ] == 1 && s != a [ i ] ) ) f = true ; } if ( f == false ) count ++ ; } return count ; } int main ( ) { int a [ ] = { 6 , 2 , 11 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << powerOfTwo ( a , n ) ; return 0 ; } |
Construct the Array using given bitwise AND , OR and XOR | C ++ program for the above approach ; Function to find the array ; Loop through all bits in number ; If bit is set in AND then set it in every element of the array ; If bit is not set in AND ; But set in b ( OR ) ; Set bit position in first element ; If bit is not set in c then set it in second element to keep xor as zero for bit position ; Calculate AND , OR and XOR of array ; Check if values are equal or not ; If not , then array is not possible ; Driver Code ; Given Bitwise AND , OR , and XOR ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findArray ( int n , int a , int b , int c ) { int arr [ n + 1 ] = { } ; for ( int bit = 30 ; bit >= 0 ; bit -- ) { int set = a & ( 1 << bit ) ; if ( set ) { for ( int i = 0 ; i < n ; i ++ ) arr [ i ] |= set ; } else { if ( b & ( 1 << bit ) ) { arr [ 0 ] |= ( 1 << bit ) ; if ( ! ( c & ( 1 << bit ) ) ) { arr [ 1 ] |= ( 1 << bit ) ; } } } } int aa = INT_MAX , bb = 0 , cc = 0 ; for ( int i = 0 ; i < n ; i ++ ) { aa &= arr [ i ] ; bb |= arr [ i ] ; cc ^= arr [ i ] ; } if ( a == aa && b == bb && c == cc ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } else cout << " - 1" ; } int main ( ) { int n = 3 , a = 4 , b = 6 , c = 6 ; findArray ( n , a , b , c ) ; return 0 ; } |
Minimum XOR of OR and AND of any pair in the Array | C ++ program for the above approach ; Function to find the minimum value of XOR of AND and OR of any pair in the given array ; Sort the array ; Traverse the array arr [ ] ; Compare and Find the minimum XOR value of an array . ; Return the final answer ; Driver Code ; Given array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxAndXor ( int arr [ ] , int n ) { int ans = INT_MAX ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { ans = min ( ans , arr [ i ] ^ arr [ i + 1 ] ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxAndXor ( arr , N ) ; return 0 ; } |
Count of subarrays of size K with elements having even frequencies | C ++ program to count subarrays of size K with all elements having even frequencies ; Function to return count of required subarrays ; If K is odd ; Not possible to have any such subarrays ; Stores the starting index of every subarrays ; Stores the count of required subarrays ; Stores Xor of the current subarray . ; Xor of first subarray of size K ; If all elements appear even number of times , increase the count of such subarrays ; Remove the starting element from the current subarray ; Traverse the array for the remaining subarrays ; Update Xor by adding the last element of the current subarray ; Increment i ; If currXor becomes 0 , then increment count ; Update currXor by removing the starting element of the current subarray ; Return count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubarray ( int arr [ ] , int K , int N ) { if ( K % 2 != 0 ) return 0 ; if ( N < K ) return 0 ; int start = 0 ; int i = 0 ; int count = 0 ; int currXor = arr [ i ++ ] ; while ( i < K ) { currXor ^= arr [ i ] ; i ++ ; } if ( currXor == 0 ) count ++ ; currXor ^= arr [ start ++ ] ; while ( i < N ) { currXor ^= arr [ i ] ; i ++ ; if ( currXor == 0 ) count ++ ; currXor ^= arr [ start ++ ] ; } return count ; } int main ( ) { int arr [ ] = { 2 , 4 , 4 , 2 , 2 , 4 } ; int K = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( countSubarray ( arr , K , N ) ) ; } |
Count of even and odd set bit Array elements after XOR with K for Q queries | C ++ Program to count number of even and odd set bits elements after XOR with a given element ; Store the count of set bits ; Brian Kernighan 's algorithm ; Function to solve Q queries ; Store set bits in X ; Count set bits of X ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void keep_count ( int arr [ ] , int & even , int & odd , int N ) { int count ; for ( int i = 0 ; i < N ; i ++ ) { count = 0 ; while ( arr [ i ] != 0 ) { arr [ i ] = ( arr [ i ] - 1 ) & arr [ i ] ; count ++ ; } if ( count % 2 == 0 ) even ++ ; else odd ++ ; } return ; } void solveQueries ( int arr [ ] , int n , int q [ ] , int m ) { int even_count = 0 , odd_count = 0 ; keep_count ( arr , even_count , odd_count , n ) ; for ( int i = 0 ; i < m ; i ++ ) { int X = q [ i ] ; int count = 0 ; while ( X != 0 ) { X = ( X - 1 ) & X ; count ++ ; } if ( count % 2 == 0 ) { cout << even_count << " β " << odd_count << " STRNEWLINE " ; } else { cout << odd_count << " β " << even_count << " STRNEWLINE " ; } } } int main ( ) { int arr [ ] = { 2 , 7 , 4 , 5 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int q [ ] = { 3 , 4 , 12 , 6 } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; solveQueries ( arr , n , q , m ) ; return 0 ; } |
Range Queries for finding the Sum of all even parity numbers | C ++ program to find the sum of all Even Parity numbers in the given range ; pref [ ] array to precompute the sum of all Even Parity Numbers ; Function that returns true if count of set bits in x is even ; Parity will store the count of set bits ; Function to precompute the sum of all even parity numbers upto 100000 ; isEvenParity ( ) return the number i if i has even parity else return 0 ; Function to print sum for each query ; Function to print sum of all even parity numbers between [ L , R ] ; Function that pre computes the sum of all even parity numbers ; Iterate over all Queries to print sum ; Driver code ; Queries ; Function that print the sum of all even parity numbers in Range [ L , R ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; int pref [ 100001 ] = { 0 } ; int isEvenParity ( int num ) { int parity = 0 ; int x = num ; while ( x != 0 ) { if ( x & 1 ) parity ++ ; x = x >> 1 ; } if ( parity % 2 == 0 ) return num ; else return 0 ; } void preCompute ( ) { for ( int i = 1 ; i < 100001 ; i ++ ) { pref [ i ] = pref [ i - 1 ] + isEvenParity ( i ) ; } } void printSum ( int L , int R ) { cout << ( pref [ R ] - pref [ L - 1 ] ) << endl ; } void printSum ( int arr [ 2 ] [ 2 ] , int Q ) { preCompute ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } int main ( ) { int N = 2 ; int Q [ 2 ] [ 2 ] = { { 1 , 10 } , { 121 , 211 } } ; printSum ( Q , N ) ; return 0 ; } |
Largest number in the Array having frequency same as value | C ++ solution to the above problem ; Function to find the largest number whose frequency is equal to itself . ; Find the maximum element in the array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findLargestNumber ( vector < int > & arr ) { int k = * max_element ( arr . begin ( ) , arr . end ( ) ) ; int m [ k ] = { } ; for ( auto n : arr ) ++ m [ n ] ; for ( auto n = arr . size ( ) ; n > 0 ; -- n ) { if ( n == m [ n ] ) return n ; } return -1 ; } int main ( ) { vector < int > arr = { 3 , 2 , 5 , 2 , 4 , 5 } ; cout << findLargestNumber ( arr ) << endl ; return 0 ; } |
Largest number in the Array having frequency same as value | C ++ code for the above problem ; Function to find the largest number whose frequency is equal to itself . ; Adding 65536 to keep the count of the current number ; right shifting by 16 bits to find the count of the number i ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findLargestNumber ( vector < int > & arr ) { for ( auto n : arr ) { n &= 0xFFFF ; if ( n <= arr . size ( ) ) { arr [ n - 1 ] += 0x10000 ; } } for ( auto i = arr . size ( ) ; i > 0 ; -- i ) { if ( ( arr [ i - 1 ] >> 16 ) == i ) return i ; } return -1 ; } int main ( ) { vector < int > arr = { 3 , 2 , 5 , 5 , 2 , 4 , 5 } ; cout << findLargestNumber ( arr ) << endl ; return 0 ; } |
Convert numbers into binary representation and add them without carry | C ++ program to add two binary number without carry ; Function returns sum of both the binary number without carry ; XOR of N and M ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int NoCarrySum ( int N , int M ) { return N ^ M ; } int main ( ) { int N = 37 ; int M = 12 ; cout << NoCarrySum ( N , M ) ; return 0 ; } |
Check if all the set bits of the binary representation of N are at least K places away | C ++ program to check if all the set bits of the binary representation of N are at least K places away . ; Initialize check and count with 0 ; The i - th bit is a set bit ; This is the first set bit so , start calculating all the distances between consecutive bits from here ; If count is less than K return false ; Adding the count as the number of zeroes increase between set bits ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool CheckBits ( int N , int K ) { int check = 0 ; int count = 0 ; for ( int i = 31 ; i >= 0 ; i -- ) { if ( ( 1 << i ) & N ) { if ( check == 0 ) { check = 1 ; } else { if ( count < K ) { return false ; } } count = 0 ; } else { count ++ ; } } return true ; } int main ( ) { int N = 5 ; int K = 1 ; if ( CheckBits ( N , K ) ) { cout << " YES " ; } else { cout << " NO " ; } return 0 ; } |
Minimize bits to be flipped in X and Y such that their Bitwise OR is equal to Z | C ++ Program to minimize number of bits to be fipped in X or Y such that their bitwise or is equal to minimize ; This function returns minimum number of bits to be flipped in X and Y to make X | Y = Z ; If current bit in Z is set and is also set in either of X or Y or both ; If current bit in Z is set and is unset in both X and Y ; Set that bit in either X or Y ; If current bit in Z is unset and is set in both X and Y ; Unset the bit in both X and Y ; If current bit in Z is unset and is set in either X or Y ; Unset that set bit ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumFlips ( int X , int Y , int Z ) { int res = 0 ; while ( X > 0 Y > 0 Z > 0 ) { if ( ( ( X & 1 ) || ( Y & 1 ) ) && ( Z & 1 ) ) { X = X >> 1 ; Y = Y >> 1 ; Z = Z >> 1 ; continue ; } else if ( ! ( X & 1 ) && ! ( Y & 1 ) && ( Z & 1 ) ) { res ++ ; } else if ( ( X & 1 ) || ( Y & 1 ) == 1 ) { if ( ( X & 1 ) && ( Y & 1 ) && ! ( Z & 1 ) ) { res += 2 ; } else if ( ( ( X & 1 ) || ( Y & 1 ) ) && ! ( Z & 1 ) ) { res ++ ; } } X = X >> 1 ; Y = Y >> 1 ; Z = Z >> 1 ; } return res ; } int main ( ) { int X = 5 , Y = 8 , Z = 6 ; cout << minimumFlips ( X , Y , Z ) ; return 0 ; } |
Count subsequences with same values of Bitwise AND , OR and XOR | function for finding count of possible subsequence ; creating a map to count the frequency of each element ; store frequency of each element ; iterate through the map ; add all possible combination for key equal zero ; add all ( odd number of elements ) possible combination for key other than zero ; driver function | int countSubseq ( int arr [ ] , int n ) { int count = 0 ; unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ arr [ i ] ] ++ ; for ( auto i : mp ) { if ( i . first == 0 ) count += pow ( 2 , i . second ) - 1 ; else count += pow ( 2 , i . second - 1 ) ; } return count ; } int main ( ) { int arr [ ] = { 2 , 2 , 2 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSubseq ( arr , n ) ; return 0 ; } |
Choose an integer K such that maximum of the xor values of K with all Array elements is minimized | C ++ implementation to find Minimum possible value of the maximum xor in an array by choosing some integer ; Function to calculate Minimum possible value of the Maximum XOR in an array ; base case ; Divide elements into two sections ; Traverse all elements of current section and divide in two groups ; Check if one of the sections is empty ; explore both the possibilities using recursion ; Function to calculate minimum XOR value ; Start recursion from the most significant pos position ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate ( vector < int > & section , int pos ) { if ( pos < 0 ) return 0 ; vector < int > on_section , off_section ; for ( auto el : section ) { if ( ( ( el >> pos ) & 1 ) == 0 ) off_section . push_back ( el ) ; else on_section . push_back ( el ) ; } if ( off_section . size ( ) == 0 ) return calculate ( on_section , pos - 1 ) ; if ( on_section . size ( ) == 0 ) return calculate ( off_section , pos - 1 ) ; return min ( calculate ( off_section , pos - 1 ) , calculate ( on_section , pos - 1 ) ) + ( 1 << pos ) ; } int minXorValue ( int a [ ] , int n ) { vector < int > section ; for ( int i = 0 ; i < n ; i ++ ) section . push_back ( a [ i ] ) ; return calculate ( section , 30 ) ; } int main ( ) { int N = 4 ; int A [ N ] = { 3 , 2 , 5 , 6 } ; cout << minXorValue ( A , N ) ; return 0 ; } |
Program to find the Nth natural number with exactly two bits set | C ++ Code to find the Nth number with exactly two bits set ; Function to find the Nth number with exactly two bits set ; Keep incrementing until we reach the partition of ' N ' stored in bit_L ; set the rightmost bit based on bit_R ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNthNum ( long long int N ) { long long int bit_L = 1 , last_num = 0 ; while ( bit_L * ( bit_L + 1 ) / 2 < N ) { last_num = last_num + bit_L ; bit_L ++ ; } int bit_R = N - last_num - 1 ; cout << ( 1 << bit_L ) + ( 1 << bit_R ) << endl ; } int main ( ) { long long int N = 13 ; findNthNum ( N ) ; return 0 ; } |
XOR of all Prime numbers in an Array at positions divisible by K | C ++ program to find XOR of all Prime numbers in an Array at positions divisible by K ; 0 and 1 are not prime numbers ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to find the required XOR ; To store XOR of the primes ; Traverse the array ; If the number is a prime ; If index is divisible by k ; Print the xor ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000005 NEW_LINE void SieveOfEratosthenes ( vector < bool > & prime ) { prime [ 1 ] = false ; prime [ 0 ] = false ; for ( int p = 2 ; p * p < MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i < MAX ; i += p ) prime [ i ] = false ; } } } void prime_xor ( int arr [ ] , int n , int k ) { vector < bool > prime ( MAX , true ) ; SieveOfEratosthenes ( prime ) ; long long int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { if ( ( i + 1 ) % k == 0 ) { ans ^= arr [ i ] ; } } } cout << ans << endl ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 7 , 11 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; prime_xor ( arr , n , K ) ; return 0 ; } |
Find XOR of all elements in an Array | C ++ program to find the XOR of all elements in the array ; Function to find the XOR of all elements in the array ; Resultant variable ; Iterating through every element in the array ; Find XOR with the result ; Return the XOR ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int xorOfArray ( int arr [ ] , int n ) { int xor_arr = 0 ; for ( int i = 0 ; i < n ; i ++ ) { xor_arr = xor_arr ^ arr [ i ] ; } return xor_arr ; } int main ( ) { int arr [ ] = { 3 , 9 , 12 , 13 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << xorOfArray ( arr , n ) << endl ; return 0 ; } |
Count of even set bits between XOR of two arrays | C ++ program for the above approach ; Function that count the XOR of B [ ] with all the element in A [ ] having even set bit ; Count the set bits in A [ i ] ; check for even or Odd ; To store the count of element for B [ ] such that XOR with all the element in A [ ] having even set bit ; Count set bit for B [ i ] ; check for Even or Odd ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countEvenBit ( int A [ ] , int B [ ] , int n , int m ) { int i , j , cntOdd = 0 , cntEven = 0 ; for ( i = 0 ; i < n ; i ++ ) { int x = __builtin_popcount ( A [ i ] ) ; if ( x & 1 ) { cntEven ++ ; } else { cntOdd ++ ; } } int CountB [ m ] ; for ( i = 0 ; i < m ; i ++ ) { int x = __builtin_popcount ( B [ i ] ) ; if ( x & 1 ) { CountB [ i ] = cntEven ; } else { CountB [ i ] = cntOdd ; } } for ( i = 0 ; i < m ; i ++ ) { cout << CountB [ i ] << ' β ' ; } } int main ( ) { int A [ ] = { 4 , 2 , 15 , 9 , 8 , 8 } ; int B [ ] = { 3 , 4 , 22 } ; countEvenBit ( A , B , 6 , 3 ) ; return 0 ; } |
Check if a Number is Odd or Even using Bitwise Operators | C ++ program to check for even or odd using Bitwise XOR operator ; Returns true if n is even , else odd ; n ^ 1 is n + 1 , then even , else odd ; Driver code | #include <iostream> NEW_LINE using namespace std ; bool isEven ( int n ) { if ( n ^ 1 == n + 1 ) return true ; else return false ; } int main ( ) { int n = 100 ; isEven ( n ) ? cout << " Even " : cout << " Odd " ; return 0 ; } |
Bitwise OR ( | ) of all even number from 1 to N | C ++ implementation of the above approach ; Function to return the bitwise OR of all the even numbers upto N ; Initialize result as 2 ; Driver code | #include <iostream> NEW_LINE using namespace std ; int bitwiseOrTillN ( int n ) { int result = 2 ; for ( int i = 4 ; i <= n ; i = i + 2 ) { result = result | i ; } return result ; } int main ( ) { int n = 10 ; cout << bitwiseOrTillN ( n ) ; return 0 ; } |
Bitwise OR ( | ) of all even number from 1 to N | C ++ implementation of the above approach ; Function to return the bitwise OR of all even numbers upto N ; For value less than 2 ; Count total number of bits in bitwise or all bits will be set except last bit ; Compute 2 to the power bitCount and subtract 2 ; Driver code | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int bitwiseOrTillN ( int n ) { if ( n < 2 ) return 0 ; int bitCount = log2 ( n ) + 1 ; return pow ( 2 , bitCount ) - 2 ; } int main ( ) { int n = 10 ; cout << bitwiseOrTillN ( n ) ; return 0 ; } |
Generating N | C ++ program Generating N - bit Gray Code starting from K ; Function to Generating N - bit Gray Code starting from K ; Generate gray code of corresponding binary number of integer i . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void genSequence ( int n , int val ) { for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int x = i ^ ( i >> 1 ) ^ val ; cout << x << " β " ; } } int main ( ) { int n = 3 , k = 2 ; genSequence ( n , k ) ; return 0 ; } |
Winner in the Rock | C ++ implementation of the approach ; Function to return the winner of the game ; Both the players chose to play the same move ; Player A wins the game ; Function to perform the queries ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string winner ( string moves ) { map < char , int > data ; data [ ' R ' ] = 0 ; data [ ' P ' ] = 1 ; data [ ' S ' ] = 2 ; if ( moves [ 0 ] == moves [ 1 ] ) { return " Draw " ; } if ( ( ( data [ moves [ 0 ] ] | 1 << ( 2 ) ) - ( data [ moves [ 1 ] ] | 0 << ( 2 ) ) ) % 3 ) { return " A " ; } return " B " ; } void performQueries ( string arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << winner ( arr [ i ] ) << endl ; } int main ( ) { string arr [ ] = { " RS " , " SR " , " SP " , " PP " } ; int n = sizeof ( arr ) / sizeof ( string ) ; performQueries ( arr , n ) ; return 0 ; } |
Find the minimum spanning tree with alternating colored edges | C ++ program for the above approach ; Initializing dp of size = ( 2 ^ 18 ) * 18 * 2. ; Recursive Function to calculate Minimum Cost with alternate colour edges ; Base case ; If already calculated ; Masking previous edges as explained in above formula . ; Function to Adjacency List Representation of a Graph ; Function to getCost for the Minimum Spanning Tree Formed ; Assigning maximum possible value . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int graph [ 18 ] [ 18 ] [ 2 ] ; long long dp [ 1 << 18 ] [ 18 ] [ 2 ] ; long long minCost ( int n , int m , int mask , int prev , int col ) { if ( mask == ( ( 1 << n ) - 1 ) ) { return 0 ; } if ( dp [ mask ] [ prev ] [ col == 1 ] != 0 ) { return dp [ mask ] [ prev ] [ col == 1 ] ; } long long ans = 1e9 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < 2 ; j ++ ) { if ( graph [ prev ] [ i ] [ j ] && ! ( mask & ( 1 << i ) ) && ( j != col ) ) { long long z = graph [ prev ] [ i ] [ j ] + minCost ( n , m , mask | ( 1 << i ) , i , j ) ; ans = min ( z , ans ) ; } } } return dp [ mask ] [ prev ] [ col == 1 ] = ans ; } void makeGraph ( vector < pair < pair < int , int > , pair < int , char > > > & vp , int m ) { for ( int i = 0 ; i < m ; i ++ ) { int a = vp [ i ] . first . first - 1 ; int b = vp [ i ] . first . second - 1 ; int cost = vp [ i ] . second . first ; char color = vp [ i ] . second . second ; graph [ a ] [ b ] [ color == ' W ' ] = cost ; graph [ b ] [ a ] [ color == ' W ' ] = cost ; } } int getCost ( int n , int m ) { long long ans = 1e9 ; for ( int i = 0 ; i < n ; i ++ ) { ans = min ( ans , minCost ( n , m , 1 << i , i , 2 ) ) ; } if ( ans != 1e9 ) { return ans ; } else { return -1 ; } } int main ( ) { int n = 3 , m = 4 ; vector < pair < pair < int , int > , pair < int , char > > > vp = { { { 1 , 2 } , { 2 , ' B ' } } , { { 1 , 2 } , { 3 , ' W ' } } , { { 2 , 3 } , { 4 , ' W ' } } , { { 2 , 3 } , { 5 , ' B ' } } } ; makeGraph ( vp , m ) ; cout << getCost ( n , m ) << ' ' ; return 0 ; } |
Maximum number of consecutive 1 's in binary representation of all the array elements | C ++ implementation of the approach ; Function to return the count of maximum consecutive 1 s in the binary representation of x ; Initialize result ; Count the number of iterations to reach x = 0. ; This operation reduces length of every sequence of 1 s by one ; Function to return the count of maximum consecutive 1 s in the binary representation among all the elements of arr [ ] ; To store the answer ; For every element of the array ; Count of maximum consecutive 1 s in the binary representation of the current element ; Update the maximum count so far ; Driver code | #include <iostream> NEW_LINE using namespace std ; int maxConsecutiveOnes ( int x ) { int count = 0 ; while ( x != 0 ) { x = ( x & ( x << 1 ) ) ; count ++ ; } return count ; } int maxOnes ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int currMax = maxConsecutiveOnes ( arr [ i ] ) ; ans = max ( ans , currMax ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << maxOnes ( arr , n ) ; return 0 ; } |
Maximum Bitwise OR pair from a range | C ++ implementation of the approach ; Function to return the maximum bitwise OR possible among all the possible pairs ; Check for every possible pair ; Maximum among all ( i , j ) pairs ; Driver code | #include <climits> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int maxOR ( int L , int R ) { int maximum = INT_MIN ; for ( int i = L ; i < R ; i ++ ) for ( int j = i + 1 ; j <= R ; j ++ ) maximum = max ( maximum , ( i j ) ) ; return maximum ; } int main ( ) { int L = 4 , R = 5 ; cout << maxOR ( L , R ) ; return 0 ; } |
Maximum Bitwise OR pair from a range | C ++ implementation of the approach ; Function to return the maximum bitwise OR possible among all the possible pairs ; If there is only a single value in the range [ L , R ] ; Loop through each bit from MSB to LSB ; MSBs where the bits differ , all bits from that bit are set ; If MSBs are same , then ans bit is same as that of bit of right or left limit ; Driver code | #include <iostream> NEW_LINE using namespace std ; const int MAX = 64 ; int maxOR ( int L , int R ) { if ( L == R ) { return L ; } int ans = 0 ; for ( int i = MAX - 1 ; i >= 0 ; i -- ) { int p , lbit , rbit ; p = 1 << i ; if ( ( rbit == 1 ) && ( lbit == 0 ) ) { ans += ( p << 1 ) - 1 ; break ; } if ( rbit == 1 ) { ans += p ; } } return ans ; } int main ( ) { int L = 4 , R = 5 ; cout << maxOR ( L , R ) ; return 0 ; } |
Longest subsequence with a given AND value | O ( N ) | C ++ implementation of the approach ; Function to return the required length ; To store the filtered numbers ; Filtering the numbers ; If there are no elements to check ; Find the AND of all the filtered elements ; Check if the AND is equal to m ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findLen ( int * arr , int n , int m ) { vector < int > filter ; for ( int i = 0 ; i < n ; i ++ ) if ( ( arr [ i ] & m ) == m ) filter . push_back ( arr [ i ] ) ; if ( filter . size ( ) == 0 ) return 0 ; int c_and = filter [ 0 ] ; for ( int i = 1 ; i < filter . size ( ) ; i ++ ) c_and &= filter [ i ] ; if ( c_and == m ) return filter . size ( ) ; return 0 ; } int main ( ) { int arr [ ] = { 7 , 3 , 3 , 1 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int m = 3 ; cout << findLen ( arr , n , m ) ; return 0 ; } |
Longest sub | C ++ implementation of the approach ; Function to return the required length ; To store the filtered numbers ; Filtering the numbers ; If there are no elements to check ; Find the OR of all the filtered elements ; Check if the OR is equal to m ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findLen ( int * arr , int n , int m ) { vector < int > filter ; for ( int i = 0 ; i < n ; i ++ ) if ( ( arr [ i ] m ) == m ) filter . push_back ( arr [ i ] ) ; if ( filter . size ( ) == 0 ) return 0 ; int c_or = filter [ 0 ] ; for ( int i = 1 ; i < filter . size ( ) ; i ++ ) c_or |= filter [ i ] ; if ( c_or == m ) return filter . size ( ) ; return 0 ; } int main ( ) { int arr [ ] = { 7 , 3 , 3 , 1 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int m = 3 ; cout << findLen ( arr , n , m ) ; return 0 ; } |
Program to toggle K | C ++ program to toggle K - th bit of a number N ; Function to toggle the kth bit of n ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int toggleBit ( int n , int k ) { return ( n ^ ( 1 << ( k - 1 ) ) ) ; } int main ( ) { int n = 5 , k = 2 ; cout << toggleBit ( n , k ) << endl ; return 0 ; } |
Program to clear K | C ++ program to clear K - th bit of a number N ; Function to clear the kth bit of n ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int clearBit ( int n , int k ) { return ( n & ( ~ ( 1 << ( k - 1 ) ) ) ) ; } int main ( ) { int n = 5 , k = 1 ; cout << clearBit ( n , k ) << endl ; return 0 ; } |
Maximize the Expression | Bit Manipulation | C ++ implementation of the approach ; Function to return the value of the maximized expression ; int can have 32 bits ; Consider the ith bit of D to be 1 ; Calculate the value of ( B AND bitOfD ) ; Check if bitOfD satisfies ( B AND D = D ) ; Check if bitOfD can maximize ( A XOR D ) ; Note that we do not need to consider ith bit of D to be 0 because if above condition are not satisfied then value of result will not change which is similar to considering bitOfD = 0 as result XOR 0 = result ; Driver code | #include <iostream> NEW_LINE using namespace std ; #define MAX 32 NEW_LINE int maximizeExpression ( int a , int b ) { int result = a ; for ( int bit = MAX - 1 ; bit >= 0 ; bit -- ) { int bitOfD = 1 << bit ; int x = b & bitOfD ; if ( x == bitOfD ) { int y = result & bitOfD ; if ( y == 0 ) { result = result ^ bitOfD ; } } } return result ; } int main ( ) { int a = 11 , b = 14 ; cout << maximizeExpression ( a , b ) ; return 0 ; } |
Find number of subarrays with XOR value a power of 2 | C ++ Program to count number of subarrays with Bitwise - XOR as power of 2 ; Function to find number of subarrays ; Hash Map to store prefix XOR values ; When no element is selected ; Check for all the powers of 2 , till a MAX value ; Insert Current prefixxor in Hash Map ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE #define MAX 10 NEW_LINE using namespace std ; int findSubarray ( int array [ ] , int n ) { unordered_map < int , int > mp ; mp . insert ( { 0 , 1 } ) ; int answer = 0 ; int preXor = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int value = 1 ; preXor ^= array [ i ] ; for ( int j = 1 ; j <= MAX ; j ++ ) { int Y = value ^ preXor ; if ( mp . find ( Y ) != mp . end ( ) ) { answer += mp [ Y ] ; } value *= 2 ; } if ( mp . find ( preXor ) != mp . end ( ) ) { mp [ preXor ] ++ ; } else { mp . insert ( { preXor , 1 } ) ; } } return answer ; } int main ( ) { int array [ ] = { 2 , 6 , 7 , 5 , 8 } ; int n = sizeof ( array ) / sizeof ( array [ 0 ] ) ; cout << findSubarray ( array , n ) << endl ; return 0 ; } |
Maximum XOR of Two Numbers in an Array | C ++ implementation ; Function to return the maximum xor ; Calculating xor of each pair ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max_xor ( int arr [ ] , int n ) { int maxXor = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { maxXor = max ( maxXor , arr [ i ] ^ arr [ j ] ) ; } } return maxXor ; } int main ( ) { int arr [ ] = { 25 , 10 , 2 , 8 , 5 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << max_xor ( arr , n ) << endl ; return 0 ; } |
Maximum XOR of Two Numbers in an Array | C ++ implementation of the above approach ; Function to return the maximum xor ; set the i 'th bit in mask like 100000, 110000, 111000.. ; Just keep the prefix till i ' th β bit β neglecting β all β β the β bit ' s after i 'th bit ; find two pair in set such that a ^ b = newMaxx which is the highest possible bit can be obtained ; clear the set for next iteration ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max_xor ( int arr [ ] , int n ) { int maxx = 0 , mask = 0 ; set < int > se ; for ( int i = 30 ; i >= 0 ; i -- ) { mask |= ( 1 << i ) ; for ( int i = 0 ; i < n ; ++ i ) { se . insert ( arr [ i ] & mask ) ; } int newMaxx = maxx | ( 1 << i ) ; for ( int prefix : se ) { if ( se . count ( newMaxx ^ prefix ) ) { maxx = newMaxx ; break ; } } se . clear ( ) ; } return maxx ; } int main ( ) { int arr [ ] = { 25 , 10 , 2 , 8 , 5 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << max_xor ( arr , n ) << endl ; return 0 ; } |
Count of triplets that satisfy the given equation | C ++ implementation of the approach ; Function to return the count of required triplets ; First element of the current sub - array ; XOR every element of the current sub - array ; If the XOR becomes 0 then update the count of triplets ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountTriplets ( int * arr , int n ) { int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int first = arr [ i ] ; for ( int j = i + 1 ; j < n ; j ++ ) { first ^= arr [ j ] ; if ( first == 0 ) ans += ( j - i ) ; } } return ans ; } int main ( ) { int arr [ ] = { 2 , 5 , 6 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CountTriplets ( arr , n ) ; return 0 ; } |
Find the Majority Element | Set 3 ( Bit Magic ) | ; Number of bits in the integer ; Variable to calculate majority element ; Loop to iterate through all the bits of number ; Loop to iterate through all elements in array to count the total set bit at position i from right ; If the total set bits exceeds n / 2 , this bit should be present in majority Element . ; iterate through array get the count of candidate majority element ; Verify if the count exceeds n / 2 ; Driver Program | #include <iostream> NEW_LINE using namespace std ; void findMajority ( int arr [ ] , int n ) { int len = sizeof ( int ) * 8 ; int number = 0 ; for ( int i = 0 ; i < len ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] & ( 1 << i ) ) count ++ ; } if ( count > ( n / 2 ) ) number += ( 1 << i ) ; } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == number ) count ++ ; if ( count > ( n / 2 ) ) cout << number ; else cout << " Majority β Element β Not β Present " ; } int main ( ) { int arr [ ] = { 3 , 3 , 4 , 2 , 4 , 4 , 2 , 4 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMajority ( arr , n ) ; return 0 ; } |
Count number of bits to be flipped to convert A to B | Set | C ++ implementation of the approach ; Function to return the count of bits to be flipped to convert a to b ; To store the required count ; Loop until both of them become zero ; Store the last bits in a as well as b ; If the current bit is not same in both the integers ; Right shift both the integers by 1 ; Return the count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countBits ( int a , int b ) { int count = 0 ; while ( a b ) { int last_bit_a = a & 1 ; int last_bit_b = b & 1 ; if ( last_bit_a != last_bit_b ) count ++ ; a = a >> 1 ; b = b >> 1 ; } return count ; } int main ( ) { int a = 10 , b = 7 ; cout << countBits ( a , b ) ; return 0 ; } |
Count Set | CPP program to find number of set bist in a number ; Recursive function to find number of set bist in a number ; Base condition ; If Least significant bit is set ; If Least significant bit is not set ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountSetBits ( int n ) { if ( n == 0 ) return 0 ; if ( ( n & 1 ) == 1 ) return 1 + CountSetBits ( n >> 1 ) ; else return CountSetBits ( n >> 1 ) ; } int main ( ) { int n = 21 ; cout << CountSetBits ( n ) << endl ; return 0 ; } |
Count smaller elements on right side and greater elements on left side using Binary Index Tree | C ++ implementation of the approach ; Function to return the sum of arr [ 0. . index ] This function assumes that the array is preprocessed and partial sums of array elements are stored in BITree [ ] ; Traverse ancestors of BITree [ index ] ; Add current element of BITree to sum ; Move index to parent node in getSum View ; Updates a node in Binary Index Tree ( BITree ) at given index in BITree . The given value ' val ' is added to BITree [ i ] and all of its ancestors in tree . ; Traverse all ancestors and add ' val ' ; Add ' val ' to current node of BI Tree ; Update index to that of parent in update View ; Converts an array to an array with values from 1 to n and relative order of smaller and greater elements remains same . For example , { 7 , - 90 , 100 , 1 } is converted to { 3 , 1 , 4 , 2 } ; Create a copy of arrp [ ] in temp and sort the temp array in increasing order ; Traverse all array elements ; lower_bound ( ) Returns pointer to the first element greater than or equal to arr [ i ] ; Function to find smaller_right array ; Convert arr [ ] to an array with values from 1 to n and relative order of smaller and greater elements remains same . For example , { 7 , - 90 , 100 , 1 } is converted to { 3 , 1 , 4 , 2 } ; Create a BIT with size equal to maxElement + 1 ( Extra one is used so that elements can be directly be used as index ) ; To store smaller elements in right side and greater elements on left side ; Traverse all elements from right . ; Get count of elements smaller than arr [ i ] ; Add current element to BIT ; Print smaller_right array ; Find all left side greater elements ; Get count of elements greater than arr [ i ] ; Add current element to BIT ; Print greater_left array ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getSum ( int BITree [ ] , int index ) { while ( index > 0 ) { sum += BITree [ index ] ; index -= index & ( - index ) ; } return sum ; } void updateBIT ( int BITree [ ] , int n , int index , int val ) { while ( index <= n ) { BITree [ index ] += val ; index += index & ( - index ) ; } } void convert ( int arr [ ] , int n ) { int temp [ n ] ; for ( int i = 0 ; i < n ; i ++ ) temp [ i ] = arr [ i ] ; sort ( temp , temp + n ) ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = lower_bound ( temp , temp + n , arr [ i ] ) - temp + 1 ; } } void findElements ( int arr [ ] , int n ) { convert ( arr , n ) ; int BIT [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) BIT [ i ] = 0 ; int smaller_right [ n ] , greater_left [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { smaller_right [ i ] = getSum ( BIT , arr [ i ] - 1 ) ; updateBIT ( BIT , n , arr [ i ] , 1 ) ; } cout << " Smaller β right : β " ; for ( int i = 0 ; i < n ; i ++ ) cout << smaller_right [ i ] << " β " ; cout << endl ; for ( int i = 1 ; i <= n ; i ++ ) BIT [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { greater_left [ i ] = i - getSum ( BIT , arr [ i ] ) ; updateBIT ( BIT , n , arr [ i ] , 1 ) ; } cout << " Greater β left : β " ; for ( int i = 0 ; i < n ; i ++ ) cout << greater_left [ i ] << " β " ; } int main ( ) { int arr [ ] = { 12 , 1 , 2 , 3 , 0 , 11 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findElements ( arr , n ) ; return 0 ; } |
Sum of Bitwise OR of all pairs in a given array | A Simple C ++ program to compute sum of bitwise OR of all pairs ; Returns value of " arr [ 0 ] β | β arr [ 1 ] β + β arr [ 0 ] β | β arr [ 2 ] β + β . . . β arr [ i ] β | β arr [ j ] β + β . . . . . β arr [ n - 2 ] β | β arr [ n - 1 ] " ; Consider all pairs ( arr [ i ] , arr [ j ) such that i < j ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int pairORSum ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) ans += arr [ i ] | arr [ j ] ; return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << pairORSum ( arr , n ) << endl ; return 0 ; } |
Number of 0 s and 1 s at prime positions in the given array | C ++ implementation of the approach ; Function that returns true if n is prime ; Check from 2 to n ; Function to find the count of 0 s and 1 s at prime indices ; To store the count of 0 s and 1 s ; If current 0 is at prime position ; If current 1 is at prime position ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; for ( int i = 2 ; i < n ; i ++ ) { if ( n % i == 0 ) return false ; } return true ; } void countPrimePosition ( int arr [ ] , int n ) { int c0 = 0 , c1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 && isPrime ( i ) ) c0 ++ ; if ( arr [ i ] == 1 && isPrime ( i ) ) c1 ++ ; } cout << " Number β of β 0s β = β " << c0 << endl ; cout << " Number β of β 1s β = β " << c1 ; } int main ( ) { int arr [ ] = { 1 , 0 , 1 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPrimePosition ( arr , n ) ; return 0 ; } |
Find a sub matrix with maximum XOR | C ++ program to implement the above approach ; Compute the xor of elements from ( 1 , 1 ) to ( i , j ) and store it in prefix_xor [ i ] [ j ] ; xor of submatrix from 1 , 1 to i , j is ( xor of submatrix from 1 , 1 to i - 1 , j ) ^ ( xor of submatrix from 1 , 1 to i , j - 1 ) ^ ( xor of submatrix from 1 , 1 to i - 1 , j - 1 ) ^ arr [ i ] [ j ] ; find the submatrix with maximum xor value ; we need four loops to find all the submatrix of a matrix ; xor of submatrix from i , j to i1 , j1 is ( xor of submatrix from 1 , 1 to i1 , j1 ) ^ ( xor of submatrix from 1 , 1 to i - 1 , j - 1 ) ^ ( xor of submatrix from 1 , 1 to i1 , j - 1 ) ^ ( xor of submatrix from 1 , 1 to i - 1 , j1 ) ; if the xor is greater than maximum value substitute it ; Driver code ; Find the prefix_xor ; Find submatrix with maximum bitwise xor | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 101 NEW_LINE void prefix ( int arr [ N ] [ N ] , int prefix_xor [ N ] [ N ] , int n ) { for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { prefix_xor [ i ] [ j ] = arr [ i ] [ j ] ^ prefix_xor [ i - 1 ] [ j ] ^ prefix_xor [ i ] [ j - 1 ] ^ prefix_xor [ i - 1 ] [ j - 1 ] ; } } } void Max_xor ( int prefix_xor [ N ] [ N ] , int n ) { int max_value = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { for ( int i1 = i ; i1 <= n ; i1 ++ ) { for ( int j1 = j ; j1 <= n ; j1 ++ ) { int x = 0 ; x ^= prefix_xor [ i1 ] [ j1 ] ; x ^= prefix_xor [ i - 1 ] [ j - 1 ] ; x ^= prefix_xor [ i1 ] [ j - 1 ] ; x ^= prefix_xor [ i - 1 ] [ j1 ] ; max_value = max ( max_value , x ) ; } } } } cout << max_value << endl ; } int main ( ) { int arr [ N ] [ N ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int n = 4 ; int prefix_xor [ N ] [ N ] = { 0 } ; prefix ( arr , prefix_xor , n ) ; Max_xor ( prefix_xor , n ) ; return 0 ; } |
Multiply a number by 15 without using * and / operators | C ++ implementation of the approach ; Function to return ( 15 * N ) without using ' * ' or ' / ' operator ; prod = 16 * n ; ( ( 16 * n ) - n ) = 15 * n ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long multiplyByFifteen ( long n ) { long prod = ( n << 4 ) ; prod = prod - n ; return prod ; } int main ( ) { long n = 7 ; cout << multiplyByFifteen ( n ) ; return 0 ; } |
Multiply a number by 15 without using * and / operators | C ++ implementation of the approach ; Function to return ( 15 * N ) without using ' * ' or ' / ' operator ; prod = 8 * n ; Add ( 4 * n ) ; Add ( 2 * n ) ; Add n ; ( 8 * n ) + ( 4 * n ) + ( 2 * n ) + n = ( 15 * n ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long multiplyByFifteen ( long n ) { long prod = ( n << 3 ) ; prod += ( n << 2 ) ; prod += ( n << 1 ) ; prod += n ; return prod ; } int main ( ) { long n = 7 ; cout << multiplyByFifteen ( n ) ; return 0 ; } |
Find a number which give minimum sum when XOR with every number of array of integers | C ++ implementation of the approach ; Function to find an integer X such that the sum of all the array elements after getting XORed with X is minimum ; Finding Maximum element of array ; Find Maximum number of bits required in the binary representation of maximum number so log2 is calculated ; Running loop from p times which is the number of bits required to represent all the elements of the array ; If the bits in same position are set then count ; If count becomes greater than half of size of array then we need to make that bit '0' by setting X bit to '1' ; Again using shift operation to calculate the required number ; Calculate minimized sum ; Print solution ; Driver code | #include <bits/stdc++.h> NEW_LINE #include <cmath> NEW_LINE using namespace std ; void findX ( int arr [ ] , int n ) { int * itr = max_element ( arr , arr + n ) ; int p = log2 ( * itr ) + 1 ; int X = 0 ; for ( int i = 0 ; i < p ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] & ( 1 << i ) ) { count ++ ; } } if ( count > ( n / 2 ) ) { X += 1 << i ; } } long long int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += ( X ^ arr [ i ] ) ; cout << " X β = β " << X << " , β Sum β = β " << sum ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findX ( arr , n ) ; return 0 ; } |
Game Theory in Balanced Ternary Numeral System | ( Moving 3 k steps at a time ) | C ++ implementation of the approach ; Numbers are in range of pow ( 3 , 32 ) ; Conversion of ternary into balanced ternary as start iterating from Least Significant Bit ( i . e 0 th ) , if encountered 0 or 1 , safely skip and pass carry 0 further 2 , replace it to - 1 and pass carry 1 further 3 , replace it to 0 and pass carry 1 further ; Similar to binary conversion ; Driver code ; Moving on to first occupied bit ; Printing ; Print ' Z ' in place of - 1 | #include <bits/stdc++.h> NEW_LINE using namespace std ; int arr [ 32 ] ; void balTernary ( int ter ) { int carry = 0 , base = 10 ; int i = 32 ; while ( ter > 0 ) { int rem = ter % base ; rem = rem + carry ; if ( rem == 0 ) { arr [ i -- ] = 0 ; carry = 0 ; } else if ( rem == 1 ) { arr [ i -- ] = 1 ; carry = 0 ; } else if ( rem == 2 ) { arr [ i -- ] = -1 ; carry = 1 ; } else if ( rem == 3 ) { arr [ i -- ] = 0 ; carry = 1 ; } ter = ter / base ; } if ( carry == 1 ) arr [ i ] = 1 ; } int ternary ( int number ) { int ans = 0 , rem = 1 , base = 1 ; while ( number > 0 ) { rem = number % 3 ; ans = ans + rem * base ; number /= 3 ; base = base * 10 ; } return ans ; } int main ( ) { int number = 3056 ; int ter = ternary ( number ) ; memset ( arr , 0 , sizeof ( arr ) ) ; balTernary ( ter ) ; int i = 0 ; while ( arr [ i ] == 0 ) { i ++ ; } for ( int j = i ; j <= 32 ; j ++ ) { if ( arr [ j ] == -1 ) cout << ' Z ' ; else cout << arr [ j ] ; } return 0 ; } |
Minimum value among AND of elements of every subset of an array | C ++ program for the above approach ; Find AND of whole array ; Print the answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minAND ( int arr [ ] , int n ) { int s = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { s = s & arr [ i ] ; } cout << ( s ) << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; minAND ( arr , n ) ; } |
Modify a binary array to Bitwise AND of all elements as 1 | C ++ implementation of the above approach ; Function to check if it is possible or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) if ( a [ i ] ) return true ; return false ; } int main ( ) { int a [ ] = { 0 , 1 , 0 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; check ( a , n ) ? cout << " YES STRNEWLINE " : cout << " NO STRNEWLINE " ; return 0 ; } |
Find array using different XORs of elements in groups of size 4 | C ++ implementation of the approach ; Utility function to print the contents of the array ; Function to find the required array ; Print the array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } void findArray ( int q [ ] , int n ) { int arr [ n ] , ans ; for ( int k = 0 , j = 0 ; j < n / 4 ; j ++ ) { ans = q [ k ] ^ q [ k + 3 ] ; arr [ k + 1 ] = q [ k + 1 ] ^ ans ; arr [ k + 2 ] = q [ k + 2 ] ^ ans ; arr [ k ] = q [ k ] ^ ( ( arr [ k + 1 ] ) ^ ( arr [ k + 2 ] ) ) ; arr [ k + 3 ] = q [ k + 3 ] ^ ( arr [ k + 1 ] ^ arr [ k + 2 ] ) ; k += 4 ; } printArray ( arr , n ) ; } int main ( ) { int q [ ] = { 4 , 1 , 7 , 0 } ; int n = sizeof ( q ) / sizeof ( q [ 0 ] ) ; findArray ( q , n ) ; return 0 ; } |
Count of values of x <= n for which ( n XOR x ) = ( n | C ++ implementation of the approach ; Function to return the count of valid values of x ; Convert n into binary String ; To store the count of 1 s ; If current bit is 1 ; Calculating answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countX ( int n ) { string binary = bitset < 8 > ( n ) . to_string ( ) ; int count = 0 ; for ( int i = 0 ; i < binary . length ( ) ; i ++ ) { if ( binary . at ( i ) == '1' ) count ++ ; } int answer = ( int ) pow ( 2 , count ) ; return answer ; } int main ( ) { int n = 5 ; int answer = countX ( n ) ; cout << ( answer ) ; } |
Check if the binary representation of a number has equal number of 0 s and 1 s in blocks | C ++ program to check if a number has same counts of 0 s and 1 s in every block . ; function to convert decimal to binary ; Count same bits in last block ; If n is 0 or it has all 1 s , then it is not considered to have equal number of 0 s and 1 s in blocks . ; Count same bits in all remaining blocks . ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; bool isEqualBlock ( int n ) { int first_bit = n % 2 ; int first_count = 1 ; n = n / 2 ; while ( n % 2 == first_bit && n > 0 ) { n = n / 2 ; first_count ++ ; } if ( n == 0 ) return false ; while ( n > 0 ) { int first_bit = n % 2 ; int curr_count = 1 ; n = n / 2 ; while ( n % 2 == first_bit ) { n = n / 2 ; curr_count ++ ; } if ( curr_count != first_count ) return false ; } return true ; } int main ( ) { int n = 51 ; if ( isEqualBlock ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
First and Last Three Bits | C ++ implementation of the approach ; Function to print the first and last 3 bits equivalent decimal number ; Converting n to binary ; Length of the array has to be at least 3 ; Convert first three bits to decimal ; Print the decimal ; Convert last three bits to decimal ; Print the decimal ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void binToDecimal3 ( int n ) { int a [ 64 ] = { 0 } ; int x = 0 , i ; for ( i = 0 ; n > 0 ; i ++ ) { a [ i ] = n % 2 ; n /= 2 ; } x = ( i < 3 ) ? 3 : i ; int d = 0 , p = 0 ; for ( int i = x - 3 ; i < x ; i ++ ) d += a [ i ] * pow ( 2 , p ++ ) ; cout << d << " β " ; d = 0 ; p = 0 ; for ( int i = 0 ; i < 3 ; i ++ ) d += a [ i ] * pow ( 2 , p ++ ) ; cout << d ; } int main ( ) { int n = 86 ; binToDecimal3 ( n ) ; return 0 ; } |
First and Last Three Bits | C ++ implementation of the approach ; Function to print the first and last 3 bits equivalent decimal number ; Number formed from last three bits ; Let us get first three bits in n ; Number formed from first three bits ; Printing result ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void binToDecimal3 ( int n ) { int last_3 = ( ( n & 4 ) + ( n & 2 ) + ( n & 1 ) ) ; n = n >> 3 ; while ( n > 7 ) n = n >> 1 ; int first_3 = ( ( n & 4 ) + ( n & 2 ) + ( n & 1 ) ) ; cout << first_3 << " β " << last_3 ; } int main ( ) { int n = 86 ; binToDecimal3 ( n ) ; return 0 ; } |
Count of numbers which can be made power of 2 by given operation | C ++ implementation of the approach ; Function that returns true if x is a power of 2 ; If x & ( x - 1 ) = 0 then x is a power of 2 ; Function to return the required count ; If a [ i ] or ( a [ i ] + 1 ) is a power of 2 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfTwo ( int x ) { if ( x == 0 ) return false ; if ( ! ( x & ( x - 1 ) ) ) return true ; else return false ; } int countNum ( int a [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isPowerOfTwo ( a [ i ] ) || isPowerOfTwo ( a [ i ] + 1 ) ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 5 , 6 , 9 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countNum ( arr , n ) ; return 0 ; } |
Sum of elements from an array having even parity | C ++ program to find the sum of the elements from an array which have even parity ; Function that returns true if x has even parity ; We basically count set bits https : www . geeksforgeeks . org / count - set - bits - in - an - integer / ; Function to return the sum of the elements from an array which have even parity ; If a [ i ] has even parity ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkEvenParity ( int x ) { int parity = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; parity ++ ; } if ( parity % 2 == 0 ) return true ; else return false ; } long sumlist ( int a [ ] , int n ) { long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( checkEvenParity ( a [ i ] ) ) sum += a [ i ] ; } return sum ; } int main ( ) { int arr [ ] = { 2 , 4 , 3 , 5 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << sumlist ( arr , n ) ; return 0 ; } |
Subsets and Splits