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_... |
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 ... | 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... |
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 ... | 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 ) % ... |
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 DEDE... |
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 p... |
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 ' ) ... |
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_L... |
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 nat... | 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... |
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 ... | ' 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... |
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 +... |
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... | 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... |
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... | 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 ) ... |
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 = 922337203... |
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 e... | 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 wh... |
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... | 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... |
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 ... | 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 DE... |
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 ... | 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 ... |
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 righ... | ' 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 Fals... |
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 " , coun... |
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 n... | 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_... |
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... | 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 ] [ nex... |
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 numbe... | 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 ... |
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 ... | 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 ... |
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 , t... | 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 ra... |
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 charact... | 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... |
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 final... | 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 ) ) ... |
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 fi... | 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 f... |
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 D... |
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... | 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 NE... |
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 β... |
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... | ' 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 I... |
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 ... |
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 resul... |
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 ... | 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 -... |
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... |
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 ... | 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... |
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... | 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 ( e... |
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 DE... |
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_LIN... |
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 , th... | 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 " , "... |
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 ... |
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 ; Func... | 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... |
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__ == " _ _ mai... |
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 ] ; S... | 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... |
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 ... | 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 , ... |
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... |
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... | 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... |
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 el... | 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... |
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 ) ; Upda... | 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 << ( ... |
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 h... | 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_LIN... |
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... | 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 +=... |
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 arr... | 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 )... |
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 n... | 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 += ... |
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 , 3... |
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 ... | 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 v... |
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 β ... | 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_x... |
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... | 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 ... |
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 cou... | 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 = ( ... |
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 ... | 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 ... |
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 ... |
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 subarr... | 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 ... |
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 c... | 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 ... |
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 ; NE... |
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 ... |
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 th... | 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... |
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 e... | 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 ... |
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 elemen... | 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 coun... |
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 sectio... | 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_s... |
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__ ==... |
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 ... | 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... |
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 ( ar... |
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 ... | 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 ... |
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 ... | 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 ( ... |
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 ) ) ) %... |
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 . ;... | 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 IND... |
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 ; Functio... | 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 = maxConsecutiv... |
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 ;... | 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_LIN... |
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 ... |
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 i... |
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 (... | 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 ^ bitOf... |
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... | 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... |
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 , ... |
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 o... | 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... |
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 ... |
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 bi... | 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 += ... |
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 integ... | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.