text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Sum of Fibonacci Numbers | Computes value of first fibonacci numbers ; Initialize result ; Add remaining terms ; Driver program to test above function
def calculateSum ( n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT fibo = [ 0 ] * ( n + 1 ) NEW_LINE fibo [ 1 ] = 1 NEW_LINE sm = fibo [ 0 ] + fibo [ 1 ] NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT fibo [ i ] = fibo [ i - 1 ] + fibo [ i - 2 ] NEW_LINE sm = sm + fibo [ i ] NEW_LINE DEDENT return sm NEW_LINE DEDENT n = 4 NEW_LINE print ( " Sum ▁ of ▁ Fibonacci ▁ numbers ▁ is ▁ : ▁ " , calculateSum ( n ) ) NEW_LINE
Find all combinations that add upto given number | arr - array to store the combination index - next location in array num - given number reducedNum - reduced number ; Base condition ; If combination is found , print it ; Find the previous number stored in arr [ ] . It helps in maintaining increasing order ; note loop starts from previous number i . e . at array location index - 1 ; next element of array is k ; call recursively with reduced number ; Function to find out all combinations of positive numbers that add upto given number . It uses findCombinationsUtil ( ) ; array to store the combinations It can contain max n elements ; find all combinations ; Driver code
def findCombinationsUtil ( arr , index , num , reducedNum ) : NEW_LINE INDENT if ( reducedNum < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( reducedNum == 0 ) : NEW_LINE INDENT for i in range ( index ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " ) NEW_LINE return NEW_LINE DEDENT prev = 1 if ( index == 0 ) else arr [ index - 1 ] NEW_LINE for k in range ( prev , num + 1 ) : NEW_LINE INDENT arr [ index ] = k NEW_LINE findCombinationsUtil ( arr , index + 1 , num , reducedNum - k ) NEW_LINE DEDENT DEDENT def findCombinations ( n ) : NEW_LINE INDENT arr = [ 0 ] * n NEW_LINE findCombinationsUtil ( arr , 0 , n , n ) NEW_LINE DEDENT n = 5 ; NEW_LINE findCombinations ( n ) ; NEW_LINE
Find Square Root under Modulo p | Set 2 ( Shanks Tonelli algorithm ) | utility function to find pow ( base , exponent ) % modulus ; utility function to find gcd ; Returns k such that b ^ k = 1 ( mod p ) ; Initializing k with first odd prime number ; function return p - 1 ( = x argument ) as x * 2 ^ e , where x will be odd sending e as reference because updation is needed in actual e ; Main function for finding the modular square root ; a and p should be coprime for finding the modular square root ; If below expression return ( p - 1 ) then modular square root is not possible ; expressing p - 1 , in terms of s * 2 ^ e , where s is odd number ; finding smallest q such that q ^ ( ( p - 1 ) / 2 ) ( mod p ) = p - 1 ; q - 1 is in place of ( - 1 % p ) ; Initializing variable x , b and g ; keep looping until b become 1 or m becomes 0 ; finding m such that b ^ ( 2 ^ m ) = 1 ; updating value of x , g and b according to algorithm ; Driver Code ; p should be prime
def pow1 ( base , exponent , modulus ) : NEW_LINE INDENT result = 1 ; NEW_LINE base = base % modulus ; NEW_LINE while ( exponent > 0 ) : NEW_LINE INDENT if ( exponent % 2 == 1 ) : NEW_LINE INDENT result = ( result * base ) % modulus ; NEW_LINE DEDENT exponent = int ( exponent ) >> 1 ; NEW_LINE base = ( base * base ) % modulus ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( b , a % b ) ; NEW_LINE DEDENT DEDENT def order ( p , b ) : NEW_LINE INDENT if ( gcd ( p , b ) != 1 ) : NEW_LINE INDENT print ( " p and b are not co - prime . " ) ; NEW_LINE return - 1 ; NEW_LINE DEDENT k = 3 ; NEW_LINE while ( True ) : NEW_LINE INDENT if ( pow1 ( b , k , p ) == 1 ) : NEW_LINE INDENT return k ; NEW_LINE DEDENT k += 1 ; NEW_LINE DEDENT DEDENT def convertx2e ( x ) : NEW_LINE INDENT z = 0 ; NEW_LINE while ( x % 2 == 0 ) : NEW_LINE INDENT x = x / 2 ; NEW_LINE z += 1 ; NEW_LINE DEDENT return [ x , z ] ; NEW_LINE DEDENT def STonelli ( n , p ) : NEW_LINE INDENT if ( gcd ( n , p ) != 1 ) : NEW_LINE INDENT print ( " a and p are not coprime " ) ; NEW_LINE return - 1 ; NEW_LINE DEDENT if ( pow1 ( n , ( p - 1 ) / 2 , p ) == ( p - 1 ) ) : NEW_LINE INDENT print ( " no sqrt possible " ) ; NEW_LINE return - 1 ; NEW_LINE DEDENT ar = convertx2e ( p - 1 ) ; NEW_LINE s = ar [ 0 ] ; NEW_LINE e = ar [ 1 ] ; NEW_LINE q = 2 ; NEW_LINE while ( True ) : NEW_LINE INDENT if ( pow1 ( q , ( p - 1 ) / 2 , p ) == ( p - 1 ) ) : NEW_LINE INDENT break ; NEW_LINE DEDENT q += 1 ; NEW_LINE DEDENT x = pow1 ( n , ( s + 1 ) / 2 , p ) ; NEW_LINE b = pow1 ( n , s , p ) ; NEW_LINE g = pow1 ( q , s , p ) ; NEW_LINE r = e ; NEW_LINE while ( True ) : NEW_LINE INDENT m = 0 ; NEW_LINE while ( m < r ) : NEW_LINE INDENT if ( order ( p , b ) == - 1 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( order ( p , b ) == pow ( 2 , m ) ) : NEW_LINE INDENT break ; NEW_LINE DEDENT m += 1 ; NEW_LINE DEDENT if ( m == 0 ) : NEW_LINE INDENT return x ; NEW_LINE DEDENT x = ( x * pow1 ( g , pow ( 2 , r - m - 1 ) , p ) ) % p ; NEW_LINE g = pow1 ( g , pow ( 2 , r - m ) , p ) ; NEW_LINE b = ( b * g ) % p ; NEW_LINE if ( b == 1 ) : NEW_LINE INDENT return x ; NEW_LINE DEDENT r = m ; NEW_LINE DEDENT DEDENT n = 2 ; NEW_LINE p = 113 ; NEW_LINE x = STonelli ( n , p ) ; NEW_LINE if ( x == - 1 ) : NEW_LINE INDENT print ( " Modular square root is not exist " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Modular ▁ square ▁ root ▁ of " , n , " and " , p , " is " , x ) ; NEW_LINE DEDENT
Check if a number is a power of another number | Python3 program to check given number number y ; logarithm function to calculate value ; Note : this is double ; compare to the result1 or result2 both are equal ; Driver Code
import math NEW_LINE def isPower ( x , y ) : NEW_LINE INDENT res1 = math . log ( y ) // math . log ( x ) ; NEW_LINE res2 = math . log ( y ) / math . log ( x ) ; NEW_LINE return 1 if ( res1 == res2 ) else 0 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( isPower ( 27 , 729 ) ) ; NEW_LINE DEDENT
Program to find the Roots of Quadratic equation | Python program to find roots of a quadratic equation ; Prints roots of quadratic equation ax * 2 + bx + x ; If a is 0 , then equation is not quadratic , but linear ; else : d < 0 ; Driver Program ; Function call
import math NEW_LINE def findRoots ( a , b , c ) : NEW_LINE INDENT if a == 0 : NEW_LINE INDENT print ( " Invalid " ) NEW_LINE return - 1 NEW_LINE DEDENT d = b * b - 4 * a * c NEW_LINE sqrt_val = math . sqrt ( abs ( d ) ) NEW_LINE if d > 0 : NEW_LINE INDENT print ( " Roots ▁ are ▁ real ▁ and ▁ different ▁ " ) NEW_LINE print ( ( - b + sqrt_val ) / ( 2 * a ) ) NEW_LINE print ( ( - b - sqrt_val ) / ( 2 * a ) ) NEW_LINE DEDENT elif d == 0 : NEW_LINE INDENT print ( " Roots ▁ are ▁ real ▁ and ▁ same " ) NEW_LINE print ( - b / ( 2 * a ) ) NEW_LINE print ( " Roots ▁ are ▁ complex " ) NEW_LINE print ( - b / ( 2 * a ) , " ▁ + ▁ i " , sqrt_val ) NEW_LINE print ( - b / ( 2 * a ) , " ▁ - ▁ i " , sqrt_val ) NEW_LINE DEDENT DEDENT a = 1 NEW_LINE b = - 7 NEW_LINE c = 12 NEW_LINE findRoots ( a , b , c ) NEW_LINE
Check perfect square using addition / subtraction | This function returns true if n is perfect square , else false ; the_sum is sum of all odd numbers . i is used one by one hold odd numbers ; Driver code
def isPerfectSquare ( n ) : NEW_LINE INDENT i = 1 NEW_LINE the_sum = 0 NEW_LINE while the_sum < n : NEW_LINE INDENT the_sum += i NEW_LINE if the_sum == n : NEW_LINE INDENT return True NEW_LINE DEDENT i += 2 NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( ' Yes ' ) if isPerfectSquare ( 35 ) else print ( ' NO ' ) NEW_LINE print ( ' Yes ' ) if isPerfectSquare ( 49 ) else print ( ' NO ' ) NEW_LINE DEDENT
Count ' d ' digit positive integers with 0 as a digit | Python 3 program to find the count of positive integer of a given number of digits that contain atleast one zero ; Returns count of ' d ' digit integers have 0 as a digit ; Driver Code
import math NEW_LINE def findCount ( d ) : NEW_LINE INDENT return 9 * ( ( int ) ( math . pow ( 10 , d - 1 ) ) - ( int ) ( math . pow ( 9 , d - 1 ) ) ) ; NEW_LINE DEDENT d = 1 NEW_LINE print ( findCount ( d ) ) NEW_LINE d = 2 NEW_LINE print ( findCount ( d ) ) NEW_LINE d = 4 NEW_LINE print ( findCount ( d ) ) NEW_LINE
Dyck path | Returns count Dyck paths in n x n grid ; Compute value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver Code
def countDyckPaths ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT res *= ( 2 * n - i ) NEW_LINE res /= ( i + 1 ) NEW_LINE DEDENT return res / ( n + 1 ) NEW_LINE DEDENT n = 4 NEW_LINE print ( " Number ▁ of ▁ Dyck ▁ Paths ▁ is ▁ " , str ( int ( countDyckPaths ( n ) ) ) ) NEW_LINE
Triangular Numbers | Returns True if ' num ' is triangular , else False ; Base case ; A Triangular number must be sum of first n natural numbers ; Driver code
def isTriangular ( num ) : NEW_LINE INDENT if ( num < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT sum , n = 0 , 1 NEW_LINE while ( sum <= num ) : NEW_LINE INDENT sum = sum + n NEW_LINE if ( sum == num ) : NEW_LINE INDENT return True NEW_LINE DEDENT n += 1 NEW_LINE DEDENT return False NEW_LINE DEDENT n = 55 NEW_LINE if ( isTriangular ( n ) ) : NEW_LINE INDENT print ( " The ▁ number ▁ is ▁ a ▁ triangular ▁ number " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ number ▁ is ▁ NOT ▁ a ▁ triangular ▁ number " ) NEW_LINE DEDENT
Triangular Numbers | Python3 program to check if a number is a triangular number using quadratic equation . ; Returns True if num is triangular ; Considering the equation n * ( n + 1 ) / 2 = num The equation is : a ( n ^ 2 ) + bn + c = 0 ; Find roots of equation ; checking if root1 is natural ; checking if root2 is natural ; Driver code
import math NEW_LINE def isTriangular ( num ) : NEW_LINE INDENT if ( num < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT c = ( - 2 * num ) NEW_LINE b , a = 1 , 1 NEW_LINE d = ( b * b ) - ( 4 * a * c ) NEW_LINE if ( d < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT root1 = ( - b + math . sqrt ( d ) ) / ( 2 * a ) NEW_LINE root2 = ( - b - math . sqrt ( d ) ) / ( 2 * a ) NEW_LINE if ( root1 > 0 and math . floor ( root1 ) == root1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( root2 > 0 and math . floor ( root2 ) == root2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT n = 55 NEW_LINE if ( isTriangular ( n ) ) : NEW_LINE INDENT print ( " The ▁ number ▁ is ▁ a ▁ triangular ▁ number " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ number ▁ is ▁ NOT ▁ a ▁ triangular ▁ number " ) NEW_LINE DEDENT
Convert from any base to decimal and vice versa | To return value of a char . For example , 2 is returned for '2' . 10 is returned for ' A ' , 11 for 'B ; Function to convert a number from given base ' b ' to decimal ; Initialize power of base ; Initialize result ; Decimal equivalent is str [ len - 1 ] * 1 + str [ len - 2 ] * base + str [ len - 3 ] * ( base ^ 2 ) + ... ; A digit in input number must be less than number 's base ; Driver code
' NEW_LINE def val ( c ) : NEW_LINE INDENT if c >= '0' and c <= '9' : NEW_LINE INDENT return ord ( c ) - ord ( '0' ) NEW_LINE DEDENT else : NEW_LINE INDENT return ord ( c ) - ord ( ' A ' ) + 10 ; NEW_LINE DEDENT DEDENT def toDeci ( str , base ) : NEW_LINE INDENT llen = len ( str ) NEW_LINE DEDENT power = 1 NEW_LINE num = 0 NEW_LINE INDENT for i in range ( llen - 1 , - 1 , - 1 ) : NEW_LINE INDENT if val ( str [ i ] ) >= base : NEW_LINE INDENT print ( ' Invalid ▁ Number ' ) NEW_LINE return - 1 NEW_LINE DEDENT num += val ( str [ i ] ) * power NEW_LINE power = power * base NEW_LINE DEDENT return num NEW_LINE DEDENT strr = "11A " NEW_LINE base = 16 NEW_LINE print ( ' Decimal ▁ equivalent ▁ of ' , strr , ' in ▁ base ' , base , ' is ' , toDeci ( strr , base ) ) NEW_LINE
Frobenius coin problem | Utility function to find gcd ; Function to print the desired output ; Solution doesn 't exist if GCD is not 1 ; Else apply the formula ; Driver Code
def gcd ( a , b ) : NEW_LINE INDENT while ( a != 0 ) : NEW_LINE INDENT c = a ; NEW_LINE a = b % a ; NEW_LINE b = c ; NEW_LINE DEDENT return b ; NEW_LINE DEDENT def forbenius ( X , Y ) : NEW_LINE INDENT if ( gcd ( X , Y ) != 1 ) : NEW_LINE INDENT print ( " NA " ) ; NEW_LINE return ; NEW_LINE DEDENT A = ( X * Y ) - ( X + Y ) ; NEW_LINE N = ( X - 1 ) * ( Y - 1 ) // 2 ; NEW_LINE print ( " Largest ▁ Amount ▁ = " , A ) ; NEW_LINE print ( " Total ▁ Count ▁ = " , N ) ; NEW_LINE DEDENT X = 2 ; NEW_LINE Y = 5 ; NEW_LINE forbenius ( X , Y ) ; NEW_LINE X = 5 ; NEW_LINE Y = 10 ; NEW_LINE print ( " " ) ; NEW_LINE forbenius ( X , Y ) ; NEW_LINE
Gray to Binary and Binary to Gray conversion | Helper function to xor two characters ; Helper function to flip the bit ; function to convert binary string to gray string ; MSB of gray code is same as binary code ; Compute remaining bits , next bit is computed by doing XOR of previous and current in Binary ; Concatenate XOR of previous bit with current bit ; function to convert gray code string to binary string ; MSB of binary code is same as gray code ; Compute remaining bits ; If current bit is 0 , concatenate previous bit ; Else , concatenate invert of previous bit ; Driver Code
def xor_c ( a , b ) : NEW_LINE INDENT return '0' if ( a == b ) else '1' ; NEW_LINE DEDENT def flip ( c ) : NEW_LINE INDENT return '1' if ( c == '0' ) else '0' ; NEW_LINE DEDENT def binarytoGray ( binary ) : NEW_LINE INDENT gray = " " ; NEW_LINE gray += binary [ 0 ] ; NEW_LINE for i in range ( 1 , len ( binary ) ) : NEW_LINE INDENT gray += xor_c ( binary [ i - 1 ] , binary [ i ] ) ; NEW_LINE DEDENT return gray ; NEW_LINE DEDENT def graytoBinary ( gray ) : NEW_LINE INDENT binary = " " ; NEW_LINE binary += gray [ 0 ] ; NEW_LINE for i in range ( 1 , len ( gray ) ) : NEW_LINE INDENT if ( gray [ i ] == '0' ) : NEW_LINE INDENT binary += binary [ i - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT binary += flip ( binary [ i - 1 ] ) ; NEW_LINE DEDENT DEDENT return binary ; NEW_LINE DEDENT binary = "01001" ; NEW_LINE print ( " Gray ▁ code ▁ of " , binary , " is " , binarytoGray ( binary ) ) ; NEW_LINE gray = "01101" ; NEW_LINE print ( " Binary ▁ code ▁ of " , gray , " is " , graytoBinary ( gray ) ) ; NEW_LINE
Solving f ( n ) = ( 1 ) + ( 2 * 3 ) + ( 4 * 5 * 6 ) . . . n using Recursion | Recursive function for finding sum of series calculated - number of terms till which sum of terms has been calculated current - number of terms for which sum has to be calculated N - Number of terms in the function to be calculated ; checking termination condition ; product of terms till current ; recursive call for adding terms next in the series ; input number of terms in the series ; invoking the function to calculate the sum
def seriesSum ( calculated , current , N ) : NEW_LINE INDENT i = calculated ; NEW_LINE cur = 1 ; NEW_LINE if ( current == N + 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT while ( i < calculated + current ) : NEW_LINE INDENT cur *= i ; NEW_LINE i += 1 ; NEW_LINE DEDENT return cur + seriesSum ( i , current + 1 , N ) ; NEW_LINE DEDENT N = 5 ; NEW_LINE print ( seriesSum ( 1 , 1 , N ) ) ; NEW_LINE
How to avoid overflow in modular multiplication ? | To compute ( a * b ) % mod ; res = 0 ; Initialize result ; If b is odd , add ' a ' to result ; Multiply ' a ' with 2 ; Divide b by 2 ; Return result ; Driver Code
def mulmod ( a , b , mod ) : NEW_LINE INDENT a = a % mod ; NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( b % 2 == 1 ) : NEW_LINE INDENT res = ( res + a ) % mod ; NEW_LINE DEDENT a = ( a * 2 ) % mod ; NEW_LINE b //= 2 ; NEW_LINE DEDENT return res % mod ; NEW_LINE DEDENT a = 9223372036854775807 ; NEW_LINE b = 9223372036854775807 ; NEW_LINE print ( mulmod ( a , b , 100000000000 ) ) ; NEW_LINE
Count inversions in an array | Set 3 ( Using BIT ) | Python3 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 . ; 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 ] ; 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 program
from bisect import bisect_left as lower_bound NEW_LINE def getSum ( BITree , index ) : NEW_LINE INDENT while ( index > 0 ) : NEW_LINE INDENT sum += BITree [ index ] NEW_LINE index -= index & ( - index ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def updateBIT ( BITree , n , index , val ) : NEW_LINE ' NEW_LINE INDENT while ( index <= n ) : NEW_LINE INDENT BITree [ index ] += val NEW_LINE DEDENT index += index & ( - index ) NEW_LINE DEDENT def convert ( arr , n ) : NEW_LINE INDENT temp = [ 0 ] * ( n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp [ i ] = arr [ i ] NEW_LINE DEDENT temp = sorted ( temp ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = lower_bound ( temp , arr [ i ] ) + 1 NEW_LINE DEDENT DEDENT def getInvCount ( arr , n ) : NEW_LINE INDENT convert ( arr , n ) NEW_LINE BIT = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT invcount += getSum ( BIT , arr [ i ] - 1 ) NEW_LINE updateBIT ( BIT , n , arr [ i ] , 1 ) NEW_LINE DEDENT return invcount NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 4 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Number ▁ of ▁ inversions ▁ are ▁ : ▁ " , getInvCount ( arr , n ) ) NEW_LINE DEDENT
Compute n ! under modulo p | Returns value of n ! % p ; Driver Code
def modFact ( n , p ) : NEW_LINE INDENT if n >= p : NEW_LINE INDENT return 0 NEW_LINE DEDENT result = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT result = ( result * i ) % p NEW_LINE DEDENT return result NEW_LINE DEDENT n = 25 ; p = 29 NEW_LINE print ( modFact ( n , p ) ) NEW_LINE
Chinese Remainder Theorem | Set 2 ( Inverse Modulo based Implementation ) | 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 method
def inv ( a , m ) : NEW_LINE INDENT m0 = m NEW_LINE x0 = 0 NEW_LINE x1 = 1 NEW_LINE if ( m == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( a > 1 ) : NEW_LINE INDENT q = a // m NEW_LINE t = m NEW_LINE m = a % m NEW_LINE a = t NEW_LINE t = x0 NEW_LINE x0 = x1 - q * x0 NEW_LINE x1 = t NEW_LINE DEDENT if ( x1 < 0 ) : NEW_LINE INDENT x1 = x1 + m0 NEW_LINE DEDENT return x1 NEW_LINE DEDENT def findMinX ( num , rem , k ) : NEW_LINE INDENT prod = 1 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT prod = prod * num [ i ] NEW_LINE DEDENT result = 0 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT pp = prod // num [ i ] NEW_LINE result = result + rem [ i ] * inv ( pp , num [ i ] ) * pp NEW_LINE DEDENT return result % prod NEW_LINE DEDENT num = [ 3 , 4 , 5 ] NEW_LINE rem = [ 2 , 3 , 1 ] NEW_LINE k = len ( num ) NEW_LINE print ( " x ▁ is ▁ " , findMinX ( num , rem , k ) ) NEW_LINE
Chinese Remainder Theorem | Set 1 ( Introduction ) | 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 forevery pair is 1 ) ; As per the Chinise 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
def findMinX ( num , rem , k ) : NEW_LINE INDENT while ( True ) : NEW_LINE INDENT j = 0 ; NEW_LINE while ( j < k ) : NEW_LINE INDENT if ( x % num [ j ] != rem [ j ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT j += 1 ; NEW_LINE DEDENT if ( j == k ) : NEW_LINE INDENT return x ; NEW_LINE DEDENT x += 1 ; NEW_LINE DEDENT DEDENT num = [ 3 , 4 , 5 ] ; NEW_LINE rem = [ 2 , 3 , 1 ] ; NEW_LINE k = len ( num ) ; NEW_LINE print ( " x ▁ is " , findMinX ( num , rem , k ) ) ; NEW_LINE
Fibonacci Coding | 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
N = 30 NEW_LINE fib = [ 0 for i in range ( N ) ] NEW_LINE def largestFiboLessOrEqual ( n ) : NEW_LINE fib [ 0 ] = 1 NEW_LINE fib [ 1 ] = 2 NEW_LINE INDENT i = 2 NEW_LINE while fib [ i - 1 ] <= n : NEW_LINE INDENT fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] NEW_LINE i += 1 NEW_LINE DEDENT return ( i - 2 ) NEW_LINE DEDENT def fibonacciEncoding ( n ) : NEW_LINE INDENT index = largestFiboLessOrEqual ( n ) NEW_LINE codeword = [ ' a ' for i in range ( index + 2 ) ] NEW_LINE i = index NEW_LINE while ( n ) : NEW_LINE INDENT codeword [ i ] = '1' NEW_LINE n = n - fib [ i ] NEW_LINE i = i - 1 NEW_LINE while ( i >= 0 and fib [ i ] > n ) : NEW_LINE INDENT codeword [ i ] = '0' NEW_LINE i = i - 1 NEW_LINE DEDENT DEDENT codeword [ index + 1 ] = '1' NEW_LINE return " " . join ( codeword ) NEW_LINE DEDENT n = 143 NEW_LINE print ( " Fibonacci ▁ code ▁ word ▁ for " , n , " is " , fibonacciEncoding ( n ) ) NEW_LINE
Print all Good numbers in given range | 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 Code ; Print good numbers in [ L , R ]
' NEW_LINE def isValid ( n , d ) : NEW_LINE INDENT digit = n % 10 ; NEW_LINE sum = digit ; NEW_LINE if ( digit == d ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT n = int ( n / 10 ) ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit = n % 10 ; NEW_LINE if ( digit == d or digit <= sum ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT else : NEW_LINE INDENT sum += digit ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def printGoodNumber ( L , R , d ) : NEW_LINE INDENT for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( isValid ( i , d ) ) : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT L = 410 ; NEW_LINE R = 520 ; NEW_LINE d = 3 ; NEW_LINE printGoodNumber ( L , R , d ) ; NEW_LINE
Count number of squares in a rectangle | 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
def countSquares ( m , n ) : NEW_LINE INDENT if ( n < m ) : NEW_LINE INDENT temp = m NEW_LINE m = n NEW_LINE n = temp NEW_LINE DEDENT return n * ( n + 1 ) * ( 3 * m - n + 1 ) // 6 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 4 NEW_LINE n = 3 NEW_LINE print ( " Count ▁ of ▁ squares ▁ is " , countSquares ( m , n ) ) NEW_LINE DEDENT
Zeckendorf 's Theorem (Non | Returns the greatest Fibonacci Number smaller than or equal to n . ; Corner cases ; Finds the greatest Fibonacci Number smaller than n . ; Prints Fibonacci Representation of n using greedy algorithm ; Find the greates Fibonacci Number smaller than or equal to n ; Print the found fibonacci number ; Reduce n ; Driver code test above functions
def nearestSmallerEqFib ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT f1 , f2 , f3 = 0 , 1 , 1 NEW_LINE while ( f3 <= n ) : NEW_LINE INDENT f1 = f2 ; NEW_LINE f2 = f3 ; NEW_LINE f3 = f1 + f2 ; NEW_LINE DEDENT return f2 ; NEW_LINE DEDENT def printFibRepresntation ( n ) : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT f = nearestSmallerEqFib ( n ) ; NEW_LINE print f , NEW_LINE n = n - f NEW_LINE DEDENT DEDENT n = 30 NEW_LINE print " Non - neighbouring ▁ Fibonacci ▁ Representation ▁ of " , n , " is " NEW_LINE printFibRepresntation ( n ) NEW_LINE
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
dp = [ [ [ - 1 for i in range ( 5 ) ] for i in range ( 501 ) ] for i in range ( 501 ) ] NEW_LINE def countWaysUtil ( n , parts , nextPart ) : NEW_LINE INDENT if ( parts == 0 and n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n <= 0 or parts <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ n ] [ nextPart ] [ parts ] != - 1 ) : NEW_LINE INDENT return dp [ n ] [ nextPart ] [ parts ] NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT for i in range ( nextPart , n + 1 ) : NEW_LINE INDENT ans += countWaysUtil ( n - i , parts - 1 , i ) NEW_LINE DEDENT dp [ n ] [ nextPart ] [ parts ] = ans NEW_LINE return ( ans ) NEW_LINE DEDENT def countWays ( n ) : NEW_LINE INDENT return countWaysUtil ( n , 4 , 1 ) NEW_LINE DEDENT n = 8 NEW_LINE print ( countWays ( n ) ) NEW_LINE
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
def simpleSieve ( limit ) : NEW_LINE INDENT mark = [ True for i in range ( limit ) ] NEW_LINE for p in range ( p * p , limit - 1 , 1 ) : NEW_LINE INDENT if ( mark [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , limit - 1 , p ) : NEW_LINE INDENT mark [ i ] = False NEW_LINE DEDENT DEDENT DEDENT for p in range ( 2 , limit - 1 , 1 ) : NEW_LINE INDENT if ( mark [ p ] == True ) : NEW_LINE INDENT print ( p , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT
Segmented Sieve | Python3 program to print all primes smaller than n , using segmented sieve ; This method finds all primes smaller than ' limit ' using simple sieve of eratosthenes . It also stores found primes in list prime ; Create a boolean list " mark [ 0 . . n - 1 ] " and initialize all entries of it as True . A value in mark [ p ] will finally be False if ' p ' is Not a prime , else True . ; If p is not changed , then it is a prime ; Update all multiples of p ; Print all prime numbers and store them in prime ; Prints all prime numbers smaller than 'n ; Compute all primes smaller than or equal to square root of n using simple sieve ; Divide the range [ 0. . n - 1 ] in different segments We have chosen segment size as sqrt ( n ) . ; While all segments of range [ 0. . n - 1 ] are not processed , process one segment at a time ; To mark primes in current range . A value in mark [ i ] will finally be False if ' i - low ' is Not a prime , else True . ; Use the found primes by simpleSieve ( ) to find primes in current range ; Find the minimum number in [ low . . high ] that is a multiple of prime [ i ] ( divisible by prime [ i ] ) For example , if low is 31 and prime [ i ] is 3 , we start with 33. ; Mark multiples of prime [ i ] in [ low . . high ] : We are marking j - low for j , i . e . each number in range [ low , high ] is mapped to [ 0 , high - low ] so if range is [ 50 , 100 ] marking 50 corresponds to marking 0 , marking 51 corresponds to 1 and so on . In this way we need to allocate space only for range ; Numbers which are not marked as False are prime ; Update low and high for next segment ; Driver Code
import math NEW_LINE prime = [ ] NEW_LINE def simpleSieve ( limit ) : NEW_LINE INDENT mark = [ True for i in range ( limit + 1 ) ] NEW_LINE p = 2 NEW_LINE while ( p * p <= limit ) : NEW_LINE INDENT if ( mark [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , limit + 1 , p ) : NEW_LINE INDENT mark [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , limit ) : NEW_LINE INDENT if mark [ p ] : NEW_LINE INDENT prime . append ( p ) NEW_LINE print ( p , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE def segmentedSieve ( n ) : NEW_LINE INDENT limit = int ( math . floor ( math . sqrt ( n ) ) + 1 ) NEW_LINE simpleSieve ( limit ) NEW_LINE low = limit NEW_LINE high = limit * 2 NEW_LINE while low < n : NEW_LINE INDENT if high >= n : NEW_LINE INDENT high = n NEW_LINE DEDENT mark = [ True for i in range ( limit + 1 ) ] NEW_LINE for i in range ( len ( prime ) ) : NEW_LINE INDENT loLim = int ( math . floor ( low / prime [ i ] ) * prime [ i ] ) NEW_LINE if loLim < low : NEW_LINE INDENT loLim += prime [ i ] NEW_LINE DEDENT for j in range ( loLim , high , prime [ i ] ) : NEW_LINE INDENT mark [ j - low ] = False NEW_LINE DEDENT DEDENT for i in range ( low , high ) : NEW_LINE INDENT if mark [ i - low ] : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT low = low + limit NEW_LINE high = high + limit NEW_LINE DEDENT DEDENT n = 100 NEW_LINE print ( " Primes ▁ smaller ▁ than " , n , " : " ) NEW_LINE segmentedSieve ( 100 ) NEW_LINE
Find the smallest twins in given range | Python3 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 Code
import math NEW_LINE def printTwins ( low , high ) : NEW_LINE INDENT prime = [ True ] * ( high + 1 ) ; NEW_LINE twin = False ; NEW_LINE prime [ 0 ] = prime [ 1 ] = False ; NEW_LINE for p in range ( 2 , int ( math . floor ( math . sqrt ( high ) ) + 2 ) ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , high + 1 , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( low , high + 1 ) : NEW_LINE INDENT if ( prime [ i ] and prime [ i + 2 ] ) : NEW_LINE INDENT print ( " Smallest ▁ twins ▁ in ▁ given ▁ range : ▁ ( " , i , " , " , ( i + 2 ) , " ) " ) ; NEW_LINE twin = True ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( twin == False ) : NEW_LINE INDENT print ( " No ▁ such ▁ pair ▁ exists " ) ; NEW_LINE DEDENT DEDENT printTwins ( 10 , 100 ) ; NEW_LINE
Check if a given number is Fancy | Python 3 program to find if a given number is fancy or not . ; To store mappings of fancy pair characters . For example 6 is paired with 9 and 9 is paired with 6. ; Find number of digits in given number ; Traverse from both ends , and compare characters one by one ; If current characters at both ends are not fancy pairs ; Driver program
def isFancy ( num ) : NEW_LINE INDENT fp = { } NEW_LINE fp [ '0' ] = '0' NEW_LINE fp [ '1' ] = '1' NEW_LINE fp [ '6' ] = '9' NEW_LINE fp [ '8' ] = '8' NEW_LINE fp [ '9' ] = '6' NEW_LINE n = len ( num ) NEW_LINE l = 0 NEW_LINE r = n - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT if ( num [ l ] not in fp or fp [ num [ l ] ] != num [ r ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "9088806" NEW_LINE if isFancy ( st ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Find Next Sparse Number | Python3 program to find next sparse number ; Find binary representation of x and store it in bin [ ] . bin [ 0 ] contains least significant bit ( LSB ) , next bit is in bin [ 1 ] , and so on . ; There my be extra bit in result , so add one extra bit ; The position till which all bits are finalized ; Start from second bit ( next to LSB ) ; If current bit and its previous bit are 1 , but next bit is not 1. ; Make the next bit 1 ; Make all bits before current bit as 0 to make sure that we get the smallest next number ; Store position of the bit set so that this bit and bits before it are not changed next time . ; Find decimal equivalent of modified bin [ ] ; Driver Code
def nextSparse ( x ) : NEW_LINE INDENT bin = [ ] NEW_LINE while ( x != 0 ) : NEW_LINE INDENT bin . append ( x & 1 ) NEW_LINE x >>= 1 NEW_LINE DEDENT bin . append ( 0 ) NEW_LINE last_final = 0 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( ( bin [ i ] == 1 and bin [ i - 1 ] == 1 and bin [ i + 1 ] != 1 ) ) : NEW_LINE INDENT bin [ i + 1 ] = 1 NEW_LINE for j in range ( i , last_final - 1 , - 1 ) : NEW_LINE INDENT bin [ j ] = 0 NEW_LINE DEDENT last_final = i + 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += bin [ i ] * ( 1 << i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 38 NEW_LINE print ( " Next ▁ Sparse ▁ Number ▁ is " , nextSparse ( x ) ) NEW_LINE DEDENT
Count number of subsets of a set with GCD equal to a given number | n is size of arr [ ] and m is sizeof gcd [ ] ; Map to store frequency of array elements ; Map to store number of subsets with given gcd ; Initialize maximum element . Assumption : all array elements are positive . ; Find maximum element in array and fill frequency map . ; Run a loop from max element to 1 to find subsets with all gcds ; Run a loop for all multiples of i ; Sum the frequencies of every element which is a multiple of i ; Excluding those subsets which have gcd > i but not i i . e . which have gcd as multiple of i in the subset . for ex : { 2 , 3 , 4 } considering i = 2 and subset we need to exclude are those having gcd as 4 ; Number of subsets with GCD equal to ' i ' is pow ( 2 , add ) - 1 - sub ; Driver Code
def countSubsets ( arr , n , gcd , m ) : NEW_LINE INDENT freq = dict ( ) NEW_LINE subsets = dict ( ) NEW_LINE arrMax = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT arrMax = max ( arrMax , arr [ i ] ) NEW_LINE if arr [ i ] not in freq : NEW_LINE INDENT freq [ arr [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT DEDENT for i in range ( arrMax , 0 , - 1 ) : NEW_LINE INDENT sub = 0 NEW_LINE add = 0 NEW_LINE if i in freq : NEW_LINE INDENT add = freq [ i ] NEW_LINE DEDENT j = 2 NEW_LINE while j * i <= arrMax : NEW_LINE INDENT if j * i in freq : NEW_LINE INDENT add += freq [ j * i ] NEW_LINE DEDENT sub += subsets [ j * i ] NEW_LINE j += 1 NEW_LINE DEDENT subsets [ i ] = ( 1 << add ) - 1 - sub NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT print ( " Number ▁ of ▁ subsets ▁ with ▁ gcd ▁ % d ▁ is ▁ % d " % ( gcd [ i ] , subsets [ gcd [ i ] ] ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT gcd = [ 2 , 3 ] NEW_LINE arr = [ 9 , 6 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE m = len ( gcd ) NEW_LINE countSubsets ( arr , n , gcd , m ) NEW_LINE DEDENT
Sum of bit differences among all pairs | Python program to compute sum of pairwise bit differences ; traverse over all bits ; count number of elements with i 'th bit set ; Add " count ▁ * ▁ ( n ▁ - ▁ count ) ▁ * ▁ 2" to the answer ; Driver prorgram
def sumBitDifferences ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , 32 ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( ( arr [ j ] & ( 1 << i ) ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT ans += ( count * ( n - count ) * 2 ) ; NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 3 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( sumBitDifferences ( arr , n ) ) NEW_LINE
Print all non | 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
def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT def generateUtil ( x , arr , curr_sum , curr_idx ) : NEW_LINE INDENT if ( curr_sum == x ) : NEW_LINE INDENT printArr ( arr , curr_idx ) NEW_LINE return NEW_LINE DEDENT num = 1 NEW_LINE while ( num <= x - curr_sum and ( curr_idx == 0 or num <= arr [ curr_idx - 1 ] ) ) : NEW_LINE INDENT arr [ curr_idx ] = num NEW_LINE generateUtil ( x , arr , curr_sum + num , curr_idx + 1 ) NEW_LINE num += 1 NEW_LINE DEDENT DEDENT def generate ( x ) : NEW_LINE INDENT arr = [ 0 ] * x NEW_LINE generateUtil ( x , arr , 0 , 0 ) NEW_LINE DEDENT x = 5 NEW_LINE generate ( x ) NEW_LINE
Perfect Number | 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
def isPerfect ( n ) : NEW_LINE INDENT sum = 1 NEW_LINE i = 2 NEW_LINE while i * i <= n : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT sum = sum + i + n / i NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return ( True if sum == n and n != 1 else False ) NEW_LINE DEDENT print ( " Below ▁ are ▁ all ▁ perfect ▁ numbers ▁ till ▁ 10000" ) NEW_LINE n = 2 NEW_LINE for n in range ( 10000 ) : NEW_LINE INDENT if isPerfect ( n ) : NEW_LINE INDENT print ( n , " ▁ is ▁ a ▁ perfect ▁ number " ) NEW_LINE DEDENT DEDENT
Check if a given number can be represented in given a no . of digits in any base | Returns true if ' num ' can be represented using ' 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
' NEW_LINE def checkUtil ( num , dig , base ) : NEW_LINE INDENT if ( dig == 1 and num < base ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( dig > 1 and num >= base ) : NEW_LINE INDENT return checkUtil ( num / base , - - dig , base ) NEW_LINE DEDENT return False NEW_LINE DEDENT def check ( num , dig ) : NEW_LINE INDENT for base in range ( 2 , 33 ) : NEW_LINE INDENT if ( checkUtil ( num , dig , base ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT num = 8 NEW_LINE dig = 3 NEW_LINE if ( check ( num , dig ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
How to compute mod of a big number ? | Function to compute num ( mod a ) ; Initialize result ; One by one process all digits of 'num ; Driver program
def mod ( num , a ) : NEW_LINE INDENT res = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 0 , len ( num ) ) : NEW_LINE INDENT res = ( res * 10 + int ( num [ i ] ) ) % a NEW_LINE DEDENT return res NEW_LINE DEDENT num = "12316767678678" NEW_LINE print ( mod ( num , 10 ) ) NEW_LINE
Modular multiplicative inverse | A naive method to find modulor multiplicative inverse of ' a ' under modulo 'm ; Driver Code ; Function call
' NEW_LINE def modInverse ( a , m ) : NEW_LINE INDENT for x in range ( 1 , m ) : NEW_LINE INDENT if ( ( ( a % m ) * ( x % m ) ) % m == 1 ) : NEW_LINE INDENT return x NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT a = 3 NEW_LINE m = 11 NEW_LINE print ( modInverse ( a , m ) ) NEW_LINE
Modular multiplicative inverse | 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
def modInverse ( a , m ) : NEW_LINE INDENT m0 = m NEW_LINE y = 0 NEW_LINE x = 1 NEW_LINE if ( m == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( a > 1 ) : NEW_LINE INDENT q = a // m NEW_LINE t = m NEW_LINE m = a % m NEW_LINE a = t NEW_LINE t = y NEW_LINE y = x - q * y NEW_LINE x = t NEW_LINE DEDENT if ( x < 0 ) : NEW_LINE INDENT x = x + m0 NEW_LINE DEDENT return x NEW_LINE DEDENT a = 3 NEW_LINE m = 11 NEW_LINE print ( " Modular ▁ multiplicative ▁ inverse ▁ is " , modInverse ( a , m ) ) NEW_LINE
Euler 's Totient Function | Function to return gcd of a and b ; A simple method to evaluate Euler Totient Function ; Driver Code
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def phi ( n ) : NEW_LINE INDENT result = 1 NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( gcd ( i , n ) == 1 ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT for n in range ( 1 , 11 ) : NEW_LINE INDENT print ( " phi ( " , n , " ) ▁ = ▁ " , phi ( n ) , sep = " " ) NEW_LINE DEDENT
Euler 's Totient Function | Python 3 program to calculate Euler ' s ▁ Totient ▁ Function ▁ using ▁ Euler ' s product formula ; 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 program to test above function
def phi ( n ) : NEW_LINE INDENT p = 2 NEW_LINE while p * p <= n : NEW_LINE INDENT if n % p == 0 : NEW_LINE INDENT while n % p == 0 : NEW_LINE INDENT n = n // p NEW_LINE DEDENT result = result * ( 1.0 - ( 1.0 / float ( p ) ) ) NEW_LINE DEDENT p = p + 1 NEW_LINE DEDENT if n > 1 : NEW_LINE INDENT result = result * ( 1.0 - ( 1.0 / float ( n ) ) ) NEW_LINE DEDENT return int ( result ) NEW_LINE DEDENT for n in range ( 1 , 11 ) : NEW_LINE INDENT print ( " phi ( " , n , " ) ▁ = ▁ " , phi ( n ) ) NEW_LINE DEDENT
Program to find remainder without using modulo or % operator | Function to return num % divisor without using % ( modulo ) operator ; While divisor is smaller than n , keep subtracting it from num ; Driver code
def getRemainder ( num , divisor ) : NEW_LINE INDENT while ( num >= divisor ) : NEW_LINE INDENT num -= divisor ; NEW_LINE DEDENT return num ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num = 100 ; divisor = 7 ; NEW_LINE print ( getRemainder ( num , divisor ) ) ; NEW_LINE DEDENT
Efficient Program to Compute Sum of Series 1 / 1 ! + 1 / 2 ! + 1 / 3 ! + 1 / 4 ! + . . + 1 / n ! | Function to find factorial of a number ; A Simple Function to return value of 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; Driver program to test above functions
def factorial ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res *= i NEW_LINE DEDENT return res NEW_LINE DEDENT def sum ( n ) : NEW_LINE INDENT s = 0.0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT s += 1.0 / factorial ( i ) NEW_LINE DEDENT print ( s ) NEW_LINE DEDENT n = 5 NEW_LINE sum ( n ) NEW_LINE
Find the number of valid parentheses expressions of given length | 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 Code
def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 ; NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k ; NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT res *= ( n - i ) ; NEW_LINE res /= ( i + 1 ) ; NEW_LINE DEDENT return int ( res ) ; NEW_LINE DEDENT def catalan ( n ) : NEW_LINE INDENT c = binomialCoeff ( 2 * n , n ) ; NEW_LINE return int ( c / ( n + 1 ) ) ; NEW_LINE DEDENT def findWays ( n ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT return catalan ( int ( n / 2 ) ) ; NEW_LINE DEDENT n = 6 ; NEW_LINE print ( " Total ▁ possible ▁ expressions ▁ of ▁ length " , n , " is " , findWays ( 6 ) ) ; NEW_LINE
Program to evaluate simple expressions | 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 Code
def isOperand ( c ) : NEW_LINE INDENT return ( c >= '0' and c <= '9' ) ; NEW_LINE DEDENT def value ( c ) : NEW_LINE INDENT return ord ( c ) - ord ( '0' ) ; NEW_LINE DEDENT def evaluate ( exp ) : NEW_LINE INDENT len1 = len ( exp ) ; NEW_LINE if ( len1 == 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT res = value ( exp [ 0 ] ) ; NEW_LINE for i in range ( 1 , len1 , 2 ) : NEW_LINE INDENT opr = exp [ i ] ; NEW_LINE opd = exp [ i + 1 ] ; NEW_LINE if ( isOperand ( opd ) == False ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( opr == ' + ' ) : NEW_LINE INDENT res += value ( opd ) ; NEW_LINE DEDENT elif ( opr == ' - ' ) : NEW_LINE INDENT res -= int ( value ( opd ) ) ; NEW_LINE DEDENT elif ( opr == ' * ' ) : NEW_LINE INDENT res *= int ( value ( opd ) ) ; NEW_LINE DEDENT elif ( opr == ' / ' ) : NEW_LINE INDENT res /= int ( value ( opd ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT expr1 = "1 + 2*5 + 3" ; NEW_LINE res = evaluate ( expr1 ) ; NEW_LINE print ( expr1 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr1 , " is " , res ) ; NEW_LINE expr2 = "1 + 2*3" ; NEW_LINE res = evaluate ( expr2 ) ; NEW_LINE print ( expr2 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr2 , " is " , res ) ; NEW_LINE expr3 = "4-2 + 6*3" ; NEW_LINE res = evaluate ( expr3 ) ; NEW_LINE print ( expr3 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr3 , " is " , res ) ; NEW_LINE expr4 = "1 + + 2" ; NEW_LINE res = evaluate ( expr4 ) ; NEW_LINE print ( expr4 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr4 , " is " , res ) ; NEW_LINE
Program to print first n Fibonacci Numbers | Set 1 | Function to print first n Fibonacci Numbers ; Driven code
def printFibonacciNumbers ( n ) : NEW_LINE INDENT f1 = 0 NEW_LINE f2 = 1 NEW_LINE if ( n < 1 ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( f1 , end = " ▁ " ) NEW_LINE for x in range ( 1 , n ) : NEW_LINE INDENT print ( f2 , end = " ▁ " ) NEW_LINE next = f1 + f2 NEW_LINE f1 = f2 NEW_LINE f2 = next NEW_LINE DEDENT DEDENT printFibonacciNumbers ( 7 ) NEW_LINE
Program to find LCM of two numbers | Recursive function to return gcd of a and b ; Function to return LCM of two numbers ; Driver program to test above function
def gcd ( a , b ) : NEW_LINE INDENT if a == 0 : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def lcm ( a , b ) : NEW_LINE INDENT return ( a / gcd ( a , b ) ) * b NEW_LINE DEDENT a = 15 NEW_LINE b = 20 NEW_LINE print ( ' LCM ▁ of ' , a , ' and ' , b , ' is ' , lcm ( a , b ) ) NEW_LINE
Program to find sum of elements in a given array | Driver code ; Calling accumulate function , passing first , last element and initial sum , which is 0 in this case .
if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , 3 , 4 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Sum ▁ of ▁ given ▁ array ▁ is ▁ " , sum ( arr ) ) ; NEW_LINE DEDENT
Program to convert a given number to words | 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
def convert_to_words ( num ) : NEW_LINE INDENT l = len ( num ) NEW_LINE if ( l == 0 ) : NEW_LINE INDENT print ( " empty ▁ string " ) NEW_LINE return NEW_LINE DEDENT if ( l > 4 ) : NEW_LINE INDENT print ( " Length ▁ more ▁ than ▁ 4 ▁ is ▁ not ▁ supported " ) NEW_LINE return NEW_LINE DEDENT single_digits = [ " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " ] NEW_LINE two_digits = [ " " , " ten " , " eleven " , " twelve " , " thirteen " , " fourteen " , " fifteen " , " sixteen " , " seventeen " , " eighteen " , " nineteen " ] NEW_LINE tens_multiple = [ " " , " " , " twenty " , " thirty " , " forty " , " fifty " , " sixty " , " seventy " , " eighty " , " ninety " ] NEW_LINE tens_power = [ " hundred " , " thousand " ] NEW_LINE print ( num , " : " , end = " ▁ " ) NEW_LINE if ( l == 1 ) : NEW_LINE INDENT print ( single_digits [ ord ( num [ 0 ] ) - 48 ] ) NEW_LINE return NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT x = 0 NEW_LINE while ( x < len ( num ) ) : NEW_LINE INDENT if ( l >= 3 ) : NEW_LINE INDENT if ( ord ( num [ x ] ) - 48 != 0 ) : NEW_LINE INDENT print ( single_digits [ ord ( num [ x ] ) - 48 ] , end = " ▁ " ) NEW_LINE print ( tens_power [ l - 3 ] , end = " ▁ " ) NEW_LINE DEDENT l -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( ord ( num [ x ] ) - 48 == 1 ) : NEW_LINE INDENT sum = ( ord ( num [ x ] ) - 48 + ord ( num [ x + 1 ] ) - 48 ) NEW_LINE print ( two_digits [ sum ] ) NEW_LINE return NEW_LINE DEDENT elif ( ord ( num [ x ] ) - 48 == 2 and ord ( num [ x + 1 ] ) - 48 == 0 ) : NEW_LINE INDENT print ( " twenty " ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT i = ord ( num [ x ] ) - 48 NEW_LINE if ( i > 0 ) : NEW_LINE INDENT print ( tens_multiple [ i ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " " , end = " " ) NEW_LINE DEDENT x += 1 NEW_LINE if ( ord ( num [ x ] ) - 48 != 0 ) : NEW_LINE INDENT print ( single_digits [ ord ( num [ x ] ) - 48 ] ) NEW_LINE DEDENT DEDENT DEDENT x += 1 NEW_LINE DEDENT DEDENT
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
MAX = 11 ; NEW_LINE def isMultipleof5 ( n ) : NEW_LINE INDENT s = str ( n ) ; NEW_LINE l = len ( s ) ; NEW_LINE if ( s [ l - 1 ] == '5' or s [ l - 1 ] == '0' ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT n = 19 ; NEW_LINE if ( isMultipleof5 ( n ) == True ) : NEW_LINE INDENT print ( n , " is ▁ multiple ▁ of ▁ 5" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( n , " is ▁ not ▁ a ▁ multiple ▁ of ▁ 5" ) ; NEW_LINE DEDENT
Check if there are T number of continuous of blocks of 0 s or not in given Binary Matrix | python program for the above approach ; Stores the moves in the matrix ; Function to find if the current cell lies in the matrix or not ; Function to perform the DFS Traversal ; Iterate over the direction vector ; DFS Call ; Function to check if it satisfy the given criteria or not ; Keeps the count of cell having value as 0 ; If condition doesn 't satisfy ; Keeps the track of unvisted cell having values 0 ; Increasing count of black_spot ; Find the GCD of N and M ; Print the result ; Driver Code
import math NEW_LINE M = 1000000000 + 7 NEW_LINE directions = [ [ 0 , 1 ] , [ - 1 , 0 ] , [ 0 , - 1 ] , [ 1 , 0 ] , [ 1 , 1 ] , [ - 1 , - 1 ] , [ - 1 , 1 ] , [ 1 , - 1 ] ] NEW_LINE def isInside ( i , j , N , M ) : NEW_LINE INDENT if ( i >= 0 and i < N and j >= 0 and j < M ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def DFS ( mat , N , M , i , j , visited ) : NEW_LINE INDENT if ( visited [ i ] [ j ] == True ) : NEW_LINE INDENT return NEW_LINE DEDENT visited [ i ] [ j ] = True NEW_LINE for it in directions : NEW_LINE INDENT I = i + it [ 0 ] NEW_LINE J = j + it [ 1 ] NEW_LINE if ( isInside ( I , J , N , M ) ) : NEW_LINE INDENT if ( mat [ I ] [ J ] == 0 ) : NEW_LINE INDENT DFS ( mat , N , M , I , J , visited ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def check ( N , M , mat ) : NEW_LINE INDENT black = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , M ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 0 ) : NEW_LINE INDENT black += 1 NEW_LINE DEDENT DEDENT DEDENT if ( black < 2 * ( max ( N , M ) ) ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE return NEW_LINE DEDENT visited = [ ] NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT temp = [ ] NEW_LINE for j in range ( 0 , M ) : NEW_LINE INDENT temp . append ( False ) NEW_LINE DEDENT visited . append ( temp ) NEW_LINE DEDENT black_spots = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , M ) : NEW_LINE INDENT if ( visited [ i ] [ j ] == False and mat [ i ] [ j ] == 0 ) : NEW_LINE INDENT black_spots += 1 NEW_LINE DFS ( mat , N , M , i , j , visited ) NEW_LINE DEDENT DEDENT DEDENT T = math . gcd ( N , M ) NEW_LINE if black_spots >= T : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE M = 3 NEW_LINE mat = [ [ 0 , 0 , 1 ] , [ 1 , 1 , 1 ] , [ 0 , 0 , 1 ] ] NEW_LINE check ( M , N , mat ) NEW_LINE DEDENT
Count subsequences having odd Bitwise OR values in an array | 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 [ ]
def countSubsequences ( arr ) : NEW_LINE INDENT odd = 0 ; NEW_LINE even = 0 ; NEW_LINE for x in arr : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT odd += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT even += 1 ; NEW_LINE DEDENT DEDENT return ( ( 1 << odd ) - 1 ) * ( 1 << even ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 1 ] ; NEW_LINE print ( countSubsequences ( arr ) ) ; NEW_LINE DEDENT
Compress a Binary Tree from top to bottom with overlapping condition | Structure of a node of th tree ; Function to compress all the nodes on the same vertical line ; Stores node by compressing all nodes on the current vertical line ; Check if i - th bit of current bit set or not ; Iterate over the range [ 0 , 31 ] ; Stores count of set bits at i - th positions ; Stores count of clear bits at i - th positions ; Traverse the array ; If i - th bit of current element is set ; Update S ; Update NS ; If count of set bits at i - th position is greater than count of clear bits ; Update ans ; Update getBit ; Function to compress all the nodes on the same vertical line with a single node that satisfies the condition ; Map all the nodes on the same vertical line ; Function to traverse the tree and map all the nodes of same vertical line to vertical distance ; Storing the values in the map ; Recursive calls on left and right subtree ; Getting the range of horizontal distances ; Driver Code ; Function Call
class TreeNode : NEW_LINE INDENT def __init__ ( self , val = ' ' , left = None , right = None ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def evalComp ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE getBit = 1 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT S = 0 NEW_LINE NS = 0 NEW_LINE for j in arr : NEW_LINE INDENT if getBit & j : NEW_LINE INDENT S += 1 NEW_LINE DEDENT else : NEW_LINE INDENT NS += 1 NEW_LINE DEDENT DEDENT if S > NS : NEW_LINE INDENT ans += 2 ** i NEW_LINE DEDENT getBit <<= 1 NEW_LINE DEDENT print ( ans , end = " ▁ " ) NEW_LINE DEDENT def compressTree ( root ) : NEW_LINE INDENT mp = { } NEW_LINE def Trav ( root , hd ) : NEW_LINE INDENT if not root : NEW_LINE INDENT return NEW_LINE DEDENT if hd not in mp : NEW_LINE INDENT mp [ hd ] = [ root . val ] NEW_LINE DEDENT else : NEW_LINE INDENT mp [ hd ] . append ( root . val ) NEW_LINE DEDENT Trav ( root . left , hd - 1 ) NEW_LINE Trav ( root . right , hd + 1 ) NEW_LINE DEDENT Trav ( root , 0 ) NEW_LINE lower = min ( mp . keys ( ) ) NEW_LINE upper = max ( mp . keys ( ) ) NEW_LINE for i in range ( lower , upper + 1 ) : NEW_LINE INDENT evalComp ( mp [ i ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = TreeNode ( 5 ) NEW_LINE root . left = TreeNode ( 3 ) NEW_LINE root . right = TreeNode ( 2 ) NEW_LINE root . left . left = TreeNode ( 1 ) NEW_LINE root . left . right = TreeNode ( 4 ) NEW_LINE root . right . left = TreeNode ( 1 ) NEW_LINE root . right . right = TreeNode ( 2 ) NEW_LINE compressTree ( root ) NEW_LINE DEDENT
Bitwise OR of Bitwise AND of all subsets of an Array for Q queries | 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 ; Given Input ; Function Call
def Or_of_Ands_for_each_query ( arr , n , queries , q ) : NEW_LINE INDENT bits = [ 0 for x in range ( 32 ) ] NEW_LINE for i in range ( 0 , 32 ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( ( 1 << i ) & arr [ j ] ) : NEW_LINE INDENT bits [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT for p in range ( 0 , q ) : NEW_LINE INDENT for i in range ( 0 , 32 ) : NEW_LINE INDENT if ( ( 1 << i ) & arr [ queries [ p ] [ 0 ] ] ) : NEW_LINE INDENT bits [ i ] -= 1 NEW_LINE DEDENT if ( queries [ p ] [ 1 ] & ( 1 << i ) ) : NEW_LINE INDENT bits [ i ] += 1 NEW_LINE DEDENT DEDENT arr [ queries [ p ] [ 0 ] ] = queries [ p ] [ 1 ] NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , 32 ) : NEW_LINE INDENT if ( bits [ i ] != 0 ) : NEW_LINE INDENT ans |= ( 1 << i ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT DEDENT n = 3 NEW_LINE q = 2 NEW_LINE arr = [ 3 , 5 , 7 ] NEW_LINE queries = [ [ 1 , 2 ] , [ 2 , 1 ] ] NEW_LINE Or_of_Ands_for_each_query ( arr , n , queries , q ) NEW_LINE
Find XOR sum of Bitwise AND of all pairs from given two Arrays | 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
def XorSum ( A , B , N , M ) : NEW_LINE INDENT ans = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( ans == - 1 ) : NEW_LINE INDENT ans = ( A [ i ] & B [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT ans ^= ( A [ i ] & B [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 5 ] NEW_LINE B = [ 2 , 3 ] NEW_LINE N = len ( A ) NEW_LINE M = len ( B ) NEW_LINE print ( XorSum ( A , B , N , M ) ) NEW_LINE DEDENT
Shortest path length between two given nodes such that adjacent nodes are at bit difference 2 | 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
def countbitdiff ( xo ) : NEW_LINE INDENT count = 0 NEW_LINE while ( xo ) : NEW_LINE INDENT if ( xo % 2 == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT xo = xo // 2 NEW_LINE DEDENT return count NEW_LINE DEDENT def shortestPath ( n , a , b ) : NEW_LINE INDENT xorVal = a ^ b NEW_LINE cnt = countbitdiff ( xorVal ) NEW_LINE if ( cnt % 2 == 0 ) : NEW_LINE INDENT print ( cnt // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 15 NEW_LINE a , b = 15 , 3 NEW_LINE shortestPath ( n , a , b ) NEW_LINE DEDENT
Modify a matrix by converting each element to XOR of its digits | Python3 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
M = 3 NEW_LINE N = 3 NEW_LINE def findXOR ( X ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( X ) : NEW_LINE INDENT ans ^= ( X % 10 ) NEW_LINE X //= 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT def printXORmatrix ( arr ) : NEW_LINE INDENT for i in range ( 3 ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def convertXOR ( arr ) : NEW_LINE INDENT for i in range ( 3 ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT X = arr [ i ] [ j ] NEW_LINE temp = findXOR ( X ) NEW_LINE arr [ i ] [ j ] = temp NEW_LINE DEDENT DEDENT printXORmatrix ( arr ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 27 , 173 , 5 ] , [ 21 , 6 , 624 ] , [ 5 , 321 , 49 ] ] NEW_LINE convertXOR ( arr ) NEW_LINE DEDENT
Sum of Bitwise AND of sum of pairs and their Bitwise AND from a given array | Python 3 program for the above approach ; Function to find the sum of Bitwise AND of sum of pairs and their Bitwise AND from a given array ; Stores the total sum ; Check if jth bit is set ; Stores the right shifted element by ( i + 1 ) ; Update the value of X ; Push in vector vec ; Sort the vector in ascending order ; Traverse the vector vec ; Stores the value 2 ^ ( i + 1 ) - 2 ^ ( i ) - vec [ j ] ; Stores count of numbers whose value > Y ; Update the ans ; Return the ans ; Driver Code
M = 1000000007 NEW_LINE from bisect import bisect_left NEW_LINE def findSum ( A , N ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 30 ) : NEW_LINE INDENT vec = [ ] NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( ( A [ j ] >> i ) & 1 ) : NEW_LINE INDENT X = ( A [ j ] >> ( i + 1 ) ) NEW_LINE X = X * ( 1 << ( i + 1 ) ) NEW_LINE X %= M NEW_LINE vec . append ( A [ j ] - X ) NEW_LINE DEDENT DEDENT vec . sort ( reverse = False ) NEW_LINE for j in range ( len ( vec ) ) : NEW_LINE INDENT Y = ( 1 << ( i + 1 ) ) + ( 1 << i ) - vec [ j ] NEW_LINE temp = vec [ j + 1 : ] NEW_LINE idx = int ( bisect_left ( temp , Y ) ) NEW_LINE ans += ( ( len ( vec ) - idx ) * ( 1 << i ) ) NEW_LINE ans %= M NEW_LINE DEDENT DEDENT ans /= 7 NEW_LINE print ( int ( ans % M ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE findSum ( arr , N ) NEW_LINE DEDENT
Count subarrays made up of elements having exactly K set bits | 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
def countSet ( N ) : NEW_LINE INDENT ans = 0 NEW_LINE while N : NEW_LINE INDENT ans += N & 1 NEW_LINE N >>= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def countSub ( arr , k ) : NEW_LINE INDENT ans = 0 NEW_LINE setK = 0 NEW_LINE for i in arr : NEW_LINE INDENT if countSet ( i ) == k : NEW_LINE INDENT setK += 1 NEW_LINE DEDENT else : NEW_LINE INDENT setK = 0 NEW_LINE DEDENT ans += setK NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 4 , 2 , 1 , 5 , 6 ] NEW_LINE K = 2 NEW_LINE print ( countSub ( arr , K ) ) NEW_LINE
Count subarrays having odd Bitwise XOR | 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
def oddXorSubarray ( a , n ) : NEW_LINE INDENT odd = 0 NEW_LINE c_odd = 0 NEW_LINE result = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] & 1 ) : NEW_LINE INDENT odd = not odd NEW_LINE DEDENT if ( odd ) : NEW_LINE INDENT c_odd += 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT result += c_odd NEW_LINE if ( a [ i ] & 1 ) : NEW_LINE INDENT c_odd = ( n - i - c_odd ) NEW_LINE DEDENT DEDENT print ( result ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 7 , 9 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE oddXorSubarray ( arr , N ) NEW_LINE DEDENT
Sum of Bitwise OR of every array element paired with all other array elements | 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 required sum ; Given array ; Size of array ; Function call
def printORSumforEachElement ( arr , N ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT req_sum = 0 NEW_LINE for j in range ( 0 , N ) : NEW_LINE INDENT req_sum += ( arr [ i ] arr [ j ] ) NEW_LINE DEDENT print ( req_sum , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE printORSumforEachElement ( arr , N ) NEW_LINE
Sum of Bitwise OR of each array element of an array with all elements of another array | 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 [ ] ; Given arr1 [ ] ; Given arr2 [ ] ; Size of arr1 [ ] ; Size of arr2 [ ] ; Function Call
def Bitwise_OR_sum_i ( arr1 , arr2 , M , N ) : NEW_LINE INDENT frequency = [ 0 ] * 32 NEW_LINE for i in range ( N ) : NEW_LINE INDENT bit_position = 0 NEW_LINE num = arr1 [ i ] NEW_LINE while ( num ) : NEW_LINE INDENT if ( num & 1 != 0 ) : NEW_LINE INDENT frequency [ bit_position ] += 1 NEW_LINE DEDENT bit_position += 1 NEW_LINE num >>= 1 NEW_LINE DEDENT DEDENT for i in range ( M ) : NEW_LINE INDENT num = arr2 [ i ] NEW_LINE value_at_that_bit = 1 NEW_LINE bitwise_OR_sum = 0 NEW_LINE for bit_position in range ( 32 ) : NEW_LINE INDENT if ( num & 1 != 0 ) : NEW_LINE INDENT bitwise_OR_sum += N * value_at_that_bit NEW_LINE DEDENT else : NEW_LINE INDENT bitwise_OR_sum += ( frequency [ bit_position ] * value_at_that_bit ) NEW_LINE DEDENT num >>= 1 NEW_LINE value_at_that_bit <<= 1 NEW_LINE DEDENT print ( bitwise_OR_sum , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT arr1 = [ 1 , 2 , 3 ] NEW_LINE arr2 = [ 1 , 2 , 3 ] NEW_LINE N = len ( arr1 ) NEW_LINE M = len ( arr2 ) NEW_LINE Bitwise_OR_sum_i ( arr1 , arr2 , M , N ) NEW_LINE
Count pairs from given array with Bitwise OR equal to K | 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
def countPairs ( arr , k , size ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( size - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , size ) : NEW_LINE INDENT x = arr [ i ] | arr [ j ] NEW_LINE if ( x == k ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT arr = [ 2 , 38 , 44 , 29 , 62 ] NEW_LINE K = 46 NEW_LINE N = len ( arr ) NEW_LINE countPairs ( arr , K , N ) NEW_LINE
Count nodes having Bitwise XOR of all edges in their path from the root equal to K | 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 prrequired count of nodes ; Add edges ; Print answer ; Driver Code ; Given K and R ; Given edges ; Number of vertices ; Function call
adj = [ [ ] for i in range ( 100005 ) ] NEW_LINE visited = [ 0 ] * 100005 NEW_LINE ans = 0 NEW_LINE def dfs ( node , xorr , k ) : NEW_LINE INDENT global ans NEW_LINE visited [ node ] = 1 NEW_LINE if ( node != 1 and xorr == k ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT for x in adj [ node ] : NEW_LINE INDENT if ( not visited [ x [ 0 ] ] ) : NEW_LINE INDENT xorr1 = xorr ^ x [ 1 ] NEW_LINE dfs ( x [ 0 ] , xorr1 , k ) NEW_LINE DEDENT DEDENT DEDENT def countNodes ( N , K , R , edges ) : NEW_LINE INDENT for i in range ( N - 1 ) : NEW_LINE INDENT u = edges [ i ] [ 0 ] NEW_LINE v = edges [ i ] [ 1 ] NEW_LINE w = edges [ i ] [ 2 ] NEW_LINE adj [ u ] . append ( [ v , w ] ) NEW_LINE adj [ v ] . append ( [ u , w ] ) NEW_LINE DEDENT dfs ( R , 0 , K ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 0 NEW_LINE R = 1 NEW_LINE edges = [ [ 1 , 2 , 3 ] , [ 1 , 3 , 1 ] , [ 2 , 4 , 3 ] , [ 2 , 5 , 4 ] , [ 3 , 6 , 1 ] , [ 3 , 7 , 2 ] ] NEW_LINE N = len ( edges ) NEW_LINE countNodes ( N , K , R , edges ) NEW_LINE DEDENT
Bitwise operations on Subarrays of size K | 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
def findMinXORSubarray ( arr , n , k ) : NEW_LINE INDENT if ( n < k ) : NEW_LINE INDENT return ; NEW_LINE DEDENT res_index = 0 ; NEW_LINE curr_xor = 0 ; NEW_LINE for i in range ( k ) : NEW_LINE INDENT curr_xor ^= arr [ i ] ; NEW_LINE DEDENT min_xor = curr_xor ; NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT curr_xor ^= ( arr [ i ] ^ arr [ i - k ] ) ; NEW_LINE if ( curr_xor < min_xor ) : NEW_LINE INDENT min_xor = curr_xor ; NEW_LINE res_index = ( i - k + 1 ) ; NEW_LINE DEDENT DEDENT print ( min_xor ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 7 , 90 , 20 , 10 , 50 , 40 ] ; NEW_LINE k = 3 ; NEW_LINE n = len ( arr ) ; NEW_LINE findMinXORSubarray ( arr , n , k ) ; NEW_LINE DEDENT
Maximum number of consecutive 1 s after flipping all 0 s in a K length subarray | 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
def findmax ( arr , n , k ) : NEW_LINE INDENT trav , i = 0 , 0 NEW_LINE c = 0 NEW_LINE maximum = 0 NEW_LINE while i < n - k + 1 : NEW_LINE INDENT trav = i - 1 NEW_LINE c = 0 NEW_LINE while trav >= 0 and arr [ trav ] == 1 : NEW_LINE INDENT trav -= 1 NEW_LINE c += 1 NEW_LINE DEDENT trav = i + k NEW_LINE while ( trav < n and arr [ trav ] == 1 ) : NEW_LINE INDENT trav += 1 NEW_LINE c += 1 NEW_LINE DEDENT c += k NEW_LINE if ( c > maximum ) : NEW_LINE INDENT maximum = c NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return maximum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 3 NEW_LINE arr = [ 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE ans = findmax ( arr , n , k ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Count of elements which cannot form any pair whose sum is power of 2 | Python3 program to count of array elements which do not form a pair with sum equal to a power of 2 with any other array element ; Function to calculate and return the count of elements ; Stores the frequencies of every array element ; Stores the count of removals ; For every element , check if it can form a sum equal to any power of 2 with any other element ; Store pow ( 2 , j ) - a [ i ] ; Check if s is present in the array ; If frequency of s exceeds 1 ; If s has frequency 1 but is different from a [ i ] ; Pair possible ; If no pair possible for the current element ; Return the answer ; Driver Code
from collections import defaultdict NEW_LINE def powerOfTwo ( a , n ) : NEW_LINE INDENT mp = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ a [ i ] ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT f = False NEW_LINE for j in range ( 31 ) : NEW_LINE INDENT s = ( 1 << j ) - a [ i ] NEW_LINE if ( s in mp and ( mp [ s ] > 1 or mp [ s ] == 1 and s != a [ i ] ) ) : NEW_LINE INDENT f = True NEW_LINE DEDENT DEDENT if ( f == False ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 6 , 2 , 11 ] NEW_LINE n = len ( a ) NEW_LINE print ( powerOfTwo ( a , n ) ) NEW_LINE DEDENT
Construct the Array using given bitwise AND , OR and XOR | Python3 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
import sys NEW_LINE def findArray ( n , a , b , c ) : NEW_LINE INDENT arr = [ 0 ] * ( n + 1 ) NEW_LINE for bit in range ( 30 , - 1 , - 1 ) : NEW_LINE INDENT set = a & ( 1 << bit ) NEW_LINE if ( set ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] |= set NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( b & ( 1 << bit ) ) : NEW_LINE INDENT arr [ 0 ] |= ( 1 << bit ) NEW_LINE if ( not ( c & ( 1 << bit ) ) ) : NEW_LINE INDENT arr [ 1 ] |= ( 1 << bit ) NEW_LINE DEDENT DEDENT DEDENT DEDENT aa = sys . maxsize NEW_LINE bb = 0 NEW_LINE cc = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT aa &= arr [ i ] NEW_LINE bb |= arr [ i ] NEW_LINE cc ^= arr [ i ] NEW_LINE DEDENT if ( a == aa and b == bb and c == cc ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE a = 4 NEW_LINE b = 6 NEW_LINE c = 6 NEW_LINE findArray ( n , a , b , c ) NEW_LINE DEDENT
Minimum XOR of OR and AND of any pair in the Array | Function to find the minimum value of XOR of AND and OR of any pair in the given array ; Sort the array ; Traverse the array arr [ ] ; Compare and Find the minimum XOR value of an array . ; Return the final answer ; Driver Code ; Given array ; Function Call
def maxAndXor ( arr , n ) : NEW_LINE INDENT ans = float ( ' inf ' ) NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT ans = min ( ans , arr [ i ] ^ arr [ i + 1 ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maxAndXor ( arr , N ) ) NEW_LINE DEDENT
Count of subarrays of size K with 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
def countSubarray ( arr , K , N ) : NEW_LINE INDENT if ( K % 2 != 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( N < K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT start = 0 NEW_LINE i = 0 NEW_LINE count = 0 NEW_LINE currXor = arr [ i ] NEW_LINE i += 1 NEW_LINE while ( i < K ) : NEW_LINE INDENT currXor ^= arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT if ( currXor == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT currXor ^= arr [ start ] NEW_LINE start += 1 NEW_LINE while ( i < N ) : NEW_LINE INDENT currXor ^= arr [ i ] NEW_LINE i += 1 NEW_LINE if ( currXor == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT currXor ^= arr [ start ] NEW_LINE start += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 4 , 2 , 2 , 4 ] NEW_LINE K = 4 NEW_LINE N = len ( arr ) NEW_LINE print ( countSubarray ( arr , K , N ) ) NEW_LINE DEDENT
Count of even and odd set bit Array elements after XOR with K for Q queries | Python3 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
even = 0 NEW_LINE odd = 0 NEW_LINE def keep_count ( arr , N ) : NEW_LINE INDENT global even NEW_LINE global odd NEW_LINE for i in range ( N ) : NEW_LINE INDENT count = 0 NEW_LINE while ( arr [ i ] != 0 ) : NEW_LINE INDENT arr [ i ] = ( arr [ i ] - 1 ) & arr [ i ] NEW_LINE count += 1 NEW_LINE DEDENT if ( count % 2 == 0 ) : NEW_LINE INDENT even += 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT def solveQueries ( arr , n , q , m ) : NEW_LINE INDENT global even NEW_LINE global odd NEW_LINE keep_count ( arr , n ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT X = q [ i ] NEW_LINE count = 0 NEW_LINE while ( X != 0 ) : NEW_LINE INDENT X = ( X - 1 ) & X NEW_LINE count += 1 NEW_LINE DEDENT if ( count % 2 == 0 ) : NEW_LINE INDENT print ( even , odd ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( odd , even ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 7 , 4 , 5 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE q = [ 3 , 4 , 12 , 6 ] NEW_LINE m = len ( q ) NEW_LINE solveQueries ( arr , n , q , m ) NEW_LINE DEDENT
Largest number in the Array having frequency same as value | Function to find the largest number whose frequency is equal to itself . ; Find the maximum element in the array ; Driver code
def findLargestNumber ( arr ) : NEW_LINE INDENT k = max ( arr ) ; NEW_LINE m = [ 0 ] * ( k + 1 ) ; NEW_LINE for n in arr : NEW_LINE INDENT m [ n ] += 1 ; NEW_LINE DEDENT for n in range ( len ( arr ) - 1 , 0 , - 1 ) : NEW_LINE INDENT if ( n == m [ n ] ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 5 , 2 , 4 , 5 ] ; NEW_LINE print ( findLargestNumber ( arr ) ) ; NEW_LINE DEDENT
Largest number in the Array having frequency same as value | 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
def findLargestNumber ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] &= 0xFFFF ; NEW_LINE if ( arr [ i ] <= n ) : NEW_LINE INDENT arr [ i ] += 0x10000 ; NEW_LINE DEDENT DEDENT for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT if ( ( arr [ i ] >> 16 ) == i ) : NEW_LINE INDENT return i + 1 ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 5 , 5 , 2 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findLargestNumber ( arr , n ) ) ; NEW_LINE DEDENT
Convert numbers into binary representation and add them without carry | Function returns sum of both the binary number without carry ; XOR of N and M ; Driver code
def NoCarrySum ( N , M ) : NEW_LINE INDENT return N ^ M NEW_LINE DEDENT N = 37 NEW_LINE M = 12 NEW_LINE print ( NoCarrySum ( N , M ) ) NEW_LINE
Check if all the set bits of the binary representation of N are at least K places away | Python3 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
def CheckBits ( N , K ) : NEW_LINE INDENT check = 0 NEW_LINE count = 0 NEW_LINE for i in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT if ( ( 1 << i ) & N ) : NEW_LINE INDENT if ( check == 0 ) : NEW_LINE INDENT check = 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( count < K ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT count = 0 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE K = 1 NEW_LINE if ( CheckBits ( N , K ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Minimize bits to be flipped in X and Y such that their Bitwise OR is equal to Z | 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
def minimumFlips ( X , Y , Z ) : NEW_LINE INDENT res = 0 NEW_LINE while ( X > 0 or Y > 0 or Z > 0 ) : NEW_LINE INDENT if ( ( ( X & 1 ) or ( Y & 1 ) ) and ( Z & 1 ) ) : NEW_LINE INDENT X = X >> 1 NEW_LINE Y = Y >> 1 NEW_LINE Z = Z >> 1 NEW_LINE continue NEW_LINE DEDENT elif ( not ( X & 1 ) and not ( Y & 1 ) and ( Z & 1 ) ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT elif ( ( X & 1 ) or ( Y & 1 ) == 1 ) : NEW_LINE INDENT if ( ( X & 1 ) and ( Y & 1 ) and not ( Z & 1 ) ) : NEW_LINE INDENT res += 2 NEW_LINE DEDENT elif ( ( ( X & 1 ) or ( Y & 1 ) ) and not ( Z & 1 ) ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT X = X >> 1 NEW_LINE Y = Y >> 1 NEW_LINE Z = Z >> 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 5 NEW_LINE Y = 8 NEW_LINE Z = 6 NEW_LINE print ( minimumFlips ( X , Y , Z ) ) NEW_LINE DEDENT
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
def countSubseq ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE mp = { } NEW_LINE for x in arr : NEW_LINE INDENT if x in mp . keys ( ) : NEW_LINE INDENT mp [ x ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ x ] = 1 NEW_LINE DEDENT DEDENT for i in mp . keys ( ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT count += pow ( 2 , mp [ i ] ) - 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += pow ( 2 , mp [ i ] - 1 ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 2 , 2 , 2 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countSubseq ( arr , n ) ) NEW_LINE
Choose an integer K such that maximum of the xor values of K with all Array elements is minimized | 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
def calculate ( section , pos ) : NEW_LINE INDENT if ( pos < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT on_section = [ ] NEW_LINE off_section = [ ] NEW_LINE for el in section : NEW_LINE INDENT if ( ( ( el >> pos ) & 1 ) == 0 ) : NEW_LINE INDENT off_section . append ( el ) NEW_LINE DEDENT else : NEW_LINE INDENT on_section . append ( el ) NEW_LINE DEDENT DEDENT if ( len ( off_section ) == 0 ) : NEW_LINE INDENT return calculate ( on_section , pos - 1 ) NEW_LINE DEDENT if ( len ( on_section ) == 0 ) : NEW_LINE INDENT return calculate ( off_section , pos - 1 ) NEW_LINE DEDENT return min ( calculate ( off_section , pos - 1 ) , calculate ( on_section , pos - 1 ) ) + ( 1 << pos ) NEW_LINE DEDENT def minXorValue ( a , n ) : NEW_LINE INDENT section = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT section . append ( a [ i ] ) ; NEW_LINE DEDENT return calculate ( section , 30 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE A = [ 3 , 2 , 5 , 6 ] NEW_LINE print ( minXorValue ( A , N ) ) NEW_LINE DEDENT
Program to find the Nth natural 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
def findNthNum ( N ) : NEW_LINE INDENT bit_L = 1 ; NEW_LINE last_num = 0 ; NEW_LINE while ( bit_L * ( bit_L + 1 ) / 2 < N ) : NEW_LINE INDENT last_num = last_num + bit_L ; NEW_LINE bit_L += 1 ; NEW_LINE DEDENT bit_R = N - last_num - 1 ; NEW_LINE print ( ( 1 << bit_L ) + ( 1 << bit_R ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 13 ; NEW_LINE findNthNum ( N ) ; NEW_LINE DEDENT
XOR of all Prime numbers in an Array at positions divisible by K | Python3 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
MAX = 1000005 NEW_LINE def SieveOfEratosthenes ( prime ) : NEW_LINE INDENT prime [ 1 ] = False ; NEW_LINE prime [ 0 ] = False ; NEW_LINE for p in range ( 2 , int ( MAX ** ( 1 / 2 ) ) ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , MAX , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def prime_xor ( arr , n , k ) : NEW_LINE INDENT prime = [ True ] * MAX ; NEW_LINE SieveOfEratosthenes ( prime ) ; NEW_LINE ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( prime [ arr [ i ] ] ) : NEW_LINE INDENT if ( ( i + 1 ) % k == 0 ) : NEW_LINE INDENT ans ^= arr [ i ] ; NEW_LINE DEDENT DEDENT DEDENT print ( ans ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 7 , 11 , 8 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE K = 2 ; NEW_LINE prime_xor ( arr , n , K ) ; NEW_LINE DEDENT
Find XOR of all elements in an 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
def xorOfArray ( arr , n ) : NEW_LINE INDENT xor_arr = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT xor_arr = xor_arr ^ arr [ i ] NEW_LINE DEDENT return xor_arr NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 9 , 12 , 13 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE print ( xorOfArray ( arr , n ) ) NEW_LINE DEDENT
Count of even set bits between XOR of two arrays | 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
def countEvenBit ( A , B , n , m ) : NEW_LINE INDENT i , j , cntOdd = 0 , 0 , 0 NEW_LINE cntEven = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = bin ( A [ i ] ) [ 2 : ] . count ( '1' ) NEW_LINE if ( x & 1 ) : NEW_LINE INDENT cntEven += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntOdd += 1 NEW_LINE DEDENT DEDENT CountB = [ 0 ] * m NEW_LINE for i in range ( m ) : NEW_LINE INDENT x = bin ( B [ i ] ) [ 2 : ] . count ( '1' ) NEW_LINE if ( x & 1 ) : NEW_LINE INDENT CountB [ i ] = cntEven NEW_LINE DEDENT else : NEW_LINE INDENT CountB [ i ] = cntOdd NEW_LINE DEDENT DEDENT for i in range ( m ) : NEW_LINE INDENT print ( CountB [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 4 , 2 , 15 , 9 , 8 , 8 ] NEW_LINE B = [ 3 , 4 , 22 ] NEW_LINE countEvenBit ( A , B , 6 , 3 ) NEW_LINE DEDENT
Check if a Number is Odd or Even using Bitwise Operators | Returns true if n is even , else odd ; n ^ 1 is n + 1 , then even , else odd ; Driver code
def isEven ( n ) : NEW_LINE INDENT if ( n ^ 1 == n + 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 100 ; NEW_LINE print ( " Even " ) if isEven ( n ) else print ( " Odd " ) ; NEW_LINE DEDENT
Bitwise OR ( | ) of all even number from 1 to N | Function to return the bitwise OR of all the even numbers upto N ; Initialize result as 2 ; Driver code
def bitwiseOrTillN ( n ) : NEW_LINE INDENT result = 2 ; NEW_LINE for i in range ( 4 , n + 1 , 2 ) : NEW_LINE INDENT result = result | i NEW_LINE DEDENT return result NEW_LINE DEDENT n = 10 ; NEW_LINE print ( bitwiseOrTillN ( n ) ) ; NEW_LINE
Bitwise OR ( | ) of all even number from 1 to N | Python3 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
from math import log2 NEW_LINE def bitwiseOrTillN ( n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT bitCount = int ( log2 ( n ) ) + 1 ; NEW_LINE return pow ( 2 , bitCount ) - 2 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 ; NEW_LINE print ( bitwiseOrTillN ( n ) ) ; NEW_LINE DEDENT
Generating N | Function to Generating N - bit Gray Code starting from K ; Generate gray code of corresponding binary number of integer i . ; Driver code
def genSequence ( n , val ) : NEW_LINE INDENT for i in range ( 1 << n ) : NEW_LINE INDENT x = i ^ ( i >> 1 ) ^ val ; NEW_LINE print ( x , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 ; k = 2 ; NEW_LINE genSequence ( n , k ) ; NEW_LINE DEDENT
Winner in the Rock | 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
def winner ( moves ) : NEW_LINE INDENT data = dict ( ) NEW_LINE data [ ' R ' ] = 0 NEW_LINE data [ ' P ' ] = 1 NEW_LINE data [ ' S ' ] = 2 NEW_LINE if ( moves [ 0 ] == moves [ 1 ] ) : NEW_LINE INDENT return " Draw " NEW_LINE DEDENT if ( ( ( data [ moves [ 0 ] ] | 1 << ( 2 ) ) - ( data [ moves [ 1 ] ] | 0 << ( 2 ) ) ) % 3 ) : NEW_LINE INDENT return " A " NEW_LINE DEDENT return " B " NEW_LINE DEDENT def performQueries ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( winner ( arr [ i ] ) ) NEW_LINE DEDENT DEDENT arr = [ " RS " , " SR " , " SP " , " PP " ] NEW_LINE n = len ( arr ) NEW_LINE performQueries ( arr , n ) NEW_LINE
Find the minimum spanning tree with alternating colored edges | Python implementation of the approach ; Initializing dp of size = ( 2 ^ 18 ) * 18 * 2. ; Recursive Function to calculate Minimum Cost with alternate colour edges ; Base case ; If already calculated ; Masking previous edges as explained in above formula . ; Function to Adjacency List Representation of a Graph ; Function to getCost for the Minimum Spanning Tree Formed ; Assigning maximum possible value . ; Driver Code
graph = [ [ [ 0 , 0 ] for i in range ( 18 ) ] for j in range ( 18 ) ] NEW_LINE dp = [ [ [ 0 , 0 ] for i in range ( 18 ) ] for j in range ( 1 << 15 ) ] NEW_LINE def minCost ( n : int , m : int , mask : int , prev : int , col : int ) -> int : NEW_LINE INDENT global dp NEW_LINE if mask == ( ( 1 << n ) - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if dp [ mask ] [ prev ] [ col == 1 ] != 0 : NEW_LINE INDENT return dp [ mask ] [ prev ] [ col == 1 ] NEW_LINE DEDENT ans = int ( 1e9 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT if graph [ prev ] [ i ] [ j ] and not ( mask & ( 1 << i ) ) and ( j != col ) : NEW_LINE INDENT z = graph [ prev ] [ i ] [ j ] + minCost ( n , m , mask | ( 1 << i ) , i , j ) NEW_LINE ans = min ( z , ans ) NEW_LINE DEDENT DEDENT DEDENT dp [ mask ] [ prev ] [ col == 1 ] = ans NEW_LINE return dp [ mask ] [ prev ] [ col == 1 ] NEW_LINE DEDENT def makeGraph ( vp : list , m : int ) : NEW_LINE INDENT global graph NEW_LINE for i in range ( m ) : NEW_LINE INDENT a = vp [ i ] [ 0 ] [ 0 ] - 1 NEW_LINE b = vp [ i ] [ 0 ] [ 1 ] - 1 NEW_LINE cost = vp [ i ] [ 1 ] [ 0 ] NEW_LINE color = vp [ i ] [ 1 ] [ 1 ] NEW_LINE graph [ a ] [ b ] [ color == ' W ' ] = cost NEW_LINE graph [ b ] [ a ] [ color == ' W ' ] = cost NEW_LINE DEDENT DEDENT def getCost ( n : int , m : int ) -> int : NEW_LINE INDENT ans = int ( 1e9 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = min ( ans , minCost ( n , m , 1 << i , i , 2 ) ) NEW_LINE DEDENT if ans != int ( 1e9 ) : NEW_LINE INDENT return ans NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE m = 4 NEW_LINE vp = [ [ [ 1 , 2 ] , [ 2 , ' B ' ] ] , [ [ 1 , 2 ] , [ 3 , ' W ' ] ] , [ [ 2 , 3 ] , [ 4 , ' W ' ] ] , [ [ 2 , 3 ] , [ 5 , ' B ' ] ] ] NEW_LINE makeGraph ( vp , m ) NEW_LINE print ( getCost ( n , m ) ) NEW_LINE DEDENT
Maximum number of consecutive 1 's in binary representation of all the array elements | 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
def maxConsecutiveOnes ( x ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( x != 0 ) : NEW_LINE INDENT x = ( x & ( x << 1 ) ) ; NEW_LINE count += 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def maxOnes ( arr , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT currMax = maxConsecutiveOnes ( arr [ i ] ) ; NEW_LINE ans = max ( ans , currMax ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxOnes ( arr , n ) ) ; NEW_LINE DEDENT
Maximum Bitwise OR pair from a range | 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
def maxOR ( L , R ) : NEW_LINE INDENT maximum = - 10 ** 9 NEW_LINE for i in range ( L , R ) : NEW_LINE INDENT for j in range ( i + 1 , R + 1 ) : NEW_LINE INDENT maximum = max ( maximum , ( i j ) ) NEW_LINE DEDENT DEDENT return maximum NEW_LINE DEDENT L = 4 NEW_LINE R = 5 NEW_LINE print ( maxOR ( L , R ) ) NEW_LINE
Maximum Bitwise OR pair from a range | Python3 implementation of the approach ; Function to return the maximum bitwise OR possible among all the possible pairs ; If there is only a single value in the range [ L , R ] ; Loop through each bit from MSB to LSB ; MSBs where the bits differ , all bits from that bit are set ; If MSBs are same , then ans bit is same as that of bit of right or left limit ; Driver code
MAX = 64 ; NEW_LINE def maxOR ( L , R ) : NEW_LINE INDENT if ( L == R ) : NEW_LINE INDENT return L ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for i in range ( MAX - 1 , - 1 , - 1 ) : NEW_LINE INDENT p = 1 << i ; NEW_LINE if ( ( rbit == 1 ) and ( lbit == 0 ) ) : NEW_LINE INDENT ans += ( p << 1 ) - 1 ; NEW_LINE break ; NEW_LINE DEDENT if ( rbit == 1 ) : NEW_LINE INDENT ans += p ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 4 ; R = 5 ; NEW_LINE print ( maxOR ( L , R ) ) ; NEW_LINE DEDENT
Longest subsequence with a given AND value | O ( N ) | 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
def findLen ( arr , n , m ) : NEW_LINE INDENT filter = [ ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( arr [ i ] & m ) == m ) : NEW_LINE INDENT filter . append ( arr [ i ] ) ; NEW_LINE DEDENT DEDENT if ( len ( filter ) == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT c_and = filter [ 0 ] ; NEW_LINE for i in range ( 1 , len ( filter ) ) : NEW_LINE INDENT c_and &= filter [ i ] ; NEW_LINE DEDENT if ( c_and == m ) : NEW_LINE INDENT return len ( filter ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 3 , 3 , 1 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE m = 3 ; NEW_LINE print ( findLen ( arr , n , m ) ) ; NEW_LINE DEDENT
Longest sub | 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
def findLen ( arr , n , m ) : NEW_LINE INDENT filter = [ ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( arr [ i ] m ) == m ) : NEW_LINE INDENT filter . append ( arr [ i ] ) ; NEW_LINE DEDENT DEDENT if ( len ( filter ) == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT c_or = filter [ 0 ] ; NEW_LINE for i in range ( 1 , len ( filter ) ) : NEW_LINE INDENT c_or |= filter [ i ] ; NEW_LINE DEDENT if ( c_or == m ) : NEW_LINE INDENT return len ( filter ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 3 , 3 , 1 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE m = 3 ; NEW_LINE print ( findLen ( arr , n , m ) ) ; NEW_LINE DEDENT
Program to toggle K | Function to toggle the kth bit of n ; Driver code
def toggleBit ( n , k ) : NEW_LINE INDENT return ( n ^ ( 1 << ( k - 1 ) ) ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; k = 2 ; NEW_LINE print ( toggleBit ( n , k ) ) ; NEW_LINE DEDENT
Program to clear K | Function to clear the kth bit of n ; Driver code
def clearBit ( n , k ) : NEW_LINE INDENT return ( n & ( ~ ( 1 << ( k - 1 ) ) ) ) NEW_LINE DEDENT n = 5 NEW_LINE k = 1 NEW_LINE print ( clearBit ( n , k ) ) NEW_LINE
Maximize the Expression | Bit Manipulation | Python3 implementation of the approach ; Function to return the value of the maximized expression ; int can have 32 bits ; Consider the ith bit of D to be 1 ; Calculate the value of ( B AND bitOfD ) ; Check if bitOfD satisfies ( B AND D = D ) ; Check if bitOfD can maximize ( A XOR D ) ; Note that we do not need to consider ith bit of D to be 0 because if above condition are not satisfied then value of result will not change which is similar to considering bitOfD = 0 as result XOR 0 = result ; Driver code
MAX = 32 NEW_LINE def maximizeExpression ( a , b ) : NEW_LINE INDENT result = a NEW_LINE for bit in range ( MAX - 1 , - 1 , - 1 ) : NEW_LINE INDENT bitOfD = 1 << bit NEW_LINE x = b & bitOfD NEW_LINE if ( x == bitOfD ) : NEW_LINE INDENT y = result & bitOfD NEW_LINE if ( y == 0 ) : NEW_LINE INDENT result = result ^ bitOfD NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT a = 11 NEW_LINE b = 14 NEW_LINE print ( maximizeExpression ( a , b ) ) NEW_LINE
Find number of subarrays with XOR value a power of 2 | Python3 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
MAX = 10 NEW_LINE def findSubarray ( array , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE mp [ 0 ] = 1 NEW_LINE answer = 0 NEW_LINE preXor = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT value = 1 NEW_LINE preXor ^= array [ i ] NEW_LINE for j in range ( 1 , MAX + 1 ) : NEW_LINE INDENT Y = value ^ preXor NEW_LINE if ( Y in mp . keys ( ) ) : NEW_LINE INDENT answer += mp [ Y ] NEW_LINE DEDENT value *= 2 NEW_LINE DEDENT if ( preXor in mp . keys ( ) ) : NEW_LINE INDENT mp [ preXor ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ preXor ] = 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT array = [ 2 , 6 , 7 , 5 , 8 ] NEW_LINE n = len ( array ) NEW_LINE print ( findSubarray ( array , n ) ) NEW_LINE
Maximum XOR of Two Numbers in an Array | Function to return the maximum xor ; Calculating xor of each pair ; Driver Code
def max_xor ( arr , n ) : NEW_LINE INDENT maxXor = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT maxXor = max ( maxXor , \ arr [ i ] ^ arr [ j ] ) ; NEW_LINE DEDENT DEDENT return maxXor ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 25 , 10 , 2 , 8 , 5 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( max_xor ( arr , n ) ) ; NEW_LINE DEDENT
Maximum XOR of Two Numbers in an Array | 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
def max_xor ( arr , n ) : NEW_LINE INDENT maxx = 0 NEW_LINE mask = 0 ; NEW_LINE se = set ( ) NEW_LINE for i in range ( 30 , - 1 , - 1 ) : NEW_LINE INDENT mask |= ( 1 << i ) NEW_LINE newMaxx = maxx | ( 1 << i ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT se . add ( arr [ i ] & mask ) NEW_LINE DEDENT for prefix in se : NEW_LINE INDENT if ( newMaxx ^ prefix ) in se : NEW_LINE INDENT maxx = newMaxx NEW_LINE break NEW_LINE DEDENT DEDENT se . clear ( ) NEW_LINE DEDENT return maxx NEW_LINE DEDENT arr = [ 25 , 10 , 2 , 8 , 5 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( max_xor ( arr , n ) ) NEW_LINE
Count of triplets that satisfy the given equation | 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
def CountTriplets ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT first = arr [ i ] NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT first ^= arr [ j ] NEW_LINE if ( first == 0 ) : NEW_LINE INDENT ans += ( j - i ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 5 , 6 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( CountTriplets ( arr , n ) ) NEW_LINE
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
def findMajority ( arr , n ) : NEW_LINE INDENT Len = 32 NEW_LINE number = 0 NEW_LINE for i in range ( Len ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ j ] & ( 1 << i ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count > ( n // 2 ) ) : NEW_LINE INDENT number += ( 1 << i ) NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == number ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count > ( n // 2 ) ) : NEW_LINE INDENT print ( number ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Majority ▁ Element ▁ Not ▁ Present " ) NEW_LINE DEDENT DEDENT arr = [ 3 , 3 , 4 , 2 , 4 , 4 , 2 , 4 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE findMajority ( arr , n ) NEW_LINE
Count number of bits to be flipped to convert A to B | Set | 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
def countBits ( a , b ) : NEW_LINE INDENT count = 0 NEW_LINE while ( a or b ) : NEW_LINE INDENT last_bit_a = a & 1 NEW_LINE last_bit_b = b & 1 NEW_LINE if ( last_bit_a != last_bit_b ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT a = a >> 1 NEW_LINE b = b >> 1 NEW_LINE DEDENT return count NEW_LINE DEDENT a = 10 NEW_LINE b = 7 NEW_LINE print ( countBits ( a , b ) ) NEW_LINE