text
stringlengths
17
3.65k
code
stringlengths
60
5.26k
How to avoid overflow in modular multiplication ? | C # program for modular multiplication without any overflow ; To compute ( a * b ) % mod ; long res = 0 ; Initialize result ; If b is odd , add ' a ' to result ; Multiply ' a ' with 2 ; Divide b by 2 ; Return result ; Driver code
using System ; class GFG { static long mulmod ( long a , long b , long mod ) { a = a % mod ; while ( b > 0 ) { if ( b % 2 == 1 ) { res = ( res + a ) % mod ; } a = ( a * 2 ) % mod ; b /= 2 ; } return res % mod ; } public static void Main ( String [ ] args ) { long a = 9223372036854775807L , b = 9223372036854775807L ; Console . WriteLine ( mulmod ( a , b , 100000000000L ) ) ; } }
Count inversions in an array | Set 3 ( Using BIT ) | C # program to count inversions using Binary Indexed Tree ; Returns sum of arr [ 0. . index ] . This function assumes that the array is preprocessed and partial sums of array elements are stored in BITree [ ] . ; Initialize result ; 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 ] ; Returns inversion count arr [ 0. . n - 1 ] ; Initialize result ; 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 ) ; Traverse all elements from right . ; Get count of elements smaller than arr [ i ] ; Add current element to BIT ; Driver code
using System ; class GFG { static int getSum ( int [ ] BITree , int index ) { int sum = 0 ; while ( index > 0 ) { sum += BITree [ index ] ; index -= index & ( - index ) ; } return sum ; } static void updateBIT ( int [ ] BITree , int n , int index , int val ) { while ( index <= n ) { BITree [ index ] += val ; index += index & ( - index ) ; } } static void convert ( int [ ] arr , int n ) { int [ ] temp = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) temp [ i ] = arr [ i ] ; Array . Sort ( temp ) ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = lower_bound ( temp , 0 , n , arr [ i ] ) + 1 ; } } static int lower_bound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) low = middle + 1 ; else high = middle ; } return low ; } static int getInvCount ( int [ ] arr , int n ) { int invcount = 0 ; convert ( arr , n ) ; int [ ] BIT = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) BIT [ i ] = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { invcount += getSum ( BIT , arr [ i ] - 1 ) ; updateBIT ( BIT , n , arr [ i ] , 1 ) ; } return invcount ; } public static void Main ( String [ ] args ) { int [ ] arr = { 8 , 4 , 2 , 1 } ; int n = arr . Length ; Console . Write ( " Number ▁ of ▁ inversions ▁ are ▁ : ▁ " + getInvCount ( arr , n ) ) ; } }
Compute n ! under modulo p | Simple method to compute n ! % p ; Returns value of n ! % p ; Driver program
using System ; class GFG { static int modFact ( int n , int p ) { if ( n >= p ) return 0 ; int result = 1 ; for ( int i = 1 ; i <= n ; i ++ ) result = ( result * i ) % p ; return result ; } static void Main ( ) { int n = 25 , p = 29 ; Console . Write ( modFact ( n , p ) ) ; } }
Chinese Remainder Theorem | Set 2 ( Inverse Modulo based Implementation ) | A C # program to demonstrate working of Chinese remainder Theorem ; Returns modulo inverse of ' a ' with respect to ' m ' using extended Euclid Algorithm . Refer below post for details : https : www . geeksforgeeks . org / multiplicative - inverse - under - modulo - m / ; Apply extended Euclid Algorithm ; q is quotient ; m is remainder now , process same as euclid 's algo ; Make x1 positive ; k is size of num [ ] and rem [ ] . Returns the smallest number x such that : x % num [ 0 ] = rem [ 0 ] , x % num [ 1 ] = rem [ 1 ] , ... ... ... ... ... ... x % num [ k - 2 ] = rem [ k - 1 ] Assumption : Numbers in num [ ] are pairwise coprime ( gcd for every pair is 1 ) ; Compute product of all numbers ; Initialize result ; Apply above formula ; Driver Code
using System ; class GFG { static int inv ( int a , int m ) { int m0 = m , t , q ; int x0 = 0 , x1 = 1 ; if ( m == 1 ) return 0 ; while ( a > 1 ) { q = a / m ; t = m ; m = a % m ; a = t ; t = x0 ; x0 = x1 - q * x0 ; x1 = t ; } if ( x1 < 0 ) x1 += m0 ; return x1 ; } static int findMinX ( int [ ] num , int [ ] rem , int k ) { int prod = 1 ; for ( int i = 0 ; i < k ; i ++ ) prod *= num [ i ] ; int result = 0 ; for ( int i = 0 ; i < k ; i ++ ) { int pp = prod / num [ i ] ; result += rem [ i ] * inv ( pp , num [ i ] ) * pp ; } return result % prod ; } static public void Main ( ) { int [ ] num = { 3 , 4 , 5 } ; int [ ] rem = { 2 , 3 , 1 } ; int k = num . Length ; Console . WriteLine ( " x ▁ is ▁ " + findMinX ( num , rem , k ) ) ; } }
Chinese Remainder Theorem | Set 1 ( Introduction ) | C # program to demonstrate working of Chinise remainder Theorem ; k is size of num [ ] and rem [ ] . Returns the smallest number x such that : x % num [ 0 ] = rem [ 0 ] , x % num [ 1 ] = rem [ 1 ] , ... ... ... ... ... ... x % num [ k - 2 ] = rem [ k - 1 ] Assumption : Numbers in num [ ] are pairwise coprime ( gcd for every pair is 1 ) ; Initialize result ; As per the Chinese remainder theorem , this loop will always break . ; Check if remainder of x % num [ j ] is rem [ j ] or not ( for all j from 0 to k - 1 ) ; If all remainders matched , we found x ; Else try next number ; Driver code
using System ; class GFG { static int findMinX ( int [ ] num , int [ ] rem , int k ) { int x = 1 ; while ( true ) { int j ; for ( j = 0 ; j < k ; j ++ ) if ( x % num [ j ] != rem [ j ] ) break ; if ( j == k ) return x ; x ++ ; } } public static void Main ( ) { int [ ] num = { 3 , 4 , 5 } ; int [ ] rem = { 2 , 3 , 1 } ; int k = num . Length ; Console . WriteLine ( " x ▁ is ▁ " + findMinX ( num , rem , k ) ) ; } }
Compute nCr % p | Set 2 ( Lucas Theorem ) | A Lucas Theorem based solution to compute nCr % p ; Returns nCr % p . In this Lucas Theorem based program , this function is only called for n < p and r < p . ; The array C is going to store last row of pascal triangle at the end . And last entry of last row is nCr ; One by constructs remaining rows of Pascal Triangle from top to bottom ; Fill entries of current row using previous row values ; nCj = ( n - 1 ) Cj + ( n - 1 ) C ( j - 1 ) ; ; Lucas Theorem based function that returns nCr % p . This function works like decimal to binary conversion recursive function . First we compute last digits of n and r in base p , then recur for remaining digits ; Base case ; Compute last digits of n and r in base p ; Compute result for last digits computed above , and for remaining digits . Multiply the two results and compute the result of multiplication in modulo p . return ( nCrModpLucas ( n / p , r / p , p ) * Last digits of n and r nCrModpDP ( ni , ri , p ) ) % p ; Remaining digits ; Driver Code
using System ; class GFG { static int nCrModpDP ( int n , int r , int p ) { int [ ] C = new int [ r + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = Math . Min ( i , r ) ; j > 0 ; j -- ) C [ j ] = ( C [ j ] + C [ j - 1 ] ) % p ; } return C [ r ] ; } static int nCrModpLucas ( int n , int r , int p ) { if ( r == 0 ) return 1 ; int ni = n % p ; int ri = r % p ; } public static void Main ( ) { int n = 1000 , r = 900 , p = 13 ; Console . Write ( " Value ▁ of ▁ nCr ▁ % ▁ p ▁ is ▁ " + nCrModpLucas ( n , r , p ) ) ; } }
Fibonacci Coding | C # program for Fibonacci Encoding of a positive integer n ; To limit on the largest Fibonacci number to be used ; Array to store fibonacci numbers . fib [ i ] is going to store ( i + 2 ) 'th Fibonacci number ; Stores values in fib and returns index of the largest fibonacci number smaller than n . ; Fib [ 0 ] stores 2 nd Fibonacci No . ; Fib [ 1 ] stores 3 rd Fibonacci No . ; Keep Generating remaining numbers while previously generated number is smaller ; Return index of the largest fibonacci number smaller than or equal to n . Note that the above loop stopped when fib [ i - 1 ] became larger . ; Returns pointer to the char string which corresponds to code for n ; Allocate memory for codeword ; Index of the largest Fibonacci f <= n ; Mark usage of Fibonacci f ( 1 bit ) ; Subtract f from n ; Move to Fibonacci just smaller than f ; Mark all Fibonacci > n as not used ( 0 bit ) , progress backwards ; Additional '1' bit ; Return pointer to codeword ; Driver code
using System ; class GFG { public static int N = 30 ; public static int [ ] fib = new int [ N ] ; public static int largestFiboLessOrEqual ( int n ) { fib [ 0 ] = 1 ; fib [ 1 ] = 2 ; int i ; for ( i = 2 ; fib [ i - 1 ] <= n ; i ++ ) { fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] ; } return ( i - 2 ) ; } public static String fibonacciEncoding ( int n ) { int index = largestFiboLessOrEqual ( n ) ; char [ ] codeword = new char [ index + 3 ] ; int i = index ; while ( n > 0 ) { codeword [ i ] = '1' ; n = n - fib [ i ] ; i = i - 1 ; while ( i >= 0 && fib [ i ] > n ) { codeword [ i ] = '0' ; i = i - 1 ; } } codeword [ index + 1 ] = '1' ; codeword [ index + 2 ] = ' \0' ; string str = new string ( codeword ) ; return str ; } static public void Main ( ) { int n = 143 ; Console . WriteLine ( " Fibonacci ▁ code ▁ word ▁ for ▁ " + n + " ▁ is ▁ " + fibonacciEncoding ( n ) ) ; } }
Print all Good numbers in given range | C # program to print good numbers in a given range [ L , R ] ; Function to check whether n is a good number and doesn ' t ▁ contain ▁ digit ▁ ' d ' ; Get last digit and initialize sum from right side ; If last digit is d , return ; Traverse remaining digits ; Current digit ; If digit is d or digit is less than or equal to sum of digits on right side ; Update sum and n ; Print Good numbers in range [ L , R ] ; Traverse all numbers in given range ; If current numbers is good , print it ; Driver program ; Print good numbers in [ L , R ]
using System ; class GFG { static bool isValid ( int n , int d ) { int digit = n % 10 ; int sum = digit ; if ( digit == d ) return false ; n /= 10 ; while ( n > 0 ) { digit = n % 10 ; if ( digit == d digit <= sum ) return false ; else { sum += digit ; n /= 10 ; } } return true ; } static void printGoodNumber ( int L , int R , int d ) { for ( int i = L ; i <= R ; i ++ ) { if ( isValid ( i , d ) ) Console . Write ( i + " ▁ " ) ; } } public static void Main ( ) { int L = 410 , R = 520 , d = 3 ; printGoodNumber ( L , R , d ) ; } }
Count number of squares in a rectangle | C # program to count squares in a rectangle of size m x n ; Returns count of all squares in a rectangle of size m x n ; If n is smaller , swap m and n ; Now n is greater dimension , apply formula ; Driver Code
using System ; class GFG { static int countSquares ( int m , int n ) { if ( n < m ) { int temp = m ; m = n ; n = temp ; } return n * ( n + 1 ) * ( 3 * m - n + 1 ) / 6 ; } public static void Main ( String [ ] args ) { int m = 4 ; int n = 3 ; Console . Write ( " Count ▁ of ▁ squares ▁ is ▁ " + countSquares ( m , n ) ) ; } }
Zeckendorf 's Theorem (Non | C # program for Zeckendorf 's theorem. It finds the representation of n as sum of non-neighbouring Fibonacci Numbers. ; Corner cases ; Find the greatest Fibonacci Number smaller than n . ; Prints Fibonacci Representation of n using greedy algorithm ; Find the greates Fibonacci Number smallerthan or equal to n ; Print the found fibonacci number ; Reduce n ; Driver method
using System ; class GFG { public static 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 ; } public static void printFibRepresntation ( int n ) { while ( n > 0 ) { int f = nearestSmallerEqFib ( n ) ; Console . Write ( f + " ▁ " ) ; n = n - f ; } } public static void Main ( ) { int n = 40 ; Console . WriteLine ( " Non - neighbouring ▁ Fibonacci ▁ " + " ▁ Representation ▁ of ▁ " + n + " ▁ is " ) ; printFibRepresntation ( n ) ; } }
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 code
using System ; class GFG { static int [ , , ] dp = new int [ 5001 , 5001 , 5 ] ; static 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 ) ; } static int countWays ( int n ) { for ( int i = 0 ; i < 5001 ; i ++ ) { for ( int j = 0 ; j < 5001 ; j ++ ) { for ( int l = 0 ; l < 5 ; l ++ ) dp [ i , j , l ] = - 1 ; } } return countWaysUtil ( n , 4 , 1 ) ; } public static void Main ( String [ ] args ) { int n = 8 ; Console . WriteLine ( countWays ( n ) ) ; } }
Segmented Sieve | This functions finds all primes smaller than ' limit ' using simple sieve of eratosthenes . ; Create a boolean array " mark [ 0 . . limit - 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 . ; One by one traverse all numbers so that their multiples can be marked as composite . ; If p is not changed , then it is a prime ; Update all multiples of p ; Print all prime numbers and store them in prime
static void simpleSieve ( int limit ) { bool [ ] mark = new bool [ limit ] ; Array . Fill ( mark , 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 ) Console . Write ( p + " ▁ " ) ; }
Segmented Sieve | C # program to print print all primes smaller than n using segmented sieve ; This methid 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 . get ( i ) ( divisible by prime . get ( i ) ) For example , if low is 31 and prime . get ( i ) is 3 , we start with 33. ; Mark multiples of prime . get ( 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 code
using System ; using System . Collections ; class GFG { static void simpleSieve ( int limit , ArrayList prime ) { bool [ ] mark = new bool [ limit + 1 ] ; for ( int i = 0 ; i < mark . Length ; i ++ ) mark [ i ] = 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 . Add ( p ) ; Console . Write ( p + " ▁ " ) ; } } } static void segmentedSieve ( int n ) { int limit = ( int ) ( Math . Floor ( Math . Sqrt ( n ) ) + 1 ) ; ArrayList prime = new ArrayList ( ) ; simpleSieve ( limit , prime ) ; int low = limit ; int high = 2 * limit ; while ( low < n ) { if ( high >= n ) high = n ; bool [ ] mark = new bool [ limit + 1 ] ; for ( int i = 0 ; i < mark . Length ; i ++ ) mark [ i ] = true ; for ( int i = 0 ; i < prime . Count ; i ++ ) { int loLim = ( ( int ) Math . Floor ( ( double ) ( low / ( int ) prime [ i ] ) ) * ( int ) prime [ i ] ) ; if ( loLim < low ) loLim += ( int ) prime [ i ] ; for ( int j = loLim ; j < high ; j += ( int ) prime [ i ] ) mark [ j - low ] = false ; } for ( int i = low ; i < high ; i ++ ) if ( mark [ i - low ] == true ) Console . Write ( i + " ▁ " ) ; low = low + limit ; high = high + limit ; } } static void Main ( ) { int n = 100 ; Console . WriteLine ( " Primes ▁ smaller ▁ than ▁ " + n + " : " ) ; segmentedSieve ( n ) ; } }
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
using System ; public class GFG { static void printTwins ( int low , int high ) { bool [ ] prime = new bool [ high + 1 ] ; bool twin = false ; for ( int i = 0 ; i < prime . Length ; i ++ ) { prime [ i ] = true ; } prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p <= Math . Floor ( Math . 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 ] ) { int a = i + 2 ; Console . Write ( " Smallest ▁ twins ▁ in ▁ given ▁ range : ▁ ( " + i + " , ▁ " + a + " ) " ) ; twin = true ; break ; } } if ( twin == false ) { Console . WriteLine ( " No ▁ such ▁ pair ▁ exists " ) ; } } public static void Main ( ) { printTwins ( 10 , 100 ) ; } }
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 Code
using System ; using System . Collections . Generic ; class GFG { static bool isFancy ( String num ) { Dictionary < char , char > fp = new Dictionary < char , char > ( ) ; fp . Add ( '0' , '0' ) ; fp . Add ( '1' , '1' ) ; fp . Add ( '6' , '9' ) ; fp . Add ( '8' , '8' ) ; fp . Add ( '9' , '6' ) ; int n = num . Length ; int l = 0 , r = n - 1 ; while ( l <= r ) { if ( ! fp . ContainsKey ( num [ l ] ) fp [ num [ l ] ] != num [ r ] ) return false ; l ++ ; r -- ; } return true ; } public static void Main ( String [ ] args ) { String str = "9088806" ; if ( isFancy ( str ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Find Next Sparse Number | C # program to find next sparse number ; Find binary representation of x and store it in bin . get ( ] . bin . get ( 0 ] contains least significant bit ( LSB ) , next bit is in bin . get ( 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 . get ( ] ; Driver program
using System ; using System . Collections ; class GFG { static int nextSparse ( int x ) { ArrayList bin = new ArrayList ( ) ; while ( x != 0 ) { bin . Add ( x & 1 ) ; x >>= 1 ; } bin . Add ( 0 ) ; int last_final = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( ( int ) bin [ i ] == 1 && ( int ) bin [ i - 1 ] == 1 && ( int ) 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 += ( int ) bin [ i ] * ( 1 << i ) ; return ans ; } static void Main ( ) { int x = 38 ; Console . WriteLine ( " Next ▁ Sparse ▁ Number ▁ is ▁ " + nextSparse ( x ) ) ; } }
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 Math . Pow ( 2 , add ) - 1 - sub ; Driver code
using System ; using System . Collections . Generic ; class GFG { static void ccountSubsets ( int [ ] arr , int n , int [ ] gcd , int m ) { Dictionary < int , int > freq = new Dictionary < int , int > ( ) ; Dictionary < int , int > subsets = new Dictionary < int , int > ( ) ; int arrMax = 0 ; for ( int i = 0 ; i < n ; i ++ ) { arrMax = Math . Max ( arrMax , arr [ i ] ) ; if ( freq . ContainsKey ( arr [ i ] ) ) { freq . Add ( arr [ i ] , freq [ arr [ i ] ] + 1 ) ; } else { freq . Add ( arr [ i ] , 1 ) ; } } for ( int i = arrMax ; i >= 1 ; i -- ) { int sub = 0 ; int add = 0 ; if ( freq . ContainsKey ( i ) ) add = freq [ i ] ; for ( int j = 2 ; j * i <= arrMax ; j ++ ) { if ( freq . ContainsKey ( i * j ) ) add += freq [ j * i ] ; sub += subsets [ j * i ] ; } subsets . Add ( i , ( 1 << add ) - 1 - sub ) ; } for ( int i = 0 ; i < m ; i ++ ) Console . Write ( " Number ▁ of ▁ subsets ▁ with ▁ gcd ▁ " + gcd [ i ] + " ▁ is ▁ " + subsets [ gcd [ i ] ] + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int [ ] gcd = { 2 , 3 } ; int [ ] arr = { 9 , 6 , 2 } ; int n = arr . Length ; int m = gcd . Length ; ccountSubsets ( arr , n , gcd , m ) ; } }
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 Code
using System ; class GFG { static 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 ) ) == 0 ) count ++ ; ans += ( count * ( n - count ) * 2 ) ; } return ans ; } public static void Main ( ) { int [ ] arr = { 1 , 3 , 5 } ; int n = arr . Length ; Console . Write ( sumBitDifferences ( arr , n ) ) ; } }
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 program
using System ; class GFG { static void printArr ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] ) ; Console . WriteLine ( ) ; } static 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 ++ ; } } static void generate ( int x ) { int [ ] arr = new int [ x ] ; generateUtil ( x , arr , 0 , 0 ) ; } public static void Main ( ) { int x = 5 ; generate ( x ) ; } }
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
class GFG { static bool isPerfect ( int n ) { int sum = 1 ; for ( 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 ; } static void Main ( ) { System . Console . WriteLine ( " Below ▁ are ▁ all ▁ perfect " + " numbers ▁ till ▁ 10000" ) ; for ( int n = 2 ; n < 10000 ; n ++ ) if ( isPerfect ( n ) ) System . Console . WriteLine ( n + " ▁ is ▁ a ▁ perfect ▁ number " ) ; } }
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 code
using System ; class GFG { static bool checkUtil ( int num , int dig , int i ) { if ( dig == 1 && num < i ) return true ; if ( dig > 1 && num >= i ) return checkUtil ( ( num / i ) , -- dig , i ) ; return false ; } static bool check ( int num , int dig ) { for ( int i = 2 ; i <= 32 ; i ++ ) if ( checkUtil ( num , dig , i ) ) return true ; return false ; } public static void Main ( ) { int num = 8 ; int dig = 3 ; if ( check ( num , dig ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
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 code
using System ; public class GFG { static 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 ; } public static void Main ( ) { String num = "12316767678678" ; Console . WriteLine ( mod ( num , 10 ) ) ; } }
Modular multiplicative inverse | C # program to find modular inverse of a under modulo m ; A naive method to find modulor multiplicative inverse of ' a ' under modulo ' m ' ; Driver Code ; Function call
using System ; class GFG { static int modInverse ( int a , int m ) { for ( int x = 1 ; x < m ; x ++ ) if ( ( ( a % m ) * ( x % m ) ) % m == 1 ) return x ; return 1 ; } public static void Main ( ) { int a = 3 , m = 11 ; Console . WriteLine ( modInverse ( a , m ) ) ; } }
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 x and y ; Make x positive ; Driver Code ; Function call
using System ; class GFG { static 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 ; } public static void Main ( ) { int a = 3 , m = 11 ; Console . WriteLine ( " Modular ▁ multiplicative ▁ " + " inverse ▁ is ▁ " + modInverse ( a , m ) ) ; } }
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 code
using System ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int phi ( int n ) { int result = 1 ; for ( int i = 2 ; i < n ; i ++ ) if ( gcd ( i , n ) == 1 ) result ++ ; return result ; } public static void Main ( ) { for ( int n = 1 ; n <= 10 ; n ++ ) Console . WriteLine ( " phi ( " + n + " ) ▁ = ▁ " + phi ( n ) ) ; } }
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
using System ; class GFG { static 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 *= ( float ) ( 1.0 - ( 1.0 / ( float ) p ) ) ; } } if ( n > 1 ) result *= ( float ) ( 1.0 - ( 1.0 / ( float ) n ) ) ; return ( int ) result ; } public static void Main ( ) { int n ; for ( n = 1 ; n <= 10 ; n ++ ) Console . WriteLine ( " phi ( " + n + " ) ▁ = ▁ " + phi ( n ) ) ; } }
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
using System ; class GFG { static int getRemainder ( int num , int divisor ) { while ( num >= divisor ) num -= divisor ; return num ; } public static void Main ( String [ ] args ) { int num = 100 , divisor = 7 ; Console . WriteLine ( getRemainder ( num , divisor ) ) ; } }
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
using System ; class GFG { static int factorial ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res *= i ; return res ; } static double sum ( int n ) { double sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += 1.0 / factorial ( i ) ; return sum ; } public static void Main ( ) { int n = 5 ; Console . WriteLine ( sum ( n ) ) ; } }
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
using System ; class GFG { static long binomialCoeff ( int n , int k ) { long res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } static long catalan ( int n ) { long c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } static long findWays ( int n ) { if ( ( n & 1 ) != 0 ) return 0 ; return catalan ( n / 2 ) ; } public static void Main ( ) { int n = 6 ; Console . Write ( " Total ▁ possible ▁ expressions " + " of ▁ length ▁ " + n + " ▁ is ▁ " + findWays ( 6 ) ) ; } }
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
using System ; class GFG { static bool isOperand ( char c ) { return ( c >= '0' && c <= '9' ) ; } static int value ( char c ) { return ( int ) ( c - '0' ) ; } static int evaluate ( string exp ) { if ( exp . Length == 0 ) return - 1 ; int res = value ( exp [ 0 ] ) ; for ( int i = 1 ; i < exp . Length ; i += 2 ) { char opr = exp [ i ] , opd = exp [ i + 1 ] ; if ( isOperand ( opd ) == false ) 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 ; } static void Main ( ) { string expr1 = "1 + 2*5 + 3" ; int res = evaluate ( expr1 ) ; if ( res == - 1 ) Console . WriteLine ( expr1 + " ▁ is ▁ Invalid " ) ; else Console . WriteLine ( " Value ▁ of ▁ " + expr1 + " ▁ is ▁ " + res ) ; string expr2 = "1 + 2*3" ; res = evaluate ( expr2 ) ; if ( res == - 1 ) Console . WriteLine ( expr2 + " ▁ is ▁ Invalid " ) ; else Console . WriteLine ( " Value ▁ of ▁ " + expr2 + " ▁ is ▁ " + res ) ; string expr3 = "4-2 + 6*3" ; res = evaluate ( expr3 ) ; if ( res == - 1 ) Console . WriteLine ( expr3 + " ▁ is ▁ Invalid " ) ; else Console . WriteLine ( " Value ▁ of ▁ " + expr3 + " ▁ is ▁ " + res ) ; string expr4 = "1 + + 2" ; res = evaluate ( expr4 ) ; if ( res == - 1 ) Console . WriteLine ( expr4 + " ▁ is ▁ Invalid " ) ; else Console . WriteLine ( " Value ▁ of ▁ " + expr4 + " ▁ is ▁ " + res ) ; } }
Program to print first n Fibonacci Numbers | Set 1 | C # program to print first n Fibonacci Numbers ; Method to print first n Fibonacci Numbers ; Driver Code
using System ; class Test { static void printFibonacciNumbers ( int n ) { int f1 = 0 , f2 = 1 , i ; if ( n < 1 ) return ; Console . Write ( f1 + " ▁ " ) ; for ( i = 1 ; i < n ; i ++ ) { Console . Write ( f2 + " ▁ " ) ; int next = f1 + f2 ; f1 = f2 ; f2 = next ; } } public static void Main ( ) { printFibonacciNumbers ( 7 ) ; } }
Program to find LCM of two numbers | C # program to find LCM of two numbers . ; Recursive method to return gcd of a and b ; method to return LCM of two numbers ; Driver method
using System ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int lcm ( int a , int b ) { return ( a / gcd ( a , b ) ) * b ; } public static void Main ( ) { int a = 15 , b = 20 ; Console . WriteLine ( " LCM ▁ of ▁ " + a + " ▁ and ▁ " + b + " ▁ is ▁ " + lcm ( a , b ) ) ; } }
Program to convert a given number to words | C # program to print a given number in words . The program handles numbers from 0 to 9999 ; A function that prints given number in words ; Get number of digits in given number ; Base cases ; The first string is not used , it is to make array indexing simple ; The first string is not used , it is to make array indexing simple ; The first two string are not used , they are to make array indexing simple ; Used for debugging purpose only ; For single digit number ; Iterate while num is not ' \0' ; Code path for first 2 digits ; here len can be 3 or 4 ; Code path for last 2 digits ; Need to explicitly handle 10 - 19. Sum of the two digits is used as index of " two _ digits " array of strings ; Need to explicitely handle 20 ; Rest of the two digit numbers i . e . , 21 to 99 ; Driver Code
using System ; class GFG { static void convert_to_words ( char [ ] num ) { int len = num . Length ; if ( len == 0 ) { Console . WriteLine ( " empty ▁ string " ) ; return ; } if ( len > 4 ) { Console . WriteLine ( " Length ▁ more ▁ than ▁ " + "4 ▁ is ▁ not ▁ supported " ) ; return ; } string [ ] single_digits = new string [ ] { " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " } ; string [ ] two_digits = new string [ ] { " " , " ten " , " eleven " , " twelve " , " thirteen " , " fourteen " , " fifteen " , " sixteen " , " seventeen " , " eighteen " , " nineteen " } ; string [ ] tens_multiple = new string [ ] { " " , " " , " twenty " , " thirty " , " forty " , " fifty " , " sixty " , " seventy " , " eighty " , " ninety " } ; string [ ] tens_power = new string [ ] { " hundred " , " thousand " } ; Console . Write ( ( new string ( num ) ) + " : ▁ " ) ; if ( len == 1 ) { Console . WriteLine ( single_digits [ num [ 0 ] - '0' ] ) ; return ; } int x = 0 ; while ( x < num . Length ) { if ( len >= 3 ) { if ( num [ x ] - '0' != 0 ) { Console . Write ( single_digits [ num [ x ] - '0' ] + " ▁ " ) ; Console . Write ( tens_power [ len - 3 ] + " ▁ " ) ; } -- len ; } else { if ( num [ x ] - '0' == 1 ) { int sum = num [ x ] - '0' + num [ x + 1 ] - '0' ; Console . WriteLine ( two_digits [ sum ] ) ; return ; } else if ( num [ x ] - '0' == 2 && num [ x + 1 ] - '0' == 0 ) { Console . WriteLine ( " twenty " ) ; return ; } else { int i = ( num [ x ] - '0' ) ; if ( i > 0 ) Console . Write ( tens_multiple [ i ] + " ▁ " ) ; else Console . Write ( " " ) ; ++ x ; if ( num [ x ] - '0' != 0 ) Console . WriteLine ( single_digits [ num [ x ] - '0' ] ) ; } } ++ x ; } } public static void Main ( ) { convert_to_words ( "9923" . ToCharArray ( ) ) ; convert_to_words ( "523" . ToCharArray ( ) ) ; convert_to_words ( "89" . ToCharArray ( ) ) ; convert_to_words ( "8" . ToCharArray ( ) ) ; } }
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
class GFG { static int MAX = 11 ; static bool isMultipleof5 ( int n ) { char [ ] str = new char [ MAX ] ; int len = str . Length ; if ( str [ len - 1 ] == '5' str [ len - 1 ] == '0' ) return true ; return false ; } static void Main ( ) { int n = 19 ; if ( isMultipleof5 ( n ) == true ) Console . WriteLine ( " { 0 } ▁ is ▁ " + " multiple ▁ of ▁ 5" , n ) ; else Console . WriteLine ( " { 0 } ▁ is ▁ not ▁ a ▁ " + " multiple ▁ of ▁ 5" , n ) ; } }
Count subsequences having odd Bitwise OR values in an array | Java 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 [ ]
using System ; class GFG { static int countSubsequences ( int [ ] arr ) { int odd = 0 ; int even = 0 ; for ( int i = 0 ; i < arr . Length ; i ++ ) { if ( ( arr [ i ] & 1 ) != 0 ) odd ++ ; else even ++ ; } return ( ( 1 << odd ) - 1 ) * ( 1 << even ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 4 , 1 } ; Console . Write ( 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
using System ; class GFG { static void Or_of_Ands_for_each_query ( int [ ] arr , int n , int [ , ] queries , int q ) { int [ ] bits = new int [ 32 ] ; for ( int i = 0 ; i < 32 ; i ++ ) { bits [ i ] = 0 ; } for ( int i = 0 ; i < 32 ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( ( ( 1 << i ) & arr [ j ] ) != 0 ) { bits [ i ] ++ ; } } } for ( int p = 0 ; p < q ; p ++ ) { for ( int i = 0 ; i < 32 ; i ++ ) { if ( ( ( 1 << i ) & arr [ queries [ p , 0 ] ] ) != 0 ) { bits [ i ] -- ; } if ( ( queries [ p , 1 ] & ( 1 << i ) ) != 0 ) { 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 ) ; } } Console . WriteLine ( ans ) ; } } public static void Main ( String [ ] args ) { int n = 3 , q = 2 ; int [ ] arr = { 3 , 5 , 7 } ; int [ , ] queries = { { 1 , 2 } , { 2 , 1 } } ; Or_of_Ands_for_each_query ( arr , n , queries , q ) ; } }
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
using System ; using System . Collections . Generic ; class GFG { static 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 ; } public static void Main ( ) { int [ ] A = { 3 , 5 } ; int [ ] B = { 2 , 3 } ; int N = A . Length ; int M = B . Length ; Console . Write ( XorSum ( A , B , N , M ) ) ; } }
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
using System ; class GFG { static int countbitdiff ( int xo ) { int count = 0 ; while ( xo != 0 ) { if ( xo % 2 == 1 ) { count ++ ; } xo = xo / 2 ; } return count ; } static void shortestPath ( int n , int a , int b ) { int xorVal = a ^ b ; int cnt = countbitdiff ( xorVal ) ; if ( cnt % 2 == 0 ) Console . Write ( cnt / 2 ) ; else Console . Write ( " - 1" ) ; } public static void Main ( String [ ] args ) { int n = 15 ; int a = 15 , b = 3 ; shortestPath ( n , a , b ) ; } }
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
using System ; using System . Collections . Generic ; class GFG { static int M = 3 ; static int N = 3 ; static int findXOR ( int X ) { int ans = 0 ; while ( X != 0 ) { ans ^= ( X % 10 ) ; X /= 10 ; } return ans ; } static void printXORmatrix ( int [ , ] arr ) { for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { Console . Write ( arr [ i , j ] + " ▁ " ) ; } Console . WriteLine ( ) ; } } static void convertXOR ( int [ , ] arr ) { 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 ) ; } static public void Main ( ) { int [ , ] arr = { { 27 , 173 , 5 } , { 21 , 6 , 624 } , { 5 , 321 , 49 } } ; convertXOR ( arr ) ; } }
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
using System ; class GFG { static int countSet ( int N ) { int ans = 0 ; while ( N > 0 ) { ans += N & 1 ; N >>= 1 ; } return ans ; } static 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 ; } public static void Main ( string [ ] args ) { int [ ] arr = { 4 , 2 , 1 , 5 , 6 } ; int K = 2 ; Console . WriteLine ( countSub ( arr , K ) ) ; } }
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
using System ; class GFG { static 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 ] % 2 != 0 ) { odd = ( odd == 0 ) ? 1 : 0 ; } if ( odd != 0 ) { c_odd ++ ; } } for ( int i = 0 ; i < n ; i ++ ) { result += c_odd ; if ( a [ i ] % 2 != 0 ) { c_odd = ( n - i - c_odd ) ; } } Console . WriteLine ( result ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 4 , 7 , 9 , 10 } ; int N = arr . Length ; oddXorSubarray ( arr , N ) ; } }
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
using System ; public class GFG { static 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 ] ) ; } Console . Write ( req_sum + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int N = arr . Length ; printORSumforEachElement ( arr , N ) ; } }
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
using System ; class GFG { static void Bitwise_OR_sum_i ( int [ ] arr1 , int [ ] arr2 , int M , int N ) { int [ ] frequency = new int [ 32 ] ; for ( int i = 0 ; i < 32 ; i ++ ) { frequency [ i ] = 0 ; } for ( int i = 0 ; i < N ; i ++ ) { int bit_position = 0 ; int num = arr1 [ i ] ; while ( num != 0 ) { if ( ( num & 1 ) != 0 ) { 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 ) != 0 ) { 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 ; } Console . Write ( bitwise_OR_sum + " ▁ " ) ; } return ; } public static void Main ( ) { int [ ] arr1 = { 1 , 2 , 3 } ; int [ ] arr2 = { 1 , 2 , 3 } ; int N = arr1 . Length ; int M = arr2 . Length ; Bitwise_OR_sum_i ( arr1 , arr2 , M , N ) ; } }
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
using System ; class GFG { static 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 ++ ; } } Console . WriteLine ( count ) ; } public static void Main ( ) { int [ ] arr = { 2 , 38 , 44 , 29 , 62 } ; int K = 46 ; int N = arr . Length ; countPairs ( arr , K , N ) ; } }
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
using System ; using System . Collections . Generic ; class GFG { public class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static List < pair > [ ] adj = new List < pair > [ 100005 ] ; static int [ ] visited = new int [ 100005 ] ; static int ans = 0 ; static void dfs ( int node , int xorr , int k ) { visited [ node ] = 1 ; if ( node != 1 && xorr == k ) ans ++ ; foreach ( pair x in adj [ node ] ) { if ( visited [ x . first ] != 1 ) { int xorr1 = xorr ^ x . second ; dfs ( x . first , xorr1 , k ) ; } } } static void countNodes ( int N , int K , int R , int [ , ] edges ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { int u = edges [ i , 0 ] ; int v = edges [ i , 1 ] , w = edges [ i , 2 ] ; adj [ u ] . Add ( new pair ( v , w ) ) ; adj [ v ] . Add ( new pair ( u , w ) ) ; } dfs ( R , 0 , K ) ; Console . Write ( ans + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int K = 0 , R = 1 ; for ( int i = 0 ; i < adj . Length ; i ++ ) adj [ i ] = new List < pair > ( ) ; int [ , ] edges = { { 1 , 2 , 3 } , { 1 , 3 , 1 } , { 2 , 4 , 3 } , { 2 , 5 , 4 } , { 3 , 6 , 1 } , { 3 , 7 , 2 } } ; int N = edges . GetLength ( 0 ) ; countNodes ( N , K , R , edges ) ; } }
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
using System ; class GFG { static 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 ) ; } } Console . WriteLine ( min_xor ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 7 , 90 , 20 , 10 , 50 , 40 } ; int k = 3 ; int n = arr . Length ; findMinXORSubarray ( arr , n , k ) ; } }
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
using System ; class GFG { static 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 ; } public static void Main ( ) { int k = 3 ; int [ ] arr = { 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 } ; int n = arr . Length ; int ans = findmax ( arr , n , k ) ; Console . WriteLine ( ans ) ; } }
Print all the leaf nodes of Binary Heap | C # implementation to print the leaf nodes of a Binary Heap ; Function to calculate height of the Binary heap with given the count of the nodes ; Function to find the leaf nodes of binary heap ; Calculate the height of the complete binary tree ; if the height if h - 1 , then there should not be any child nodes ; Function to print the leaf nodes ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int height ( int N ) { return ( int ) Math . Ceiling ( Math . Log ( N + 1 ) / Math . Log ( 2 ) ) - 1 ; } static void findLeafNodes ( int [ ] arr , int n ) { int h = height ( n ) ; List < int > arrlist = new List < int > ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( height ( i + 1 ) == h ) { arrlist . Add ( arr [ i ] ) ; } else if ( height ( i + 1 ) == h - 1 && n <= ( ( 2 * i ) + 1 ) ) { arrlist . Add ( arr [ i ] ) ; } else { break ; } } printLeafNodes ( arrlist ) ; } static void printLeafNodes ( List < int > arrlist ) { for ( int i = arrlist . Count - 1 ; i >= 0 ; i -- ) { Console . Write ( arrlist [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; findLeafNodes ( arr , arr . Length ) ; } }
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 Math . 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
using System ; using System . Collections . Generic ; class GFG { static int powerOfTwo ( int [ ] a , int n ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . ContainsKey ( a [ i ] ) ) { mp [ a [ i ] ] = mp [ a [ i ] ] + 1 ; } else { mp . Add ( a [ i ] , 1 ) ; } } 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 . ContainsKey ( s ) && ( mp [ s ] > 1 || mp [ s ] == 1 && s != a [ i ] ) ) f = true ; } if ( f == false ) count ++ ; } return count ; } public static void Main ( String [ ] args ) { int [ ] a = { 6 , 2 , 11 } ; int n = a . Length ; Console . Write ( powerOfTwo ( a , n ) ) ; } }
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
using System ; class GFG { static void findArray ( int n , int a , int b , int c ) { int [ ] arr = new int [ n + 1 ] ; for ( int bit = 30 ; bit >= 0 ; bit -- ) { int set = a & ( 1 << bit ) ; if ( set != 0 ) { for ( int i = 0 ; i < n ; i ++ ) arr [ i ] |= set ; } else { if ( ( b & ( 1 << bit ) ) != 0 ) { arr [ 0 ] |= ( 1 << bit ) ; if ( ( c & ( 1 << bit ) ) == 0 ) { arr [ 1 ] |= ( 1 << bit ) ; } } } } int aa = int . MaxValue , 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 ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } else Console . WriteLine ( " - 1" ) ; } public static void Main ( String [ ] args ) { int n = 3 , a = 4 , b = 6 , c = 6 ; findArray ( n , a , b , c ) ; } }
Minimum XOR of OR and AND of any pair in the Array | C # program to for 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 arr [ ] ; Function Call
using System ; class GFG { static int maxAndXor ( int [ ] arr , int n ) { int ans = 9999999 ; Array . Sort ( arr ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { ans = Math . Min ( ans , arr [ i ] ^ arr [ i + 1 ] ) ; } return ans ; } public static void Main ( ) { int [ ] arr = new int [ ] { 1 , 2 , 3 , 4 , 5 } ; int N = arr . Length ; Console . Write ( maxAndXor ( arr , N ) ) ; } }
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
using System ; class GFG { static 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 ; } public static void Main ( ) { int [ ] arr = { 2 , 4 , 4 , 2 , 2 , 4 } ; int K = 4 ; int N = arr . Length ; Console . Write ( 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
using System ; class GFG { static int even , odd ; static void keep_count ( int [ ] arr , 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 ; } static void solveQueries ( int [ ] arr , int n , int [ ] q , int m ) { even = 0 ; odd = 0 ; keep_count ( arr , 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 ) { Console . Write ( even + " ▁ " + odd + " STRNEWLINE " ) ; } else { Console . Write ( odd + " ▁ " + even + " STRNEWLINE " ) ; } } } public static void Main ( ) { int [ ] arr = { 2 , 7 , 4 , 5 , 3 } ; int n = arr . Length ; int [ ] q = { 3 , 4 , 12 , 6 } ; int m = q . Length ; solveQueries ( arr , n , q , m ) ; } }
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 ]
using System ; class GFG { static int [ ] pref = new int [ 100001 ] ; static int isEvenParity ( int num ) { int parity = 0 ; int x = num ; while ( x != 0 ) { if ( ( x & 1 ) == 1 ) parity ++ ; x = x >> 1 ; } if ( parity % 2 == 0 ) return num ; else return 0 ; } static void preCompute ( ) { for ( int i = 1 ; i < 100001 ; i ++ ) { pref [ i ] = pref [ i - 1 ] + isEvenParity ( i ) ; } } static void printSum ( int L , int R ) { Console . WriteLine ( pref [ R ] - pref [ L - 1 ] ) ; } static void printSum ( int [ , ] arr , int Q ) { preCompute ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i , 0 ] , arr [ i , 1 ] ) ; } } public static void Main ( ) { int N = 2 ; int [ , ] Q = { { 1 , 10 } , { 121 , 211 } } ; printSum ( Q , N ) ; } }
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
using System ; using System . Linq ; class GFG { static int findLargestNumber ( int [ ] arr ) { int k = arr . Max ( ) ; int [ ] m = new int [ k + 1 ] ; foreach ( int n in arr ) ++ m [ n ] ; for ( int n = arr . Length - 1 ; n > 0 ; -- n ) { if ( n == m [ n ] ) return n ; } return - 1 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 5 , 2 , 4 , 5 } ; Console . Write ( findLargestNumber ( arr ) + " STRNEWLINE " ) ; } }
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
using System ; class GFG { static int findLargestNumber ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] &= 0xFFFF ; if ( arr [ i ] <= n ) { arr [ i ] += 0x10000 ; } } for ( int i = n - 1 ; i > 0 ; -- i ) { if ( ( arr [ i ] >> 16 ) == i ) return i + 1 ; } return - 1 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 5 , 5 , 2 , 4 , 5 } ; int n = arr . Length ; Console . Write ( findLargestNumber ( arr , n ) + " STRNEWLINE " ) ; } }
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
using System ; class GFG { static int NoCarrySum ( int N , int M ) { return N ^ M ; } static public void Main ( String [ ] args ) { int N = 37 ; int M = 12 ; Console . Write ( NoCarrySum ( N , M ) ) ; } }
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
using System ; public class GFG { static bool CheckBits ( int N , int K ) { int check = 0 ; int count = 0 ; for ( int i = 31 ; i >= 0 ; i -- ) { if ( ( ( 1 << i ) & N ) > 0 ) { if ( check == 0 ) { check = 1 ; } else { if ( count < K ) { return false ; } } count = 0 ; } else { count ++ ; } } return true ; } static public void Main ( ) { int N = 5 ; int K = 1 ; if ( CheckBits ( N , K ) ) { Console . Write ( " YES " ) ; } else { Console . Write ( " NO " ) ; } } }
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
using System ; class GFG { static int minimumFlips ( int X , int Y , int Z ) { int res = 0 ; while ( X > 0 Y > 0 Z > 0 ) { if ( ( ( X % 2 == 1 ) || ( Y % 2 == 1 ) ) && ( Z % 2 == 1 ) ) { X = X >> 1 ; Y = Y >> 1 ; Z = Z >> 1 ; continue ; } else if ( ! ( X % 2 == 1 ) && ! ( Y % 2 == 1 ) && ( Z % 2 == 1 ) ) { res ++ ; } else if ( ( X % 2 == 1 ) || ( Y % 2 == 1 ) ) { if ( ( X % 2 == 1 ) && ( Y % 2 == 1 ) && ! ( Z % 2 == 1 ) ) { res += 2 ; } else if ( ( ( X % 2 == 1 ) || ( Y % 2 == 1 ) ) && ! ( Z % 2 == 1 ) ) { res ++ ; } } X = X >> 1 ; Y = Y >> 1 ; Z = Z >> 1 ; } return res ; } public static void Main ( ) { int X = 5 , Y = 8 , Z = 6 ; Console . Write ( minimumFlips ( X , Y , Z ) ) ; } }
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
static int countSubseq ( int [ ] arr , int n ) { int count = 0 ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . ContainsKey ( arr [ i ] ) ) { var val = mp [ arr [ i ] ] ; mp . Remove ( arr [ i ] ) ; mp . Add ( arr [ i ] , val + 1 ) ; } else { mp . Add ( arr [ i ] , 1 ) ; } } foreach ( KeyValuePair < int , int > entry in mp ) { if ( entry . Key == 0 ) count += ( int ) ( Math . Pow ( 2 , entry . Value - 1 ) ) ; else count += ( int ) ( Math . Pow ( 2 , entry . Value - 1 ) ) ; } return count ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 2 , 2 , 5 , 6 } ; int n = arr . Length ; Console . WriteLine ( countSubseq ( arr , n ) ) ; } }
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
using System ; using System . Collections . Generic ; class GFG { static int calculate ( List < int > section , int pos ) { if ( pos < 0 ) return 0 ; List < int > on_section = new List < int > ( ) , off_section = new List < int > ( ) ; foreach ( int el in section ) { if ( ( ( el >> pos ) & 1 ) == 0 ) off_section . Add ( el ) ; else on_section . Add ( el ) ; } if ( off_section . Count == 0 ) return calculate ( on_section , pos - 1 ) ; if ( on_section . Count == 0 ) return calculate ( off_section , pos - 1 ) ; return Math . Min ( calculate ( off_section , pos - 1 ) , calculate ( on_section , pos - 1 ) ) + ( 1 << pos ) ; } static int minXorValue ( int [ ] a , int n ) { List < int > section = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) section . Add ( a [ i ] ) ; return calculate ( section , 30 ) ; } public static void Main ( String [ ] args ) { int N = 4 ; int [ ] A = { 3 , 2 , 5 , 6 } ; Console . Write ( minXorValue ( A , N ) ) ; } }
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
using System ; class GFG { static void findNthNum ( int N ) { 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 ; Console . Write ( ( 1 << bit_L ) + ( 1 << bit_R ) + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int N = 13 ; findNthNum ( N ) ; } }
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
using System ; class GFG { static int MAX = 1000005 ; static bool [ ] prime = new bool [ MAX ] ; static void SieveOfEratosthenes ( 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 ; } } } static void prime_xor ( int [ ] arr , int n , int k ) { for ( int i = 0 ; i < MAX ; i ++ ) prime [ i ] = true ; SieveOfEratosthenes ( prime ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { if ( ( i + 1 ) % k == 0 ) { ans ^= arr [ i ] ; } } } Console . WriteLine ( ans ) ; } public static void Main ( string [ ] args ) { int [ ] arr = { 2 , 3 , 5 , 7 , 11 , 8 } ; int n = arr . Length ; int K = 2 ; prime_xor ( arr , n , K ) ; } }
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
using System ; class GFG { static 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 ; } public static void Main ( string [ ] args ) { int [ ] arr = { 3 , 9 , 12 , 13 , 15 } ; int n = arr . Length ; Console . WriteLine ( xorOfArray ( arr , n ) ) ; } }
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
using System ; class GFG { static void countEvenBit ( int [ ] A , int [ ] B , int n , int m ) { int i , cntOdd = 0 , cntEven = 0 ; for ( i = 0 ; i < n ; i ++ ) { int x = bitCount ( A [ i ] ) ; if ( x % 2 == 1 ) { cntEven ++ ; } else { cntOdd ++ ; } } int [ ] CountB = new int [ m ] ; for ( i = 0 ; i < m ; i ++ ) { int x = bitCount ( B [ i ] ) ; if ( x % 2 == 1 ) { CountB [ i ] = cntEven ; } else { CountB [ i ] = cntOdd ; } } for ( i = 0 ; i < m ; i ++ ) { Console . Write ( CountB [ i ] + " ▁ " ) ; } } static int bitCount ( int x ) { int setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } public static void Main ( String [ ] args ) { int [ ] A = { 4 , 2 , 15 , 9 , 8 , 8 } ; int [ ] B = { 3 , 4 , 22 } ; countEvenBit ( A , B , 6 , 3 ) ; } }
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
using System ; class GFG { static bool isEven ( int n ) { if ( ( n ^ 1 ) == n + 1 ) return true ; else return false ; } public static void Main ( String [ ] args ) { int n = 100 ; Console . Write ( isEven ( n ) == true ? " Even " : " Odd " ) ; } }
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
using System ; class GFG { static int bitwiseOrTillN ( int n ) { int result = 2 ; for ( int i = 4 ; i <= n ; i = i + 2 ) { result = result | i ; } return result ; } static public void Main ( ) { int n = 10 ; Console . WriteLine ( bitwiseOrTillN ( n ) ) ; } }
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
using System ; class GFG { static int bitwiseOrTillN ( int n ) { if ( n < 2 ) return 0 ; int bitCount = ( int ) ( Math . Log ( n ) / Math . Log ( 2 ) ) + 1 ; return ( int ) Math . Pow ( 2 , bitCount ) - 2 ; } public static void Main ( ) { int n = 10 ; Console . WriteLine ( bitwiseOrTillN ( n ) ) ; } }
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
using System ; class GFG { static void genSequence ( int n , int val ) { for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int x = i ^ ( i >> 1 ) ^ val ; Console . Write ( x + " ▁ " ) ; } } public static void Main ( ) { int n = 3 , k = 2 ; genSequence ( n , k ) ; } }
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
using System ; using System . Collections . Generic ; class GFG { static String winner ( String moves ) { Dictionary < char , int > data = new Dictionary < char , int > ( ) ; data . Add ( ' R ' , 0 ) ; data . Add ( ' P ' , 1 ) ; data . Add ( ' S ' , 2 ) ; if ( moves [ 0 ] == moves [ 1 ] ) { return " Draw " ; } if ( ( ( data [ moves [ 0 ] ] | 1 << ( 2 ) ) - ( data [ moves [ 1 ] ] | 0 << ( 2 ) ) ) % 3 != 0 ) { return " A " ; } return " B " ; } static void performQueries ( String [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) Console . Write ( winner ( arr [ i ] ) + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { String [ ] arr = { " RS " , " SR " , " SP " , " PP " } ; int n = arr . Length ; performQueries ( arr , n ) ; } }
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
using System ; class GFG { static int maxConsecutiveOnes ( int x ) { int count = 0 ; while ( x != 0 ) { x = ( x & ( x << 1 ) ) ; count ++ ; } return count ; } static int maxOnes ( int [ ] arr , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int currMax = maxConsecutiveOnes ( arr [ i ] ) ; ans = Math . Max ( ans , currMax ) ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int n = arr . Length ; Console . WriteLine ( maxOnes ( arr , n ) ) ; } }
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
using System ; class GFG { static int maxOR ( int L , int R ) { int maximum = int . MinValue ; for ( int i = L ; i < R ; i ++ ) for ( int j = i + 1 ; j <= R ; j ++ ) maximum = Math . Max ( maximum , ( i j ) ) ; return ; } public static void ( String [ ] args ) { int L = 4 , R = 5 ; Console . WriteLine ( maxOR ( L , R ) ) ; } }
Maximum Bitwise OR pair from a range | C # implementation of the above 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
using System ; class GFG { static int MAX = 64 ; static 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 ; } public static void Main ( String [ ] args ) { int L = 4 , R = 5 ; Console . WriteLine ( maxOR ( L , R ) ) ; } }
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
using System ; using System . Collections . Generic ; class GFG { static int findLen ( int [ ] arr , int n , int m ) { List < int > filter = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( ( arr [ i ] & m ) == m ) filter . Add ( arr [ i ] ) ; if ( filter . Count == 0 ) return 0 ; int c_and = filter [ 0 ] ; for ( int i = 1 ; i < filter . Count ; i ++ ) c_and &= filter [ i ] ; if ( c_and == m ) return filter . Count ; return 0 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 7 , 3 , 3 , 1 , 3 } ; int n = arr . Length ; int m = 3 ; Console . WriteLine ( findLen ( arr , n , m ) ) ; } }
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
using System ; using System . Collections . Generic ; class GFG { static int findLen ( int [ ] arr , int n , int m ) { List < int > filter = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( ( arr [ i ] m ) == m ) filter . Add ( arr [ i ] ) ; if ( filter . Count == 0 ) return 0 ; int c_or = filter [ 0 ] ; for ( int i = 1 ; i < filter . Count ; i ++ ) c_or |= filter [ i ] ; if ( c_or == m ) return filter . Count ; return 0 ; } public static void Main ( ) { int [ ] arr = { 7 , 3 , 3 , 1 , 3 } ; int n = arr . Length ; int m = 3 ; Console . Write ( findLen ( arr , n , m ) ) ; } }
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
using System ; class GFG { static int toggleBit ( int n , int k ) { return ( n ^ ( 1 << ( k - 1 ) ) ) ; } public static void Main ( String [ ] args ) { int n = 5 , k = 2 ; Console . WriteLine ( " { 0 } " , toggleBit ( n , k ) ) ; } }
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
using System ; class GFG { static int clearBit ( int n , int k ) { return ( n & ( ~ ( 1 << ( k - 1 ) ) ) ) ; } public static void Main ( String [ ] args ) { int n = 5 , k = 1 ; Console . WriteLine ( clearBit ( n , k ) ) ; } }
Maximize the Expression | Bit Manipulation | C # implementation of the above 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
using System ; class GFG { static int MAX = 32 ; static 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 ; } public static void Main ( String [ ] args ) { int a = 11 , b = 14 ; Console . WriteLine ( maximizeExpression ( a , b ) ) ; } }
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
using System ; using System . Collections . Generic ; class GFG { static int MAX = 10 ; static int findSubarray ( int [ ] array , int n ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; mp . Add ( 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 . ContainsKey ( Y ) ) { answer += mp [ Y ] ; } value *= 2 ; } if ( mp . ContainsKey ( preXor ) ) { mp [ preXor ] = mp [ preXor ] + 1 ; } else { mp . Add ( preXor , 1 ) ; } } return answer ; } public static void Main ( String [ ] args ) { int [ ] array = { 2 , 6 , 7 , 5 , 8 } ; int n = array . Length ; Console . WriteLine ( findSubarray ( array , n ) ) ; } }
Maximum XOR of Two Numbers in an Array | C # implementation of the approach ; Function to return the maximum xor ; Calculating xor of each pair ; Driver Code
using System ; class GFG { static 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 = Math . Max ( maxXor , arr [ i ] ^ arr [ j ] ) ; } } return maxXor ; } public static void Main ( ) { int [ ] arr = { 25 , 10 , 2 , 8 , 5 , 3 } ; int n = arr . Length ; Console . WriteLine ( max_xor ( arr , n ) ) ; } }
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
using System ; using System . Collections . Generic ; class GFG { static int max_xor ( int [ ] arr , int n ) { int maxx = 0 , mask = 0 ; HashSet < int > se = new HashSet < int > ( ) ; for ( int i = 30 ; i >= 0 ; i -- ) { mask |= ( 1 << i ) ; for ( int j = 0 ; j < n ; ++ j ) { se . Add ( arr [ j ] & mask ) ; } int newMaxx = maxx | ( 1 << i ) ; foreach ( int prefix in se ) { if ( se . Contains ( newMaxx ^ prefix ) ) { maxx = newMaxx ; break ; } } se . Clear ( ) ; } return maxx ; } public static void Main ( String [ ] args ) { int [ ] arr = { 25 , 10 , 2 , 8 , 5 , 3 } ; int n = arr . Length ; Console . WriteLine ( max_xor ( arr , n ) ) ; } }
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
using System ; class GFG { static 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 ; } public static void Main ( ) { int [ ] arr = { 2 , 5 , 6 , 4 , 2 } ; int n = arr . Length ; Console . WriteLine ( CountTriplets ( arr , n ) ) ; } }
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 Code
using System ; class GFG { static void findMajority ( int [ ] arr , int n ) { int len = 32 ; int number = 0 ; for ( int i = 0 ; i < len ; i ++ ) { int countt = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) != 0 ) countt ++ ; } if ( countt > ( n / 2 ) ) number += ( 1 << i ) ; } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == number ) count ++ ; if ( count > ( n / 2 ) ) Console . Write ( number ) ; else Console . Write ( " Majority ▁ Element ▁ Not ▁ Present " ) ; } static public void Main ( ) { int [ ] arr = { 3 , 3 , 4 , 2 , 4 , 4 , 2 , 4 , 4 } ; int n = arr . Length ; findMajority ( arr , n ) ; } }
Count number of bits to be flipped to convert A to B | Set | C # implementation of the above 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
using System ; class GFG { static int countBits ( int a , int b ) { int count = 0 ; while ( a > 0 b > 0 ) { 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 ; } public static void Main ( String [ ] args ) { int a = 10 , b = 7 ; Console . WriteLine ( countBits ( a , b ) ) ; } }
Count Set | C # 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
using System ; class GFG { static int CountSetBits ( int n ) { if ( n == 0 ) return 0 ; if ( ( n & 1 ) == 1 ) return 1 + CountSetBits ( n >> 1 ) ; else return CountSetBits ( n >> 1 ) ; } public static void Main ( ) { int n = 21 ; Console . WriteLine ( CountSetBits ( n ) ) ; } }
Count smaller elements on right side and greater elements on left side using Binary Index Tree | C # implementation of the above 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 [ ] ; Initialize result ; 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 ; Arrays . binarySearch ( ) returns index 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
using System ; class GFG { public static int getSum ( int [ ] BITree , int index ) { int sum = 0 ; while ( index > 0 ) { sum += BITree [ index ] ; index -= index & ( - index ) ; } return sum ; } public static void updateBIT ( int [ ] BITree , int n , int index , int val ) { while ( index <= n ) { BITree [ index ] += val ; index += index & ( - index ) ; } } public static void convert ( int [ ] arr , int n ) { int [ ] temp = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) temp [ i ] = arr [ i ] ; Array . Sort ( temp ) ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = Array . BinarySearch ( temp , arr [ i ] ) + 1 ; } } public static void findElements ( int [ ] arr , int n ) { convert ( arr , n ) ; int [ ] BIT = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) BIT [ i ] = 0 ; int [ ] smaller_right = new int [ n ] ; int [ ] greater_left = new int [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { smaller_right [ i ] = getSum ( BIT , arr [ i ] - 1 ) ; updateBIT ( BIT , n , arr [ i ] , 1 ) ; } Console . Write ( " Smaller ▁ right : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( smaller_right [ i ] + " ▁ " ) ; Console . WriteLine ( ) ; 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 ) ; } Console . Write ( " Greater ▁ left : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( greater_left [ i ] + " ▁ " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 12 , 1 , 2 , 3 , 0 , 11 , 4 } ; int n = arr . Length ; findElements ( arr , n ) ; } }
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
using System ; class GFG { static 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 ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int n = arr . Length ; Console . Write ( pairORSum ( arr , n ) ) ; } }
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
using System ; class GFG { static bool isPrime ( int n ) { if ( n <= 1 ) return false ; for ( int i = 2 ; i < n ; i ++ ) { if ( ( n % i ) == 0 ) return false ; } return true ; } static void countPrimePosition ( int [ ] arr ) { int c0 = 0 , c1 = 0 ; int n = arr . Length ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] == 0 ) && ( isPrime ( i ) ) ) c0 ++ ; if ( ( arr [ i ] == 1 ) && ( isPrime ( i ) ) ) c1 ++ ; } Console . WriteLine ( " Number ▁ of ▁ 0s ▁ = ▁ " + c0 ) ; Console . WriteLine ( " Number ▁ of ▁ 1s ▁ = ▁ " + c1 ) ; } static public void Main ( ) { int [ ] arr = { 1 , 0 , 1 , 0 , 1 } ; countPrimePosition ( arr ) ; } }
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
using System ; class GFG { static long multiplyByFifteen ( long n ) { long prod = ( n << 4 ) ; prod = prod - n ; return prod ; } public static void Main ( ) { long n = 7 ; Console . Write ( multiplyByFifteen ( n ) ) ; } }
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
using System ; class GFG { static long multiplyByFifteen ( long n ) { long prod = ( n << 3 ) ; prod += ( n << 2 ) ; prod += ( n << 1 ) ; prod += n ; return prod ; } public static void Main ( ) { long n = 7 ; Console . Write ( multiplyByFifteen ( n ) ) ; } }
Find a number which give minimum sum when XOR with every number of array of integers | C # implementation of above 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
using System ; using System . Linq ; class GFG { public static void findX ( int [ ] a , int n ) { int itr = a . Max ( ) ; int p = ( int ) Math . Log ( itr , 2 ) + 1 ; int x = 0 ; for ( int i = 0 ; i < p ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( a [ j ] & ( 1 << i ) ) != 0 ) count ++ ; } if ( count > ( n / 2 ) ) { x += 1 << i ; } } long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += ( x ^ a [ i ] ) ; Console . Write ( " X ▁ = ▁ " + x + " , ▁ Sum ▁ = ▁ " + sum ) ; } public static void Main ( String [ ] args ) { int [ ] a = { 2 , 3 , 4 , 5 , 6 } ; int n = a . Length ; findX ( a , n ) ; } }
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
using System ; class GFG { static int [ ] arr = new int [ 33 ] ; static void balTernary ( int ter ) { int carry = 0 , b = 10 ; int i = 32 ; while ( ter > 0 ) { int rem = ter % b ; 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 = ( int ) ( ter / b ) ; } if ( carry == 1 ) arr [ i ] = 1 ; } static int ternary ( int number ) { int ans = 0 , rem = 1 , b = 1 ; while ( number > 0 ) { rem = number % 3 ; ans = ans + rem * b ; number = ( int ) ( number / 3 ) ; b = b * 10 ; } return ans ; } public static void Main ( String [ ] args ) { int number = 3056 ; int ter = ternary ( number ) ; balTernary ( ter ) ; int i = 0 ; while ( arr [ i ] == 0 ) { i ++ ; } for ( int j = i ; j <= 32 ; j ++ ) { if ( arr [ j ] == - 1 ) Console . Write ( ' Z ' ) ; else Console . Write ( arr [ j ] ) ; } } }
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
class GFG { static void minAND ( int [ ] arr , int n ) { int s = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { s = s & arr [ i ] ; } System . Console . WriteLine ( s ) ; } static void Main ( ) { int [ ] arr = { 1 , 2 , 3 } ; int n = arr . Length ; 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
using System ; class GFG { static bool check ( int [ ] a , int n ) { for ( int i = 0 ; i < n ; i ++ ) if ( a [ i ] == 1 ) return true ; return false ; } public static void Main ( ) { int [ ] a = { 0 , 1 , 0 , 1 } ; int n = a . Length ; if ( check ( a , n ) == true ) Console . Write ( " YES STRNEWLINE " ) ; else Console . Write ( " NO STRNEWLINE " ) ; } }
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
using System ; class GFG { static void printArray ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } static void findArray ( int [ ] q , int n ) { int ans ; int [ ] arr = new int [ n ] ; 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 ) ; } public static void Main ( ) { int [ ] q = { 4 , 1 , 7 , 0 } ; int n = q . Length ; findArray ( q , n ) ; } }
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
using System ; class GFG { static int countX ( int n ) { string binary = Convert . ToString ( n , 2 ) ; int count = 0 ; for ( int i = 0 ; i < binary . Length ; i ++ ) { if ( binary [ i ] == '1' ) count ++ ; } int answer = ( int ) Math . Pow ( 2 , count ) ; return answer ; } public static void Main ( ) { int n = 5 ; int answer = countX ( n ) ; Console . WriteLine ( 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 code
using System ; class GFG { static 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 ) { 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 ; } public static void Main ( ) { int n = 51 ; if ( isEqualBlock ( n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
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
using System ; class GFG { static void binToDecimal3 ( int n ) { int [ ] a = new int [ 64 ] ; 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 j = x - 3 ; j < x ; j ++ ) d += a [ j ] * ( int ) Math . Pow ( 2 , p ++ ) ; int d1 = d ; d = 0 ; p = 0 ; for ( int k = 0 ; k < 3 ; k ++ ) d += a [ k ] * ( int ) Math . Pow ( 2 , p ++ ) ; Console . WriteLine ( d1 + " ▁ " + d ) ; } static void Main ( ) { int n = 86 ; binToDecimal3 ( n ) ; } }
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
using System ; class GFG { static 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 ) ) ; Console . WriteLine ( first_3 + " ▁ " + last_3 ) ; } static public void Main ( ) { int n = 86 ; binToDecimal3 ( n ) ; } }
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
using System ; class GFG { static bool isPowerOfTwo ( int x ) { if ( x == 0 ) return false ; if ( ( x & ( x - 1 ) ) == 0 ) return true ; else return false ; } static 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 ; } public static void Main ( ) { int [ ] arr = { 5 , 6 , 9 , 3 , 1 } ; int n = arr . Length ; Console . WriteLine ( countNum ( arr , n ) ) ; } }