text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Highest power of 2 that divides a number represented in binary | Function to return the highest power of 2 which divides the given binary number ; To store the highest required power of 2 ; Counting number of consecutive zeros from the end in the given binary string ; Driver code | def highestPower ( str , length ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( length - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT str = "100100" ; NEW_LINE length = len ( str ) ; NEW_LINE print ( highestPower ( str , length ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Number of ways to arrange K different objects taking N objects at a time | Python3 implementation of the approach ; Function to return n ! % p ; res = 1 Initialize result ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; Returns n ^ ( - 1 ) mod p ; Returns nCr % p using Fermat 's little theorem. ; Base case ; Fifactorial array so that we can find afactorial of r , n and n - r ; Function to return the number of ways to arrange K different objects taking N objects at a time ; Drivers Code ; Function call | mod = 10 ** 9 + 7 NEW_LINE def factorial ( n , p ) : NEW_LINE INDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = ( res * i ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def power ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def modInverse ( n , p ) : NEW_LINE INDENT return power ( n , p - 2 , p ) NEW_LINE DEDENT def nCrModP ( n , r , p ) : NEW_LINE INDENT if ( r == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT fac = [ 0 for i in range ( n + 1 ) ] NEW_LINE fac [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fac [ i ] = fac [ i - 1 ] * i % p NEW_LINE DEDENT return ( fac [ n ] * modInverse ( fac [ r ] , p ) % p * modInverse ( fac [ n - r ] , p ) % p ) % p NEW_LINE DEDENT def countArrangements ( n , k , p ) : NEW_LINE INDENT return ( factorial ( n , p ) * nCrModP ( k , n , p ) ) % p NEW_LINE DEDENT N = 5 NEW_LINE K = 8 NEW_LINE print ( countArrangements ( N , K , mod ) ) NEW_LINE |
Find maximum product of digits among numbers less than or equal to N | Function that returns the maximum product of digits among numbers less than or equal to N ; Driver code | def maxProd ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( N < 10 ) : NEW_LINE INDENT return N NEW_LINE DEDENT return max ( maxProd ( N // 10 ) * ( N % 10 ) , maxProd ( N // 10 - 1 ) * 9 ) NEW_LINE DEDENT N = 390 NEW_LINE print ( maxProd ( N ) ) NEW_LINE |
Check if a number from every row can be selected such that xor of the numbers is greater than zero | Python3 program to implement the above approach ; Function to check if a number from every row can be selected such that xor of the numbers is greater than zero ; Find the xor of first column for every row ; If Xorr is 0 ; Traverse in the matrix ; Check is atleast 2 distinct elements ; Driver code | N = 2 NEW_LINE M = 3 NEW_LINE def check ( mat ) : NEW_LINE INDENT xorr = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT xorr ^= mat [ i ] [ 0 ] NEW_LINE DEDENT if ( xorr != 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( 1 , M ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != mat [ i ] [ 0 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT mat = [ [ 7 , 7 , 7 ] , [ 10 , 10 , 7 ] ] NEW_LINE if ( check ( mat ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Sum of the series 1 , 2 , 4 , 3 , 5 , 7 , 9 , 6 , 8 , 10 , 11 , 13. . till N | Function to find the sum of first N odd numbers ; Function to find the sum of first N even numbers ; Function to overall find the sum of series ; Initial odd numbers ; Initial even numbers ; First power of 2 ; Check for parity for odd / even ; Counts the sum ; Get the minimum out of remaining num or power of 2 ; Decrease that much numbers from num ; If the segment has odd numbers ; Summate the odd numbers By exclusion ; Increase number of odd numbers ; If the segment has even numbers ; Summate the even numbers By exclusion ; Increase number of even numbers ; Next set of numbers ; Change parity for odd / even ; Driver code | def sumodd ( n ) : NEW_LINE INDENT return ( n * n ) NEW_LINE DEDENT def sumeven ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) ) NEW_LINE DEDENT def findSum ( num ) : NEW_LINE INDENT sumo = 0 NEW_LINE sume = 0 NEW_LINE x = 1 NEW_LINE cur = 0 NEW_LINE ans = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT inc = min ( x , num ) NEW_LINE num -= inc NEW_LINE if ( cur == 0 ) : NEW_LINE INDENT ans = ans + sumodd ( sumo + inc ) - sumodd ( sumo ) NEW_LINE sumo += inc NEW_LINE DEDENT else : NEW_LINE INDENT ans = ans + sumeven ( sume + inc ) - sumeven ( sume ) NEW_LINE sume += inc NEW_LINE DEDENT x *= 2 NEW_LINE cur ^= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 4 NEW_LINE print ( findSum ( n ) ) NEW_LINE |
Find the nth term of the given series | Function to return the nth term of the given series ; Driver code | def oddTriangularNumber ( N ) : NEW_LINE INDENT return ( N * ( ( 2 * N ) - 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE print ( oddTriangularNumber ( N ) ) NEW_LINE DEDENT |
Check if given two straight lines are identical or not | Function to check if they are identical ; Driver Code | def idstrt ( a1 , b1 , c1 , a2 , b2 , c2 ) : NEW_LINE INDENT if ( ( a1 // a2 == b1 // b2 ) and ( a1 // a2 == c1 // c2 ) and ( b1 // b2 == c1 // c2 ) ) : NEW_LINE INDENT print ( " The β given β straight β lines " , " are β identical " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The β given β straight β lines " , " are β not β identical " ) ; NEW_LINE DEDENT DEDENT a1 , b1 = - 2 , 4 NEW_LINE c1 , a2 = 3 , - 6 NEW_LINE b2 , c2 = 12 , 9 NEW_LINE idstrt ( a1 , b1 , c1 , a2 , b2 , c2 ) NEW_LINE |
Count arrays of length K whose product of elements is same as that of given array | Python 3 implementation of the approach ; To store the smallest prime factor for every number ; Initialize map to store count of prime factors ; Function to calculate SPF ( Smallest Prime Factor ) for every number till MAXN ; Marking smallest prime factor for every number to be itself ; Separately marking spf for every even number as 2 ; Checking if i is prime ; Marking SPF for all numbers divisible by i ; Marking spf [ j ] if it is not previously marked ; Function to factorize using spf and store in cnt ; Function to return n ! % p ; Initialize result ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is >= p ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Function that returns n ^ ( - 1 ) mod p ; Function that returns nCr % p using Fermat 's little theorem ; Base case ; Fill factorial array so that we can find all factorial of r , n and n - r ; Function to return the count the number of possible arrays mod P of length K such that the product of all elements of that array is equal to the product of all elements of the given array of length N ; Initialize result ; Call sieve to get spf ; Factorize arr [ i ] , count and store its factors in cnt ; Driver code | from math import sqrt NEW_LINE MAXN = 100001 NEW_LINE mod = 1000000007 NEW_LINE spf = [ 0 for i in range ( MAXN ) ] NEW_LINE cnt = { i : 0 for i in range ( 10 ) } NEW_LINE def sieve ( ) : NEW_LINE INDENT spf [ 1 ] = 1 NEW_LINE for i in range ( 2 , MAXN ) : NEW_LINE INDENT spf [ i ] = i NEW_LINE DEDENT for i in range ( 4 , MAXN , 2 ) : NEW_LINE INDENT spf [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , int ( sqrt ( MAXN ) ) + 1 , 1 ) : NEW_LINE INDENT if ( spf [ i ] == i ) : NEW_LINE INDENT for j in range ( i * i , MAXN , i ) : NEW_LINE INDENT if ( spf [ j ] == j ) : NEW_LINE INDENT spf [ j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def factorize ( f ) : NEW_LINE INDENT while ( f > 1 ) : NEW_LINE INDENT x = spf [ f ] NEW_LINE while ( f % x == 0 ) : NEW_LINE INDENT cnt [ x ] += 1 NEW_LINE f = int ( f / x ) NEW_LINE DEDENT DEDENT DEDENT def factorial ( n , p ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT res = ( res * i ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def modInverse ( n , p ) : NEW_LINE INDENT return power ( n , p - 2 , p ) NEW_LINE DEDENT def nCrModP ( n , r , p ) : NEW_LINE INDENT if ( r == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT fac = [ 0 for i in range ( n + 1 ) ] NEW_LINE fac [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT fac [ i ] = fac [ i - 1 ] * i % p NEW_LINE DEDENT return ( fac [ n ] * modInverse ( fac [ r ] , p ) % p * modInverse ( fac [ n - r ] , p ) % p ) % p NEW_LINE DEDENT def countArrays ( arr , N , K , P ) : NEW_LINE INDENT res = 1 NEW_LINE sieve ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT factorize ( arr [ i ] ) NEW_LINE DEDENT for key , value in cnt . items ( ) : NEW_LINE INDENT ci = value NEW_LINE res = ( res * nCrModP ( ci + K - 1 , K - 1 , P ) ) % P NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 5 , 2 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( countArrays ( arr , N , K , mod ) ) NEW_LINE DEDENT |
Count different numbers possible using all the digits their frequency times | Python3 implementation of the above approach ; Initialize an array to store factorial values ; Function to calculate and store X ! values ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function that return modular inverse of x under modulo p ; Function that returns the count of different number possible by using all the digits its frequency times ; Preprocess factorial values ; Initialize the result and sum of aint the frequencies ; Calculate the sum of frequencies ; Putting res equal to x ! ; Multiplying res with modular inverse of X0 ! , X1 ! , . . , X9 ! ; Driver Code | MAXN = 100000 NEW_LINE MOD = 1000000007 NEW_LINE fact = [ 0 ] * MAXN ; NEW_LINE def factorial ( ) : NEW_LINE INDENT fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , MAXN ) : NEW_LINE INDENT fact [ i ] = ( fact [ i - 1 ] * i ) % MOD NEW_LINE DEDENT DEDENT def power ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def modInverse ( x , p ) : NEW_LINE INDENT return power ( x , p - 2 , p ) NEW_LINE DEDENT def countDifferentNumbers ( arr , P ) : NEW_LINE INDENT factorial ( ) ; NEW_LINE res = 0 ; X = 0 ; NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT X += arr [ i ] NEW_LINE DEDENT res = fact [ X ] NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT if ( arr [ i ] > 1 ) : NEW_LINE INDENT res = ( res * modInverse ( fact [ arr [ i ] ] , P ) ) % P ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 0 , 2 , 0 , 0 , 7 , 4 , 0 , 0 , 3 ] NEW_LINE print ( countDifferentNumbers ( arr , MOD ) ) NEW_LINE DEDENT |
Equation of straight line passing through a given point which bisects it into two equal line segments | Function to print the equation of the required line ; Driver code | def line ( x0 , y0 ) : NEW_LINE INDENT c = 2 * y0 * x0 NEW_LINE print ( y0 , " x " , " + " , x0 , " y = " , c ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x0 = 4 NEW_LINE y0 = 3 NEW_LINE line ( x0 , y0 ) NEW_LINE DEDENT |
Find the original matrix when largest element in a row and a column are given | Python3 implementation of the approach ; Function that prints the original matrix ; Iterate in the row ; Iterate in the column ; If previously existed an element ; Driver code | N = 3 NEW_LINE M = 7 NEW_LINE def printOriginalMatrix ( a , b , mat ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT print ( min ( a [ i ] , b [ j ] ) , end = " β " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 , end = " β " ) ; NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 1 , 3 ] NEW_LINE b = [ 2 , 3 , 0 , 0 , 2 , 0 , 1 ] NEW_LINE mat = [ [ 1 , 0 , 0 , 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 1 , 0 , 0 , 0 , 0 , 0 ] ] ; NEW_LINE printOriginalMatrix ( a , b , mat ) ; NEW_LINE DEDENT |
Calculate the loss incurred in selling the given items at discounted price | Function to return the x % of n ; Function to return the total loss ; To store the total loss ; Original price of the item ; The price at which the item will be sold ; The discounted price of the item ; Loss incurred ; Driver code ; Total items | def percent ( n , x ) : NEW_LINE INDENT p = ( int ) ( n ) * x ; NEW_LINE p /= 100 ; NEW_LINE return p ; NEW_LINE DEDENT def getLoss ( price , quantity , X , n ) : NEW_LINE INDENT loss = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT originalPrice = price [ i ] ; NEW_LINE sellingPrice = originalPrice + percent ( originalPrice , X [ i ] ) ; NEW_LINE afterDiscount = sellingPrice - percent ( sellingPrice , X [ i ] ) ; NEW_LINE loss += ( ( originalPrice - afterDiscount ) * quantity [ i ] ) ; NEW_LINE DEDENT return round ( loss , 2 ) ; NEW_LINE DEDENT price = [ 20 , 48 , 200 , 100 ] ; NEW_LINE quantity = [ 20 , 48 , 1 , 1 ] ; NEW_LINE X = [ 0 , 48 , 200 , 5 ] ; NEW_LINE n = len ( X ) ; NEW_LINE print ( getLoss ( price , quantity , X , n ) ) ; NEW_LINE |
Maximum difference between two elements in an Array | Function to return the maximum absolute difference between any two elements of the array ; To store the minimum and the maximum elements from the array ; Driver code | def maxAbsDiff ( arr , n ) : NEW_LINE INDENT minEle = arr [ 0 ] NEW_LINE maxEle = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT minEle = min ( minEle , arr [ i ] ) NEW_LINE maxEle = max ( maxEle , arr [ i ] ) NEW_LINE DEDENT return ( maxEle - minEle ) NEW_LINE DEDENT arr = [ 2 , 1 , 5 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxAbsDiff ( arr , n ) ) NEW_LINE |
Maximize the maximum subarray sum after removing atmost one element | Python3 implementation of the approach ; Function to return the maximum sub - array sum ; Initialized ; Traverse in the array ; Increase the sum ; If sub - array sum is more than the previous ; If sum is negative ; Function that returns the maximum sub - array sum after removing an element from the same sub - array ; Maximum sub - array sum using Kadane 's Algorithm ; Re - apply Kadane 's with minor changes ; Increase the sum ; If sub - array sum is greater than the previous ; If elements are 0 , no removal ; If elements are more , then store the minimum value in the sub - array obtained till now ; If sum is negative ; Re - initialize everything ; Driver code | import sys ; NEW_LINE def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - ( sys . maxsize - 1 ) ; NEW_LINE max_ending_here = 0 ; NEW_LINE for i in range ( size ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] ; NEW_LINE if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_here ; NEW_LINE DEDENT if ( max_ending_here < 0 ) : NEW_LINE INDENT max_ending_here = 0 ; NEW_LINE DEDENT DEDENT return max_so_far ; NEW_LINE DEDENT def maximizeSum ( a , n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE mini = sys . maxsize ; NEW_LINE minSubarray = sys . maxsize ; NEW_LINE sum = maxSubArraySum ( a , n ) ; NEW_LINE max_so_far = - ( sys . maxsize - 1 ) ; NEW_LINE max_ending_here = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] ; NEW_LINE cnt += 1 ; NEW_LINE minSubarray = min ( a [ i ] , minSubarray ) ; NEW_LINE if ( sum == max_ending_here ) : NEW_LINE INDENT if ( cnt == 1 ) : NEW_LINE INDENT mini = min ( mini , 0 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT mini = min ( mini , minSubarray ) ; NEW_LINE DEDENT DEDENT if ( max_ending_here < 0 ) : NEW_LINE INDENT max_ending_here = 0 ; NEW_LINE cnt = 0 ; NEW_LINE minSubarray = sys . maxsize ; NEW_LINE DEDENT DEDENT return sum - mini ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 3 , - 2 , 3 ] ; NEW_LINE n = len ( a ) NEW_LINE print ( maximizeSum ( a , n ) ) ; NEW_LINE DEDENT |
3 | Function that returns true if n is an Osiris number ; 3 rd digit ; 2 nd digit ; 1 st digit ; Check the required condition ; Driver code | def isOsiris ( n ) : NEW_LINE INDENT a = n % 10 NEW_LINE b = ( n // 10 ) % 10 NEW_LINE c = n // 100 NEW_LINE digit_sum = a + b + c NEW_LINE if ( n == ( 2 * ( digit_sum ) * 11 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 132 NEW_LINE if isOsiris ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Dudeney Numbers | Function that returns true if n is a Dudeney number ; If n is not a perfect cube ; Last digit ; Update the digit sum ; Remove the last digit ; If cube root of n is not equal to the sum of its digits ; Driver code | def isDudeney ( n ) : NEW_LINE INDENT cube_rt = int ( round ( ( pow ( n , 1.0 / 3.0 ) ) ) ) NEW_LINE if cube_rt * cube_rt * cube_rt != n : NEW_LINE INDENT return False NEW_LINE DEDENT dig_sum = 0 NEW_LINE temp = n NEW_LINE while temp > 0 : NEW_LINE INDENT rem = temp % 10 NEW_LINE dig_sum += rem NEW_LINE temp //= 10 NEW_LINE DEDENT if cube_rt != dig_sum : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 17576 NEW_LINE if isDudeney ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Number of triangles possible with given lengths of sticks which are powers of 2 | Function to return the number of positive area triangles ; To store the count of total triangles ; To store the count of pairs of sticks with equal lengths ; Back - traverse and count the number of triangles ; Count the number of pairs ; If we have one remaining stick and we have a pair ; Count 1 triangle ; Reduce one pair ; Count the remaining triangles that can be formed ; Driver code | def countTriangles ( a , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE pairs = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT pairs += a [ i ] // 2 NEW_LINE if ( a [ i ] % 2 == 1 and pairs > 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE pairs -= 1 NEW_LINE DEDENT DEDENT cnt += ( 2 * pairs ) // 3 NEW_LINE return cnt NEW_LINE DEDENT a = [ 1 , 2 , 2 , 2 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( countTriangles ( a , n ) ) NEW_LINE |
Smallest N digit number which is a multiple of 5 | Function to return the smallest n digit number which is a multiple of 5 ; Driver code | def smallestMultiple ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 5 NEW_LINE DEDENT return pow ( 10 , n - 1 ) NEW_LINE DEDENT n = 4 NEW_LINE print ( smallestMultiple ( n ) ) NEW_LINE |
Find HCF of two numbers without using recursion or Euclidean algorithm | Function to return the HCF of x and y ; Minimum of the two numbers ; If both the numbers are divisible by the minimum of these two then the HCF is equal to the minimum ; Highest number between 2 and minimum / 2 which can divide both the numbers is the required HCF ; If both the numbers are divisible by i ; 1 divides every number ; Driver code | def getHCF ( x , y ) : NEW_LINE INDENT minimum = min ( x , y ) NEW_LINE if ( x % minimum == 0 and y % minimum == 0 ) : NEW_LINE INDENT return minimum NEW_LINE DEDENT for i in range ( minimum // 2 , 1 , - 1 ) : NEW_LINE INDENT if ( x % i == 0 and y % i == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT x , y = 16 , 32 NEW_LINE print ( getHCF ( x , y ) ) NEW_LINE |
Check if product of first N natural numbers is divisible by their sum | Python 3 implementation of the approach ; Function that returns true if n is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function that return true if the product of the first n natural numbers is divisible by the sum of first n natural numbers ; Driver code | from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 5 , int ( sqrt ( n ) ) + 1 , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isDivisible ( n ) : NEW_LINE INDENT if ( isPrime ( n + 1 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE if ( isDivisible ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Maximum sum of cocktail glass in a 2D matrix | Python 3 implementation of the approach ; Function to return the maximum sum of a cocktail glass ; If no cocktail glass is possible ; Initialize max_sum with the mini ; Here loop runs ( R - 2 ) * ( C - 2 ) times considering different top left cells of cocktail glasses ; Considering mat [ i ] [ j ] as the top left cell of the cocktail glass ; Update the max_sum ; Driver code | import sys NEW_LINE R = 5 NEW_LINE C = 5 NEW_LINE def findMaxCock ( ar ) : NEW_LINE INDENT if ( R < 3 or C < 3 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT max_sum = - sys . maxsize - 1 NEW_LINE for i in range ( R - 2 ) : NEW_LINE INDENT for j in range ( C - 2 ) : NEW_LINE INDENT sum = ( ( ar [ i ] [ j ] + ar [ i ] [ j + 2 ] ) + ( ar [ i + 1 ] [ j + 1 ] ) + ( ar [ i + 2 ] [ j ] + ar [ i + 2 ] [ j + 1 ] + ar [ i + 2 ] [ j + 2 ] ) ) NEW_LINE max_sum = max ( max_sum , sum ) NEW_LINE DEDENT DEDENT return max_sum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ar = [ [ 0 , 3 , 0 , 6 , 0 ] , [ 0 , 1 , 1 , 0 , 0 ] , [ 1 , 1 , 1 , 0 , 0 ] , [ 0 , 0 , 2 , 0 , 1 ] , [ 0 , 2 , 0 , 1 , 3 ] ] NEW_LINE print ( findMaxCock ( ar ) ) NEW_LINE DEDENT |
Find the number of sub arrays in the permutation of first N natural numbers such that their median is M | Function to return the count of sub - arrays in the given permutation of first n natural numbers such that their median is m ; If element is less than m ; If element greater than m ; If m is found ; Count the answer ; Increment Sum ; Driver code | def segments ( n , p , m ) : NEW_LINE INDENT c = dict ( ) NEW_LINE c [ 0 ] = 1 NEW_LINE has = False NEW_LINE Sum = 0 NEW_LINE ans = 0 NEW_LINE for r in range ( n ) : NEW_LINE INDENT if ( p [ r ] < m ) : NEW_LINE INDENT Sum -= 1 NEW_LINE DEDENT elif ( p [ r ] > m ) : NEW_LINE INDENT Sum += 1 NEW_LINE DEDENT if ( p [ r ] == m ) : NEW_LINE INDENT has = True NEW_LINE DEDENT if ( has ) : NEW_LINE INDENT if ( Sum in c . keys ( ) ) : NEW_LINE INDENT ans += c [ Sum ] NEW_LINE DEDENT if Sum - 1 in c . keys ( ) : NEW_LINE INDENT ans += c [ Sum - 1 ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT c [ Sum ] = c . get ( Sum , 0 ) + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT a = [ 2 , 4 , 5 , 3 , 1 ] NEW_LINE n = len ( a ) NEW_LINE m = 4 NEW_LINE print ( segments ( n , a , m ) ) NEW_LINE |
Program to calculate the number of odd days in given number of years | Function to return the count of odd days ; Count of years divisible by 100 and 400 ; Every 4 th year is a leap year ; Every 100 th year is divisible by 4 but is not a leap year ; Every 400 th year is divisible by 100 but is a leap year ; Total number of extra days ; modulo ( 7 ) for final answer ; Number of days | def oddDays ( N ) : NEW_LINE INDENT hund1 = N // 100 NEW_LINE hund4 = N // 400 NEW_LINE leap = N >> 2 NEW_LINE ordd = N - leap NEW_LINE if ( hund1 ) : NEW_LINE INDENT ordd += hund1 NEW_LINE leap -= hund1 NEW_LINE DEDENT if ( hund4 ) : NEW_LINE INDENT ordd -= hund4 NEW_LINE leap += hund4 NEW_LINE DEDENT days = ordd + leap * 2 NEW_LINE odd = days % 7 NEW_LINE return odd NEW_LINE DEDENT N = 100 NEW_LINE print ( oddDays ( N ) ) NEW_LINE |
Largest ellipse that can be inscribed within a rectangle which in turn is inscribed within a semicircle | Function to find the area of the biggest ellipse ; the radius cannot be negative ; area of the ellipse ; Driver code | def ellipsearea ( r ) : NEW_LINE INDENT if ( r < 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT a = ( 3.14 * r * r ) / 4 ; NEW_LINE return a ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT r = 5 ; NEW_LINE print ( ellipsearea ( r ) ) ; NEW_LINE DEDENT |
Find the minimum number of operations required to make all array elements equal | Python3 implementation of the approach ; Function to return the minimum operations required to make all array elements equal ; To store the frequency of all the array elements ; Traverse through array elements and update frequencies ; To store the maximum frequency of an element from the array ; Traverse through the map and find the maximum frequency for any element ; Return the minimum operations required ; Driver code | import sys NEW_LINE def minOperations ( arr , n ) : NEW_LINE INDENT mp = dict . fromkeys ( arr , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 ; NEW_LINE DEDENT maxFreq = - ( sys . maxsize - 1 ) ; NEW_LINE for key in mp : NEW_LINE INDENT maxFreq = max ( maxFreq , mp [ key ] ) ; NEW_LINE DEDENT return ( n - maxFreq ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 6 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( minOperations ( arr , n ) ) ; NEW_LINE DEDENT |
Count all prefixes of the given binary array which are divisible by x | Function to return the count of total binary prefix which are divisible by x ; Initialize with zero ; Convert all prefixes to decimal ; If number is divisible by x then increase count ; Driver code | def CntDivbyX ( arr , n , x ) : NEW_LINE INDENT number = 0 NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT number = number * 2 + arr [ i ] NEW_LINE if ( ( number % x == 0 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 1 , 0 , 1 , 1 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE x = 2 NEW_LINE print ( CntDivbyX ( arr , n , x ) ) NEW_LINE DEDENT |
Count consecutive pairs of same elements | Function to return the count of consecutive elements in the array which are equal ; If consecutive elements are same ; Driver code | def countCon ( ar , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( ar [ i ] == ar [ i + 1 ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT ar = [ 1 , 2 , 2 , 3 , 4 , 4 , 5 , 5 , 5 , 5 ] NEW_LINE n = len ( ar ) NEW_LINE print ( countCon ( ar , n ) ) NEW_LINE |
Reduce the fraction to its lowest form | Python3 program to reduce a fraction x / y to its lowest form ; Function to reduce a fraction to its lowest form ; Driver Code | from math import gcd NEW_LINE def reduceFraction ( x , y ) : NEW_LINE INDENT d = gcd ( x , y ) ; NEW_LINE x = x // d ; NEW_LINE y = y // d ; NEW_LINE print ( " x β = " , x , " , β y β = " , y ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 16 ; NEW_LINE y = 10 ; NEW_LINE reduceFraction ( x , y ) ; NEW_LINE DEDENT |
Number of ways of choosing K equal substrings of any length for every query | Python3 implementation of the approach ; Function to generate all the sub - strings ; Length of the string ; Generate all sub - strings ; Count the occurrence of every sub - string ; Compute the Binomial Coefficient ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to return the result for a query ; Iterate for every unique sub - string ; Count the combinations ; Driver code ; Get all the sub - strings Store the occurrence of all the sub - strings ; Pre - computation ; Queries ; Perform queries | from collections import defaultdict NEW_LINE maxlen = 100 NEW_LINE def generateSubStrings ( s , mpp ) : NEW_LINE INDENT l = len ( s ) NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT temp = " " NEW_LINE for j in range ( i , l ) : NEW_LINE INDENT temp += s [ j ] NEW_LINE mpp [ temp ] += 1 NEW_LINE DEDENT DEDENT DEDENT def binomialCoeff ( C ) : NEW_LINE INDENT for i in range ( 0 , 100 ) : NEW_LINE INDENT for j in range ( 0 , 100 ) : NEW_LINE INDENT if j == 0 or j == i : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def answerQuery ( mpp , C , k ) : NEW_LINE INDENT ans = 0 NEW_LINE for it in mpp : NEW_LINE INDENT if mpp [ it ] >= k : NEW_LINE INDENT ans += C [ mpp [ it ] ] [ k ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aabaab " NEW_LINE mpp = defaultdict ( lambda : 0 ) NEW_LINE generateSubStrings ( s , mpp ) NEW_LINE C = [ [ 0 for i in range ( maxlen ) ] for j in range ( maxlen ) ] NEW_LINE binomialCoeff ( C ) NEW_LINE queries = [ 2 , 3 , 4 ] NEW_LINE q = len ( queries ) NEW_LINE for i in range ( 0 , q ) : NEW_LINE INDENT print ( answerQuery ( mpp , C , queries [ i ] ) ) NEW_LINE DEDENT DEDENT |
Times required by Simple interest for the Principal to become Y times itself | Function to return the no . of years ; Driver code | def noOfYears ( t1 , n1 , t2 ) : NEW_LINE INDENT years = ( t2 - 1 ) * n1 / ( t1 - 1 ) NEW_LINE return years NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT T1 , N1 , T2 = 3 , 5 , 6 NEW_LINE print ( noOfYears ( T1 , N1 , T2 ) ) NEW_LINE DEDENT |
Check if a given number divides the sum of the factorials of its digits | Function that returns true if n divides the sum of the factorials of its digits ; To store factorials of digits ; To store sum of the factorials of the digits ; Store copy of the given number ; Store sum of the factorials of the digits ; If it is divisible ; Driver code | def isPossible ( n ) : NEW_LINE INDENT fac = [ 0 for i in range ( 10 ) ] NEW_LINE fac [ 0 ] = 1 NEW_LINE fac [ 1 ] = 1 NEW_LINE for i in range ( 2 , 10 , 1 ) : NEW_LINE INDENT fac [ i ] = fac [ i - 1 ] * i NEW_LINE DEDENT sum = 0 NEW_LINE x = n NEW_LINE while ( x ) : NEW_LINE INDENT sum += fac [ x % 10 ] NEW_LINE x = int ( x / 10 ) NEW_LINE DEDENT if ( sum % n == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 19 NEW_LINE if ( isPossible ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Find the longest subsequence of an array having LCM at most K | Python3 implementation of the approach ; Function to find the longest subsequence having LCM less than or equal to K ; Map to store unique elements and their frequencies ; Update the frequencies ; Array to store the count of numbers whom 1 <= X <= K is a multiple of ; Check every unique element ; Find all its multiples <= K ; Store its frequency ; Obtain the number having maximum count ; Condition to check if answer doesn 't exist ; Print the answer ; Driver code | from collections import defaultdict NEW_LINE def findSubsequence ( arr , n , k ) : NEW_LINE INDENT M = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT M [ arr [ i ] ] += 1 NEW_LINE DEDENT numCount = [ 0 ] * ( k + 1 ) NEW_LINE for p in M : NEW_LINE INDENT if p <= k : NEW_LINE INDENT i = 1 NEW_LINE while p * i <= k : NEW_LINE INDENT numCount [ p * i ] += M [ p ] NEW_LINE i += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT lcm , length = 0 , 0 NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT if numCount [ i ] > length : NEW_LINE INDENT length = numCount [ i ] NEW_LINE lcm = i NEW_LINE DEDENT DEDENT if lcm == 0 : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " LCM β = β { 0 } , β Length β = β { 1 } " . format ( lcm , length ) ) NEW_LINE print ( " Indexes β = β " , end = " " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if lcm % arr [ i ] == 0 : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k = 14 NEW_LINE arr = [ 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE findSubsequence ( arr , n , k ) NEW_LINE DEDENT |
Count number of binary strings of length N having only 0 ' s β and β 1' s | Python 3 implementation of the approach ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; Function to count the number of binary strings of length N having only 0 ' s β and β 1' s ; Driver code | mod = 1000000007 NEW_LINE def power ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def findCount ( N ) : NEW_LINE INDENT count = power ( 2 , N , mod ) NEW_LINE return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 25 NEW_LINE print ( findCount ( N ) ) NEW_LINE DEDENT |
XOR of all the elements in the given range [ L , R ] | Function to return the most significant bit ; Function to return the required XOR ; Finding the MSB ; Value of the current bit to be added ; To store the final answer ; Loop for case 1 ; Edge case when both the integers lie in the same segment of continuous 1 s ; To store whether parity of count is odd ; Updating the answer if parity is odd ; Updating the number to be added ; Case 2 ; Driver code ; Final answer | def msb ( x ) : NEW_LINE INDENT ret = 0 NEW_LINE while ( ( x >> ( ret + 1 ) ) != 0 ) : NEW_LINE INDENT ret = ret + 1 NEW_LINE DEDENT return ret NEW_LINE DEDENT def xorRange ( l , r ) : NEW_LINE INDENT max_bit = msb ( r ) NEW_LINE mul = 2 NEW_LINE ans = 0 NEW_LINE for i in range ( 1 , max_bit + 1 ) : NEW_LINE INDENT if ( ( l // mul ) * mul == ( r // mul ) * mul ) : NEW_LINE INDENT if ( ( ( ( l & ( 1 << i ) ) != 0 ) and ( r - l + 1 ) % 2 == 1 ) ) : NEW_LINE INDENT ans = ans + mul NEW_LINE DEDENT mul = mul * 2 NEW_LINE continue NEW_LINE DEDENT odd_c = 0 NEW_LINE if ( ( ( l & ( 1 << i ) ) != 0 ) and l % 2 == 1 ) : NEW_LINE INDENT odd_c = ( odd_c ^ 1 ) NEW_LINE DEDENT if ( ( ( r & ( 1 << i ) ) != 0 ) and r % 2 == 0 ) : NEW_LINE INDENT odd_c = ( odd_c ^ 1 ) NEW_LINE DEDENT if ( odd_c ) : NEW_LINE INDENT ans = ans + mul NEW_LINE DEDENT mul = mul * 2 NEW_LINE DEDENT zero_bit_cnt = ( r - l + 1 ) // 2 NEW_LINE if ( ( l % 2 == 1 ) and ( r % 2 == 1 ) ) : NEW_LINE INDENT zero_bit_cnt = zero_bit_cnt + 1 NEW_LINE DEDENT if ( zero_bit_cnt % 2 == 1 ) : NEW_LINE INDENT ans = ans + 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT l = 1 NEW_LINE r = 4 NEW_LINE print ( xorRange ( l , r ) ) NEW_LINE |
XOR of all the elements in the given range [ L , R ] | Function to return the required XOR ; Modulus operator are expensive on most of the computers . n & 3 will be equivalent to n % 4 n % 4 ; If n is a multiple of 4 ; If n % 4 gives remainder 1 ; If n % 4 gives remainder 2 ; If n % 4 gives remainder 3 ; Driver code | def computeXOR ( n ) : NEW_LINE INDENT switch = { 0 : n , 1 : 1 , 2 : n + 1 , 3 : 0 , } NEW_LINE return switch . get ( n & 3 , " " ) NEW_LINE DEDENT l = 1 NEW_LINE r = 4 NEW_LINE print ( computeXOR ( r ) ^ computeXOR ( l - 1 ) ) NEW_LINE |
Find the number of integers from 1 to n which contains digits 0 ' s β and β 1' s only | Function to find the number of integers from 1 to n which contains 0 ' s β and β 1' s only ; If number is greater than n ; otherwise add count this number and call two functions ; Driver code | def countNumbers ( x , n ) : NEW_LINE INDENT if x > n : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( 1 + countNumbers ( x * 10 , n ) + countNumbers ( x * 10 + 1 , n ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 120 ; NEW_LINE print ( countNumbers ( 1 , n ) ) ; NEW_LINE DEDENT |
Check if factorial of N is divisible by the sum of squares of first N natural numbers | Python 3 implementation of the approach ; Function to count number of times prime P divide factorial N ; Lengendre Formula ; Function to find count number of times all prime P divide summation ; Formula for summation of square after removing n and constant 6 ; Loop to traverse over all prime P which divide summation ; If Number itself is a Prime Number ; Driver Code | from math import sqrt NEW_LINE def checkfact ( N , countprime , prime ) : NEW_LINE INDENT countfact = 0 NEW_LINE if ( prime == 2 or prime == 3 ) : NEW_LINE INDENT countfact += 1 NEW_LINE DEDENT divide = prime NEW_LINE while ( int ( N / divide ) != 0 ) : NEW_LINE INDENT countfact += int ( N / divide ) NEW_LINE divide = divide * divide NEW_LINE DEDENT if ( countfact >= countprime ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def check ( N ) : NEW_LINE INDENT sumsquares = ( N + 1 ) * ( 2 * N + 1 ) NEW_LINE countprime = 0 NEW_LINE for i in range ( 2 , int ( sqrt ( sumsquares ) ) + 1 , 1 ) : NEW_LINE INDENT flag = 0 NEW_LINE while ( sumsquares % i == 0 ) : NEW_LINE INDENT flag = 1 NEW_LINE countprime += 1 NEW_LINE sumsquares /= i NEW_LINE DEDENT if ( flag ) : NEW_LINE INDENT if ( checkfact ( N - 1 , countprime , i ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT countprime = 0 NEW_LINE DEDENT DEDENT if ( sumsquares != 1 ) : NEW_LINE INDENT if ( checkfact ( N - 1 , 1 , sumsquares ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE if ( check ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Count the number of non | Python3 program to count number of non increasing subarrays ; Initialize result ; Initialize length of current non - increasing subarray ; Traverse through the array ; If arr [ i + 1 ] is less than or equal to arr [ i ] , then increment length ; Else Update count and reset length ; If last length is more than 1 ; Driver code | def countNonIncreasing ( arr , n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE len = 1 ; NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr [ i + 1 ] <= arr [ i ] ) : NEW_LINE INDENT len += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT cnt += ( ( ( len + 1 ) * len ) / 2 ) ; NEW_LINE len = 1 ; NEW_LINE DEDENT DEDENT if ( len > 1 ) : NEW_LINE INDENT cnt += ( ( ( len + 1 ) * len ) / 2 ) ; NEW_LINE DEDENT return int ( cnt ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 2 , 3 , 7 , 1 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countNonIncreasing ( arr , n ) ) ; NEW_LINE DEDENT |
Minimum array elements to be changed to make Recaman 's sequence | Python3 implementation of the approach ; First term of the sequence is always 0 ; Fill remaining terms using recursive formula ; If arr [ i - 1 ] - i is negative or already exists ; Function that returns minimum changes required ; Set to store first n Recaman numbers ; Generate and store first n Recaman numbers ; Insert first n Recaman numbers to set ; If current element of the array is present in the set ; Return the remaining number of elements in the set ; Driver code | def recamanGenerator ( arr , n ) : NEW_LINE INDENT arr [ 0 ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT temp = arr [ i - 1 ] - i NEW_LINE j = 0 NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( ( arr [ j ] == temp ) or temp < 0 ) : NEW_LINE INDENT temp = arr [ i - 1 ] + i NEW_LINE break NEW_LINE DEDENT DEDENT arr [ i ] = temp NEW_LINE DEDENT DEDENT def recamanArray ( arr , n ) : NEW_LINE INDENT s = dict ( ) NEW_LINE recaman = [ 0 for i in range ( n ) ] NEW_LINE recamanGenerator ( recaman , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s [ recaman [ i ] ] = s . get ( recaman [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in s . keys ( ) : NEW_LINE INDENT del s [ arr [ i ] ] NEW_LINE DEDENT DEDENT return len ( s ) NEW_LINE DEDENT arr = [ 7 , 11 , 20 , 4 , 2 , 1 , 8 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( recamanArray ( arr , n ) ) NEW_LINE |
Check if product of array containing prime numbers is a perfect square | Function that returns true if the product of all the array elements is a perfect square ; Update the frequencies of all the array elements ; If frequency of some element in the array is odd ; Driver code | def isPerfectSquare ( arr , n ) : NEW_LINE INDENT umap = dict . fromkeys ( arr , n ) ; NEW_LINE for key in arr : NEW_LINE INDENT umap [ key ] += 1 ; NEW_LINE DEDENT for key in arr : NEW_LINE INDENT if ( umap [ key ] % 2 == 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 2 , 7 , 7 ] ; NEW_LINE n = len ( arr ) NEW_LINE if ( isPerfectSquare ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Find the good permutation of first N natural numbers | Function to print the good permutation of first N natural numbers ; If n is odd ; Otherwise ; Driver code | def printPermutation ( n ) : NEW_LINE INDENT if ( n % 2 != 0 ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 1 , ( n // 2 ) + 1 ) : NEW_LINE INDENT print ( ( 2 * i ) , ( 2 * i - 1 ) , end = " β " ) ; NEW_LINE DEDENT DEDENT DEDENT n = 4 ; NEW_LINE printPermutation ( n ) ; NEW_LINE |
Minimum number operations required to convert n to m | Set | Python 3 implementation of the above approach ; Function to find the minimum number of steps ; If n exceeds M ; If N reaches the target ; The minimum of both the states will be the answer ; Driver code | MAXN = 10000000 NEW_LINE def minimumSteps ( n , m , a , b ) : NEW_LINE INDENT if ( n > m ) : NEW_LINE INDENT return MAXN NEW_LINE DEDENT if ( n == m ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return min ( 1 + minimumSteps ( n * a , m , a , b ) , 1 + minimumSteps ( n * b , m , a , b ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 120 NEW_LINE m = 51840 NEW_LINE a = 2 NEW_LINE b = 3 NEW_LINE print ( minimumSteps ( n , m , a , b ) ) NEW_LINE DEDENT |
Minimum number of given operation required to convert n to m | Function to return the minimum operations required ; Counting all 2 s ; Counting all 3 s ; If q contained only 2 and 3 as the only prime factors then it must be 1 now ; Driver code | def minOperations ( n , m ) : NEW_LINE INDENT if ( m % n != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT minOperations = 0 NEW_LINE q = int ( m / n ) NEW_LINE while ( q % 2 == 0 ) : NEW_LINE INDENT q = int ( q / 2 ) NEW_LINE minOperations += 1 NEW_LINE DEDENT while ( q % 3 == 0 ) : NEW_LINE INDENT q = int ( q / 3 ) NEW_LINE minOperations += 1 NEW_LINE DEDENT if ( q == 1 ) : NEW_LINE INDENT return minOperations NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 120 NEW_LINE m = 51840 NEW_LINE print ( minOperations ( n , m ) ) NEW_LINE DEDENT |
Sum of Fibonacci Numbers in a range | Function to return the nth Fibonacci number ; Function to return the required sum ; To store the sum ; Calculate the sum ; Driver Code | def fib ( n ) : NEW_LINE INDENT phi = ( ( 1 + ( 5 ** ( 1 / 2 ) ) ) / 2 ) ; NEW_LINE return round ( ( phi ** n ) / ( 5 ** ( 1 / 2 ) ) ) ; NEW_LINE DEDENT def calculateSum ( l , r ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT sum += fib ( i ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l , r = 4 , 8 ; NEW_LINE print ( calculateSum ( l , r ) ) ; NEW_LINE DEDENT |
Largest sphere that can be inscribed within a cube which is in turn inscribed within a right circular cone | Program to find the biggest sphere which is inscribed within a cube which in turn inscribed within a right circular cone ; Function to find the radius of the sphere ; height and radius cannot be negative ; radius of the sphere ; Driver code | import math NEW_LINE def sphereSide ( h , r ) : NEW_LINE INDENT if h < 0 and r < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT R = ( ( ( h * r * math . sqrt ( 2 ) ) ) / ( h + math . sqrt ( 2 ) * r ) / 2 ) NEW_LINE return R NEW_LINE DEDENT h = 5 ; r = 6 NEW_LINE print ( sphereSide ( h , r ) ) NEW_LINE |
Find the number of ways to divide number into four parts such that a = c and b = d | Function to find the number of ways to divide N into four parts such that a = c and b = d ; Driver code | def possibleways ( n ) : NEW_LINE INDENT if ( n % 2 == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT elif ( n % 4 == 0 ) : NEW_LINE INDENT return n // 4 - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return n // 4 ; NEW_LINE DEDENT DEDENT n = 20 ; NEW_LINE print ( possibleways ( n ) ) ; NEW_LINE |
Count sub | Function to count sub - arrays whose product is divisible by K ; Calculate the product of the current sub - array ; If product of the current sub - array is divisible by K ; Driver code | def countSubarrays ( arr , n , K ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT product = 1 NEW_LINE for x in range ( i , j + 1 ) : NEW_LINE INDENT product *= arr [ x ] NEW_LINE DEDENT if ( product % K == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 2 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE K = 4 NEW_LINE print ( countSubarrays ( arr , n , K ) ) NEW_LINE DEDENT |
Count sub | Python3 implementation of the approach ; Segment tree implemented as an array ; Function to build the segment tree ; Function to query product of sub - array [ l . . r ] in O ( log n ) time ; Function to count sub - arrays whose product is divisible by K ; Query segment tree to find product % k of the sub - array [ i . . j ] ; Driver code ; Build the segment tree | MAX = 100002 NEW_LINE tree = [ 0 for i in range ( 4 * MAX ) ] ; NEW_LINE def build ( node , start , end , arr , k ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT tree [ node ] = ( arr [ start ] ) % k ; NEW_LINE return ; NEW_LINE DEDENT mid = ( start + end ) >> 1 ; NEW_LINE build ( 2 * node , start , mid , arr , k ) ; NEW_LINE build ( 2 * node + 1 , mid + 1 , end , arr , k ) ; NEW_LINE tree [ node ] = ( tree [ 2 * node ] * tree [ 2 * node + 1 ] ) % k ; NEW_LINE DEDENT def query ( node , start , end , l , r , k ) : NEW_LINE INDENT if ( start > end or start > r or end < l ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( start >= l and end <= r ) : NEW_LINE INDENT return tree [ node ] % k ; NEW_LINE DEDENT mid = ( start + end ) >> 1 ; NEW_LINE q1 = query ( 2 * node , start , mid , l , r , k ) ; NEW_LINE q2 = query ( 2 * node + 1 , mid + 1 , end , l , r , k ) ; NEW_LINE return ( q1 * q2 ) % k ; NEW_LINE DEDENT def countSubarrays ( arr , n , k ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT product_mod_k = query ( 1 , 0 , n - 1 , i , j , k ) ; NEW_LINE if ( product_mod_k == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 6 , 2 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE k = 4 ; NEW_LINE build ( 1 , 0 , n - 1 , arr , k ) ; NEW_LINE print ( countSubarrays ( arr , n , k ) ) NEW_LINE DEDENT |
Find a pair from the given array with maximum nCr value | Function to print the pair that gives maximum nCr ; This gives the value of N in nCr ; Case 1 : When N is odd ; Case 2 : When N is even ; Driver code | def printMaxValPair ( v , n ) : NEW_LINE INDENT v . sort ( ) NEW_LINE N = v [ n - 1 ] NEW_LINE if N % 2 == 1 : NEW_LINE INDENT first_maxima = N // 2 NEW_LINE second_maxima = first_maxima + 1 NEW_LINE ans1 , ans2 = 3 * ( 10 ** 18 ) , 3 * ( 10 ** 18 ) NEW_LINE from_left , from_right = - 1 , - 1 NEW_LINE _from = - 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if v [ i ] > first_maxima : NEW_LINE INDENT _from = i NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT diff = first_maxima - v [ i ] NEW_LINE if diff < ans1 : NEW_LINE INDENT ans1 = diff NEW_LINE from_left = v [ i ] NEW_LINE DEDENT DEDENT DEDENT from_right = v [ _from ] NEW_LINE diff1 = first_maxima - from_left NEW_LINE diff2 = from_right - second_maxima NEW_LINE if diff1 < diff2 : NEW_LINE INDENT print ( N , from_left ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( N , from_right ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT maxima = N // 2 NEW_LINE ans1 = 3 * ( 10 ** 18 ) NEW_LINE R = - 1 NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT diff = abs ( v [ i ] - maxima ) NEW_LINE if diff < ans1 : NEW_LINE INDENT ans1 = diff NEW_LINE R = v [ i ] NEW_LINE DEDENT DEDENT print ( N , R ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT v = [ 1 , 1 , 2 , 3 , 6 , 1 ] NEW_LINE n = len ( v ) NEW_LINE printMaxValPair ( v , n ) NEW_LINE DEDENT |
Find the number of good permutations | Function to return the count of good permutations ; For m = 0 , ans is 1 ; If k is greater than 1 ; If k is greater than 2 ; If k is greater than 3 ; Driver code | def Permutations ( n , k ) : NEW_LINE INDENT ans = 1 NEW_LINE if k >= 2 : NEW_LINE INDENT ans += ( n ) * ( n - 1 ) // 2 NEW_LINE DEDENT if k >= 3 : NEW_LINE INDENT ans += ( ( n ) * ( n - 1 ) * ( n - 2 ) * 2 // 6 ) NEW_LINE DEDENT if k >= 4 : NEW_LINE INDENT ans += ( ( n ) * ( n - 1 ) * ( n - 2 ) * ( n - 3 ) * 9 // 24 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 5 , 2 NEW_LINE print ( Permutations ( n , k ) ) NEW_LINE DEDENT |
Count integers in a range which are divisible by their euler totient value | Function to return a ^ n ; Function to return count of integers that satisfy n % phi ( n ) = 0 ; Driver Code | def power ( a , n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT p = power ( a , n // 2 ) NEW_LINE p = p * p NEW_LINE if n & 1 : NEW_LINE INDENT p = p * a NEW_LINE DEDENT return p NEW_LINE DEDENT def countIntegers ( l , r ) : NEW_LINE INDENT ans , i = 0 , 1 NEW_LINE v = power ( 2 , i ) NEW_LINE while v <= r : NEW_LINE INDENT while v <= r : NEW_LINE INDENT if v >= l : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT v = v * 3 NEW_LINE DEDENT i += 1 NEW_LINE v = power ( 2 , i ) NEW_LINE DEDENT if l == 1 : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l , r = 12 , 21 NEW_LINE print ( countIntegers ( l , r ) ) NEW_LINE DEDENT |
Number of pairs from the first N natural numbers whose sum is divisible by K | Function to find the number of pairs from the set of natural numbers up to N whose sum is divisible by K ; Declaring a Hash to store count ; Storing the count of integers with a specific remainder in Hash array ; Check if K is even ; Count of pairs when both integers are divisible by K ; Count of pairs when one remainder is R and other remainder is K - R ; Count of pairs when both the remainders are K / 2 ; Count of pairs when both integers are divisible by K ; Count of pairs when one remainder is R and other remainder is K - R ; Driver code ; Print the count of pairs | def findPairCount ( N , K ) : NEW_LINE INDENT count = 0 ; NEW_LINE rem = [ 0 ] * K ; NEW_LINE rem [ 0 ] = N // K ; NEW_LINE for i in range ( 1 , K ) : NEW_LINE INDENT rem [ i ] = ( N - i ) // K + 1 ; NEW_LINE DEDENT if ( K % 2 == 0 ) : NEW_LINE INDENT count += ( rem [ 0 ] * ( rem [ 0 ] - 1 ) ) // 2 ; NEW_LINE for i in range ( 1 , K // 2 ) : NEW_LINE INDENT count += rem [ i ] * rem [ K - i ] ; NEW_LINE DEDENT count += ( rem [ K // 2 ] * ( rem [ K // 2 ] - 1 ) ) // 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT count += ( rem [ 0 ] * ( rem [ 0 ] - 1 ) ) // 2 ; NEW_LINE for i in rage ( 1 , K // 2 + 1 ) : NEW_LINE INDENT count += rem [ i ] * rem [ K - i ] ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 10 ; K = 4 ; NEW_LINE print ( findPairCount ( N , K ) ) ; NEW_LINE DEDENT |
Find the sum of all Truncatable primes below N | Python3 implementation of the above approach ; To check if a number is prime or not ; Sieve of Eratosthenes function to find all prime numbers ; Function to return the sum of all truncatable primes below n ; To store the required sum ; Check every number below n ; Check from right to left ; If number is not prime at any stage ; Check from left to right ; If number is not prime at any stage ; If flag is still true ; Return the required sum ; Driver code | N = 1000005 NEW_LINE prime = [ True for i in range ( N ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT prime [ 1 ] = False NEW_LINE prime [ 0 ] = False NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT if ( prime [ i ] == True ) : NEW_LINE INDENT for j in range ( i * 2 , N , i ) : NEW_LINE INDENT prime [ j ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def sumTruncatablePrimes ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT num = i NEW_LINE flag = True NEW_LINE while ( num ) : NEW_LINE INDENT if ( prime [ num ] == False ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT num //= 10 NEW_LINE DEDENT num = i NEW_LINE power = 10 NEW_LINE while ( num // power ) : NEW_LINE INDENT if ( prime [ num % power ] == False ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT power *= 10 NEW_LINE DEDENT if ( flag == True ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT n = 25 NEW_LINE sieve ( ) NEW_LINE print ( sumTruncatablePrimes ( n ) ) NEW_LINE |
Smallest and Largest N | Python3 implementation of the approach ; Function to print the largest and the smallest n - digit perfect squares ; Smallest n - digit perfect square ; Largest n - digit perfect square ; Driver code | import math NEW_LINE def nDigitPerfectSquares ( n ) : NEW_LINE INDENT print ( pow ( math . ceil ( math . sqrt ( pow ( 10 , n - 1 ) ) ) , 2 ) , end = " β " ) ; NEW_LINE print ( pow ( math . ceil ( math . sqrt ( pow ( 10 , n ) ) ) - 1 , 2 ) ) ; NEW_LINE DEDENT n = 4 ; NEW_LINE nDigitPerfectSquares ( n ) ; NEW_LINE |
Maximum trace possible for any sub | Python 3 implementation of the approach ; Function to return the maximum trace possible for a sub - matrix of the given matrix ; Calculate the trace for each of the sub - matrix with top left corner at cell ( r , s ) ; Update the maximum trace ; Return the maximum trace ; Driver code | N = 3 NEW_LINE def MaxTraceSub ( mat ) : NEW_LINE INDENT max_trace = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT r = i NEW_LINE s = j NEW_LINE trace = 0 NEW_LINE while ( r < N and s < N ) : NEW_LINE INDENT trace += mat [ r ] NEW_LINE r += 1 NEW_LINE s += 1 NEW_LINE max_trace = max ( trace , max_trace ) NEW_LINE DEDENT DEDENT DEDENT return max_trace NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 10 , 2 , 5 ] , [ 6 , 10 , 4 ] , [ 2 , 7 , - 10 ] ] NEW_LINE print ( MaxTraceSub ( mat ) ) NEW_LINE DEDENT |
Check if matrix can be converted to another matrix by transposing square sub | Python 3 implementation of the approach ; Function that returns true if matrix1 can be converted to matrix2 with the given operation ; Traverse all the diagonals starting at first column ; Traverse in diagonal ; Store the diagonal elements ; Move up ; Sort the elements ; Check if they are same ; Traverse all the diagonals starting at last row ; Traverse in the diagonal ; Store diagonal elements ; Sort all elements ; Check for same ; If every element matches ; Driver code | n = 3 NEW_LINE m = 3 NEW_LINE def check ( a , b ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE r = i NEW_LINE col = 0 NEW_LINE while ( r >= 0 and col < m ) : NEW_LINE INDENT v1 . append ( a [ r ] [ col ] ) NEW_LINE v2 . append ( b [ r ] [ col ] ) NEW_LINE r -= 1 NEW_LINE col += 1 NEW_LINE DEDENT v1 . sort ( reverse = False ) NEW_LINE v2 . sort ( reverse = False ) NEW_LINE for i in range ( len ( v1 ) ) : NEW_LINE INDENT if ( v1 [ i ] != v2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT for j in range ( 1 , m ) : NEW_LINE INDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE r = n - 1 NEW_LINE col = j NEW_LINE while ( r >= 0 and col < m ) : NEW_LINE INDENT v1 . append ( a [ r ] [ col ] ) NEW_LINE v2 . append ( b [ r ] [ col ] ) NEW_LINE r -= 1 NEW_LINE col += 1 NEW_LINE DEDENT v1 . sort ( reverse = False ) NEW_LINE v2 . sort ( reverse = False ) NEW_LINE for i in range ( len ( v1 ) ) : NEW_LINE INDENT if ( v1 [ i ] != v2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE b = [ [ 1 , 4 , 7 ] , [ 2 , 5 , 6 ] , [ 3 , 8 , 9 ] ] NEW_LINE if ( check ( a , b ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Last digit of Product of two Large or Small numbers ( a * b ) | Function to print the last digit of product a * b ; Driver code | def lastDigit ( a , b ) : NEW_LINE INDENT lastDig = ( ( int ( a [ len ( a ) - 1 ] ) - int ( '0' ) ) * ( int ( b [ len ( b ) - 1 ] ) - int ( '0' ) ) ) NEW_LINE print ( lastDig % 10 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a , b = "1234567891233" , "1234567891233156" NEW_LINE lastDigit ( a , b ) NEW_LINE DEDENT |
Smallest and Largest Palindrome with N Digits | Python 3 implementation of the above approach ; Function to print the smallest and largest palindrome with N digits ; Driver Code | from math import pow NEW_LINE def printPalindrome ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( " Smallest β Palindrome : β 0" ) NEW_LINE print ( " Largest β Palindrome : β 9" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Smallest β Palindrome : " , int ( pow ( 10 , n - 1 ) ) + 1 ) NEW_LINE print ( " Largest β Palindrome : " , int ( pow ( 10 , n ) ) - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE printPalindrome ( n ) NEW_LINE DEDENT |
Addition of two numbers without propagating Carry | Function to prsum of 2 numbers without propagating carry ; Reverse a ; Reverse b ; Generate sum Since length of both a and b are same , take any one of them . ; Extract digits from a and b and add ; If sum is single digit ; If sum is not single digit reverse sum ; Extract digits from sum and append to result ; Driver code | def printSum ( a , b ) : NEW_LINE INDENT res , temp1 , temp2 = 0 , 0 , 0 NEW_LINE while a > 0 : NEW_LINE INDENT temp1 = temp1 * 10 + ( a % 10 ) NEW_LINE a //= 10 NEW_LINE DEDENT a = temp1 NEW_LINE while b > 0 : NEW_LINE INDENT temp2 = temp2 * 10 + ( b % 10 ) NEW_LINE b //= 10 NEW_LINE DEDENT b = temp2 NEW_LINE while a : NEW_LINE INDENT Sum = a % 10 + b % 10 NEW_LINE if Sum // 10 == 0 : NEW_LINE INDENT res = res * 10 + Sum NEW_LINE DEDENT else : NEW_LINE INDENT temp1 = 0 NEW_LINE while Sum > 0 : NEW_LINE INDENT temp1 = temp1 * 10 + ( Sum % 10 ) NEW_LINE Sum //= 10 NEW_LINE DEDENT Sum = temp1 NEW_LINE while Sum > 0 : NEW_LINE INDENT res = res * 10 + ( Sum % 10 ) NEW_LINE Sum //= 10 NEW_LINE DEDENT DEDENT a //= 10 NEW_LINE b //= 10 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a , b = 7752 , 8834 NEW_LINE print ( printSum ( a , b ) ) NEW_LINE DEDENT |
Number of digits before the decimal point in the division of two numbers | Function to return the number of digits before the decimal in a / b ; Absolute value of a / b ; If result is 0 ; Count number of digits in the result ; Return the required count of digits ; Driver code | def countDigits ( a , b ) : NEW_LINE INDENT count = 0 NEW_LINE p = abs ( a // b ) NEW_LINE if ( p == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT while ( p > 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE p = p // 10 NEW_LINE DEDENT return count NEW_LINE DEDENT a = 100 NEW_LINE b = 10 NEW_LINE print ( countDigits ( a , b ) ) NEW_LINE |
Number of digits before the decimal point in the division of two numbers | Python3 implementation of the approach ; Function to return the number of digits before the decimal in a / b ; Return the required count of digits ; Driver code | import math NEW_LINE def countDigits ( a , b ) : NEW_LINE INDENT return math . floor ( math . log10 ( abs ( a ) ) - math . log10 ( abs ( b ) ) ) + 1 NEW_LINE DEDENT a = 100 NEW_LINE b = 10 NEW_LINE print ( countDigits ( a , b ) ) NEW_LINE |
Smallest odd number with N digits | Function to return smallest even number with n digits ; Driver Code | def smallestOdd ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return pow ( 10 , n - 1 ) + 1 NEW_LINE DEDENT n = 4 NEW_LINE print ( smallestOdd ( n ) ) NEW_LINE |
Largest Even and Odd N | Function to print the largest n - digit even and odd numbers ; Driver code | def findNumbers ( n ) : NEW_LINE INDENT odd = pow ( 10 , n ) - 1 NEW_LINE even = odd - 1 NEW_LINE print ( " Even β = β " , even ) NEW_LINE print ( " Odd β = β " , odd ) NEW_LINE DEDENT n = 4 NEW_LINE findNumbers ( n ) NEW_LINE |
Longest sub | Function to return the length of the longest sub - array whose product of elements is 0 ; Driver code | def longestSubArray ( arr , n ) : NEW_LINE INDENT isZeroPresent = False NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT isZeroPresent = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( isZeroPresent ) : NEW_LINE INDENT return n NEW_LINE DEDENT return 0 NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 0 , 1 , 2 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestSubArray ( arr , n ) ) NEW_LINE |
Smallest Even number with N digits | Function to return smallest even number with n digits ; Driver Code | def smallestEven ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return pow ( 10 , n - 1 ) NEW_LINE DEDENT n = 4 NEW_LINE print ( smallestEven ( n ) ) NEW_LINE |
Maximize profit when divisibility by two numbers have associated profits | Python3 implementation of the approach ; Function to return the maximum profit ; min ( x , y ) * n / lcm ( a , b ) ; Driver code | from math import gcd NEW_LINE def maxProfit ( n , a , b , x , y ) : NEW_LINE INDENT res = x * ( n // a ) ; NEW_LINE res += y * ( n // b ) ; NEW_LINE res -= min ( x , y ) * ( n // ( ( a * b ) // gcd ( a , b ) ) ) ; NEW_LINE return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 ; a = 6 ; b = 2 ; x = 8 ; y = 2 ; NEW_LINE print ( maxProfit ( n , a , b , x , y ) ) ; NEW_LINE DEDENT |
Series summation if T ( n ) is given and n is very large | Python 3 implementation of the approach ; Function to return the sum of the given series ; Driver code | from math import pow NEW_LINE MOD = 1000000007 NEW_LINE def sumOfSeries ( n ) : NEW_LINE INDENT ans = pow ( n % MOD , 2 ) NEW_LINE return ( ans % MOD ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE print ( int ( sumOfSeries ( n ) ) ) NEW_LINE DEDENT |
Kth odd number in an array | Function to return the kth odd element from the array ; Traverse the array ; If current element is odd ; If kth odd element is found ; Total odd elements in the array are < k ; Driver code | def kthOdd ( arr , n , k ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT k -= 1 ; NEW_LINE DEDENT if ( k == 0 ) : NEW_LINE INDENT return arr [ i ] ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE print ( kthOdd ( arr , n , k ) ) ; NEW_LINE |
Find last five digits of a given five digit number raised to power five | Function to find the last five digits of a five digit number raised to power five ; Driver code | def lastFiveDigits ( n ) : NEW_LINE INDENT n = ( ( int ) ( n / 10000 ) * 10000 + ( ( int ) ( n / 100 ) % 10 ) * 1000 + ( n % 10 ) * 100 + ( ( int ) ( n / 10 ) % 10 ) * 10 + ( int ) ( n / 1000 ) % 10 ) NEW_LINE ans = 1 NEW_LINE for i in range ( 5 ) : NEW_LINE INDENT ans *= n NEW_LINE ans %= 100000 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12345 NEW_LINE lastFiveDigits ( n ) NEW_LINE DEDENT |
Sum of ( maximum element | Function to return a ^ n % mod ; Compute sum of max ( A ) - min ( A ) for all subsets ; Sort the array . ; Maxs = 2 ^ i - 1 ; Mins = 2 ^ ( n - 1 - i ) - 1 ; Driver code | def power ( a , n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT p = power ( a , n // 2 ) % mod NEW_LINE p = ( p * p ) % mod NEW_LINE if n & 1 == 1 : NEW_LINE INDENT p = ( p * a ) % mod NEW_LINE DEDENT return p NEW_LINE DEDENT def computeSum ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE Sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT maxs = ( power ( 2 , i ) - 1 + mod ) % mod NEW_LINE maxs = ( maxs * arr [ i ] ) % mod NEW_LINE mins = ( power ( 2 , n - 1 - i ) - 1 + mod ) % mod NEW_LINE mins = ( mins * arr [ i ] ) % mod NEW_LINE V = ( maxs - mins + mod ) % mod NEW_LINE Sum = ( Sum + V ) % mod NEW_LINE DEDENT return Sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mod = 1000000007 NEW_LINE arr = [ 4 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( computeSum ( arr , n ) ) NEW_LINE DEDENT |
Count of all N digit numbers such that num + Rev ( num ) = 10 ^ N | Function to return the count of such numbers ; If n is odd ; Driver code | def countNumbers ( n ) : NEW_LINE INDENT if n % 2 == 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( 9 * pow ( 10 , n // 2 - 1 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 NEW_LINE print ( countNumbers ( n ) ) NEW_LINE DEDENT |
Count of numbers having only 1 set bit in the range [ 0 , n ] | Function to return the required count ; To store the count of numbers ; Every power of 2 contains only 1 set bit ; Driver code | def count ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE p = 1 NEW_LINE while ( p <= n ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE p *= 2 NEW_LINE DEDENT return cnt NEW_LINE DEDENT n = 7 NEW_LINE print ( count ( n ) ) ; NEW_LINE |
Find the K | Function to find the K - th minimum element from an array concatenated M times ; sort the elements in ascending order ; return K 'th Min element present at K-1 index ; Driver Code | def KthMinValAfterMconcatenate ( A , N , M , K ) : NEW_LINE INDENT V = [ ] NEW_LINE for i in range ( 0 , M ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT V . append ( A [ j ] ) NEW_LINE DEDENT DEDENT V . sort ( ) NEW_LINE return V [ K - 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 3 , 1 , 2 ] NEW_LINE M , K = 3 , 4 NEW_LINE N = len ( A ) NEW_LINE print ( KthMinValAfterMconcatenate ( A , N , M , K ) ) NEW_LINE DEDENT |
Sum of all i such that ( 2 ^ i + 1 ) % 3 = 0 where i is in range [ 1 , n ] | Function to return the required sum ; Total odd numbers from 1 to n ; Sum of first n odd numbers ; Driver code | def sumN ( n ) : NEW_LINE INDENT n = ( n + 1 ) // 2 ; NEW_LINE return ( n * n ) ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( sumN ( n ) ) ; NEW_LINE |
Numbers that are not divisible by any number in the range [ 2 , 10 ] | Function to return the count of numbers from 1 to N which are not divisible by any number in the range [ 2 , 10 ] ; Driver code | def countNumbers ( n ) : NEW_LINE INDENT return ( n - n // 2 - n // 3 - n // 5 - n // 7 + n // 6 + n // 10 + n // 14 + n // 15 + n // 21 + n // 35 - n // 30 - n // 42 - n // 70 - n // 105 + n // 210 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 20 NEW_LINE print ( countNumbers ( n ) ) NEW_LINE DEDENT |
Maximum Primes whose sum is equal to given N | Function to find max count of primes ; if n is even n / 2 is required answer if n is odd floor ( n / 2 ) = ( int ) ( n / 2 ) is required answer ; Driver code | def maxPrmimes ( n ) : NEW_LINE INDENT return n // 2 NEW_LINE DEDENT n = 17 NEW_LINE print ( maxPrmimes ( n ) ) NEW_LINE |
Sum of the series ( 1 * 2 ) + ( 2 * 3 ) + ( 3 * 4 ) + ... ... upto n terms | Function to return sum ; Driver code | def Sum ( n ) : NEW_LINE INDENT return n * ( n + 1 ) * ( n + 2 ) // 3 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; NEW_LINE print ( Sum ( n ) ) NEW_LINE DEDENT |
Smallest divisor D of N such that gcd ( D , M ) is greater than 1 | Python3 implementation of the above approach ; Function to find the minimum divisor ; Iterate for all factors of N ; Check for gcd > 1 ; Check for gcd > 1 ; If gcd is m itself ; Drivers code | import math NEW_LINE def findMinimum ( n , m ) : NEW_LINE INDENT mini , i = m , 1 NEW_LINE while i * i <= n : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT sec = n // i NEW_LINE if math . gcd ( m , i ) > 1 : NEW_LINE INDENT return i NEW_LINE DEDENT elif math . gcd ( sec , m ) > 1 : NEW_LINE INDENT mini = min ( sec , mini ) NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT if mini == m : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return mini NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , m = 8 , 10 NEW_LINE print ( findMinimum ( n , m ) ) NEW_LINE DEDENT |
Find Nth term of the series 1 , 5 , 32 , 288 ... | Function to generate a fixed number ; Finding nth term ; Driver code | def nthTerm ( N ) : NEW_LINE INDENT nth = 0 NEW_LINE for i in range ( N , 0 , - 1 ) : NEW_LINE INDENT nth += pow ( i , i ) NEW_LINE DEDENT return nth NEW_LINE DEDENT N = 3 NEW_LINE print ( nthTerm ( N ) ) NEW_LINE |
Find kth smallest number in range [ 1 , n ] when all the odd numbers are deleted | Function to return the kth smallest element from the range [ 1 , n ] after removing all the odd elements ; Driver code | def kthSmallest ( n , k ) : NEW_LINE INDENT return 2 * k NEW_LINE DEDENT n = 8 ; k = 4 NEW_LINE print ( kthSmallest ( n , k ) ) NEW_LINE |
Check if a number can be represented as sum of non zero powers of 2 | Function that return true if n can be represented as the sum of powers of 2 without using 2 ^ 0 ; Driver code | def isSumOfPowersOfTwo ( n ) : NEW_LINE INDENT if n % 2 == 1 : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT n = 10 NEW_LINE if isSumOfPowersOfTwo ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Minimize sum of adjacent difference with removal of one element from array | Function to find the element ; Value variable for storing the total value ; Declaring maximum value as zero ; If array contains on element ; Storing the maximum value in temp variable ; Adding the adjacent difference modulus values of removed element . Removing adjacent difference modulus value after removing element ; Returning total value - maximum value ; Drivers code | def findMinRemoval ( arr , n ) : NEW_LINE INDENT value = 0 NEW_LINE maximum = 0 NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( i != 0 and i != n - 1 ) : NEW_LINE INDENT value = value + abs ( arr [ i ] - arr [ i + 1 ] ) NEW_LINE temp = ( abs ( arr [ i ] - arr [ i + 1 ] ) + abs ( arr [ i ] - arr [ i - 1 ] ) - abs ( arr [ i - 1 ] - arr [ i + 1 ] ) ) NEW_LINE DEDENT elif ( i == 0 ) : NEW_LINE INDENT value = value + abs ( arr [ i ] - arr [ i + 1 ] ) NEW_LINE temp = abs ( arr [ i ] - arr [ i + 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT temp = abs ( arr [ i ] - arr [ i - 1 ] ) NEW_LINE DEDENT maximum = max ( maximum , temp ) NEW_LINE DEDENT return ( value - maximum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 5 , 3 , 2 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMinRemoval ( arr , n ) ) NEW_LINE DEDENT |
Time until distance gets equal to X between two objects moving in opposite direction | Function to return the time for which the two policemen can communicate ; time = distance / speed ; Driver code | def getTime ( u , v , x ) : NEW_LINE INDENT speed = u + v NEW_LINE time = x / speed NEW_LINE return time NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT u , v , x = 3 , 3 , 3 NEW_LINE print ( getTime ( u , v , x ) ) NEW_LINE DEDENT |
Given number of matches played , find number of teams in tournament | Python implementation of the approach ; Function to return the number of teams ; To store both roots of the equation ; sqrt ( b ^ 2 - 4 ac ) ; First root ( - b + sqrt ( b ^ 2 - 4 ac ) ) / 2 a ; Second root ( - b - sqrt ( b ^ 2 - 4 ac ) ) / 2 a ; Return the positive root ; Driver code | import math NEW_LINE def number_of_teams ( M ) : NEW_LINE INDENT N1 , N2 , sqr = 0 , 0 , 0 NEW_LINE sqr = math . sqrt ( 1 + ( 8 * M ) ) NEW_LINE N1 = ( 1 + sqr ) / 2 NEW_LINE N2 = ( 1 - sqr ) / 2 NEW_LINE if ( N1 > 0 ) : NEW_LINE INDENT return int ( N1 ) NEW_LINE DEDENT return int ( N2 ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT M = 45 NEW_LINE print ( number_of_teams ( M ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Greatest number less than equal to B that can be formed from the digits of A | Function to return the greatest number not gtreater than B that can be formed with the digits of A ; To store size of A ; To store the required answer ; Traverse from leftmost digit and place a smaller digit for every position . ; Keep all digits in A ; To avoid leading zeros ; For all possible values at ith position from largest value to smallest ; Take largest possible digit ; Keep duplicate of string a ; Remove the taken digit from s2 ; Sort all the remaining digits of s2 ; Add s2 to current s1 ; If s1 is less than B then it can be included in the answer . Note that int ( ) converts a string to integer ; change A to s2 ; Return the required answer ; Driver Code | def permuteDigits ( a : str , b : int ) -> str : NEW_LINE INDENT n = len ( a ) NEW_LINE ans = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = set ( list ( a ) ) NEW_LINE if i == 0 : NEW_LINE INDENT temp . discard ( 0 ) NEW_LINE DEDENT for j in reversed ( list ( temp ) ) : NEW_LINE INDENT s1 = ans + j NEW_LINE s2 = list ( a ) . copy ( ) NEW_LINE s2 . remove ( j ) NEW_LINE s2 = ' ' . join ( sorted ( list ( s2 ) ) ) NEW_LINE s1 += s2 NEW_LINE if int ( s1 ) <= b : NEW_LINE INDENT ans += j NEW_LINE a = ' ' . join ( list ( s2 ) ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = "123" NEW_LINE b = 222 NEW_LINE print ( permuteDigits ( a , b ) ) NEW_LINE DEDENT |
Sum of numbers from 1 to N which are in Lucas Sequence | Function to return the required Sum ; Generate lucas number and keep on adding them ; Driver code | def LucasSum ( N ) : NEW_LINE INDENT Sum = 0 NEW_LINE a = 2 NEW_LINE b = 1 NEW_LINE c = 0 NEW_LINE Sum += a NEW_LINE while ( b <= N ) : NEW_LINE INDENT Sum += b NEW_LINE c = a + b NEW_LINE a = b NEW_LINE b = c NEW_LINE DEDENT return Sum NEW_LINE DEDENT N = 20 NEW_LINE print ( LucasSum ( N ) ) NEW_LINE |
Count of all even numbers in the range [ L , R ] whose sum of digits is divisible by 3 | Function to return the count of required numbers ; Count of numbers in range which are divisible by 6 ; Driver code | def countNumbers ( l , r ) : NEW_LINE INDENT return ( ( r // 6 ) - ( l - 1 ) // 6 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 1000 ; r = 6000 ; NEW_LINE print ( countNumbers ( l , r ) ) ; NEW_LINE DEDENT |
Sum of minimum element of all sub | Function to find the sum of minimum of all subsequence ; Driver code | def findMinSum ( arr , n ) : NEW_LINE INDENT occ = n - 1 NEW_LINE Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum += arr [ i ] * pow ( 2 , occ ) NEW_LINE occ -= 1 NEW_LINE DEDENT return Sum NEW_LINE DEDENT arr = [ 1 , 2 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMinSum ( arr , n ) ) NEW_LINE |
Number of trailing zeroes in base B representation of N ! | Python 3 program to find the number of trailing zeroes in base B representation of N ! ; To find the power of a prime p in factorial N ; calculating floor ( n / r ) and adding to the count ; increasing the power of p from 1 to 2 to 3 and so on ; returns all the prime factors of k ; vector to store all the prime factors along with their number of occurrence in factorization of B ; Returns largest power of B that divides N ! ; calculating minimum power of all the prime factors of B ; Driver code | import sys NEW_LINE def findPowerOfP ( N , p ) : NEW_LINE INDENT count = 0 NEW_LINE r = p NEW_LINE while ( r <= N ) : NEW_LINE INDENT count += int ( N / r ) NEW_LINE r = r * p NEW_LINE DEDENT return count NEW_LINE DEDENT def primeFactorsofB ( B ) : NEW_LINE ' NEW_LINE INDENT ans = [ ] NEW_LINE i = 2 NEW_LINE while ( B != 1 ) : NEW_LINE INDENT if ( B % i == 0 ) : NEW_LINE INDENT count = 0 NEW_LINE while ( B % i == 0 ) : NEW_LINE INDENT B = int ( B / i ) NEW_LINE count += 1 NEW_LINE DEDENT ans . append ( ( i , count ) ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def largestPowerOfB ( N , B ) : NEW_LINE INDENT vec = [ ] NEW_LINE vec = primeFactorsofB ( B ) NEW_LINE ans = sys . maxsize NEW_LINE ans = min ( ans , int ( findPowerOfP ( N , vec [ 0 ] [ 0 ] ) / vec [ 0 ] [ 1 ] ) ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( largestPowerOfB ( 5 , 2 ) ) NEW_LINE print ( largestPowerOfB ( 6 , 9 ) ) NEW_LINE DEDENT |
Count numbers in range 1 to N which are divisible by X but not by Y | Function to count total numbers divisible by x but not y in range 1 to N ; Check if Number is divisible by x but not Y if yes , Increment count ; Driver Code | def countNumbers ( X , Y , N ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( ( i % X == 0 ) and ( i % Y != 0 ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT X = 2 ; NEW_LINE Y = 3 ; NEW_LINE N = 10 ; NEW_LINE print ( countNumbers ( X , Y , N ) ) ; NEW_LINE |
Position of a person diametrically opposite on a circle | Function to return the required position ; Driver code | def getPosition ( n , m ) : NEW_LINE INDENT if ( m > ( n // 2 ) ) : NEW_LINE INDENT return ( m - ( n // 2 ) ) NEW_LINE DEDENT return ( m + ( n // 2 ) ) NEW_LINE DEDENT n = 8 NEW_LINE m = 5 NEW_LINE print ( getPosition ( n , m ) ) NEW_LINE |
Minimum operations required to modify the array such that parity of adjacent elements is different | Function to return the parity of a number ; Function to return the minimum number of operations required ; Operation needs to be performed ; Parity of previous element ; Parity of next element ; Update parity of current element to be other than the parities of the previous and the next number ; Driver Code | def parity ( a ) : NEW_LINE INDENT return a % 3 NEW_LINE DEDENT def solve ( array , size ) : NEW_LINE INDENT operations = 0 NEW_LINE for i in range ( 0 , size - 1 ) : NEW_LINE INDENT if parity ( array [ i ] ) == parity ( array [ i + 1 ] ) : NEW_LINE INDENT operations += 1 NEW_LINE if i + 2 < size : NEW_LINE INDENT pari1 = parity ( array [ i ] ) NEW_LINE pari2 = parity ( array [ i + 2 ] ) NEW_LINE if pari1 == pari2 : NEW_LINE INDENT if pari1 == 0 : NEW_LINE INDENT array [ i + 1 ] = 1 NEW_LINE DEDENT elif pari1 == 1 : NEW_LINE INDENT array [ i + 1 ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT array [ i + 1 ] = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( ( pari1 == 0 and pari2 == 1 ) or ( pari1 == 1 and pari2 == 0 ) ) : NEW_LINE INDENT array [ i + 1 ] = 2 NEW_LINE DEDENT if ( ( pari1 == 1 and pari2 == 2 ) or ( pari1 == 2 and pari2 == 1 ) ) : NEW_LINE INDENT array [ i + 1 ] = 0 NEW_LINE DEDENT if ( ( pari1 == 2 and pari2 == 0 ) and ( pari1 == 0 and pari2 == 2 ) ) : NEW_LINE INDENT array [ i + 1 ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return operations NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT array = [ 2 , 1 , 3 , 0 ] NEW_LINE size = len ( array ) NEW_LINE print ( solve ( array , size ) ) NEW_LINE DEDENT |
Number of submatrices with OR value 1 | Function to find required prefix - count for each row from right to left ; Function to find the count of submatrices with OR value 1 ; Array to store prefix count of zeros from right to left for boolean array ; Variable to store the count of submatrices with OR value 0 ; Loop to evaluate each column of the prefix matrix uniquely . For each index of a column we will try to determine the number of sub - matrices starting from that index and has all 1 s ; First part of pair will be the value of inserted element . Second part will be the count of the number of elements pushed before with a greater value ; Variable to store the number of submatrices with all 0 s ; Return the final answer ; Driver Code | def findPrefixCount ( p_arr , arr ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if arr [ i ] [ j ] : NEW_LINE INDENT continue NEW_LINE DEDENT if j != n - 1 : NEW_LINE INDENT p_arr [ i ] [ j ] += p_arr [ i ] [ j + 1 ] NEW_LINE DEDENT p_arr [ i ] [ j ] += int ( not arr [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT def matrixOrValueOne ( arr ) : NEW_LINE INDENT p_arr = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE findPrefixCount ( p_arr , arr ) NEW_LINE count_zero_submatrices = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT i = n - 1 NEW_LINE q = [ ] NEW_LINE to_sum = 0 NEW_LINE while i >= 0 : NEW_LINE INDENT c = 0 NEW_LINE while ( len ( q ) != 0 and q [ - 1 ] [ 0 ] > p_arr [ i ] [ j ] ) : NEW_LINE INDENT to_sum -= ( ( q [ - 1 ] [ 1 ] + 1 ) * ( q [ - 1 ] [ 0 ] - p_arr [ i ] [ j ] ) ) NEW_LINE c += q . pop ( ) [ 1 ] + 1 NEW_LINE DEDENT to_sum += p_arr [ i ] [ j ] NEW_LINE count_zero_submatrices += to_sum NEW_LINE q . append ( ( p_arr [ i ] [ j ] , c ) ) NEW_LINE i -= 1 NEW_LINE DEDENT DEDENT return ( ( n * ( n + 1 ) * n * ( n + 1 ) ) // 4 - count_zero_submatrices ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE arr = [ [ 0 , 0 , 0 ] , [ 0 , 1 , 0 ] , [ 0 , 0 , 0 ] ] NEW_LINE print ( matrixOrValueOne ( arr ) ) NEW_LINE DEDENT |
XOR of XORs of all sub | Function to find to required XOR value ; Nested loop to find the number of sub - matrix each index belongs to ; Number of ways to choose from top - left elements ; Number of ways to choose from bottom - right elements ; Driver code | def submatrixXor ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT top_left = ( i + 1 ) * ( j + 1 ) NEW_LINE bottom_right = ( n - i ) * ( n - j ) NEW_LINE if ( top_left % 2 == 1 and bottom_right % 2 == 1 ) : NEW_LINE INDENT ans = ( ans ^ arr [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT n = 3 NEW_LINE arr = [ [ 6 , 7 , 13 ] , [ 8 , 3 , 4 ] , [ 9 , 7 , 6 ] ] NEW_LINE print ( submatrixXor ( arr , n ) ) NEW_LINE |
Find Nth positive number whose digital root is X | Python3 program to find the N - th number whose digital root is X ; Function to find the digital root of a number ; Function to find the Nth number with digital root as X ; Counter variable to keep the count of valid numbers ; Find digital root ; Check if is required answer or not ; Print the answer if you have found it and breakout of the loop ; Driver Code | import sys NEW_LINE def findDigitalRoot ( num ) : NEW_LINE INDENT sum = sys . maxsize ; NEW_LINE tempNum = num ; NEW_LINE while ( sum >= 10 ) : NEW_LINE INDENT sum = 0 ; NEW_LINE while ( tempNum > 0 ) : NEW_LINE INDENT sum += tempNum % 10 ; NEW_LINE tempNum //= 10 ; NEW_LINE DEDENT tempNum = sum ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def findAnswer ( X , N ) : NEW_LINE INDENT counter = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( counter < N ) : NEW_LINE INDENT i += 1 ; NEW_LINE digitalRoot = findDigitalRoot ( i ) ; NEW_LINE if ( digitalRoot == X ) : NEW_LINE INDENT counter += 1 ; NEW_LINE DEDENT if ( counter == N ) : NEW_LINE INDENT print ( i ) ; NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 1 ; NEW_LINE N = 3 ; NEW_LINE findAnswer ( X , N ) ; NEW_LINE DEDENT |
Find Nth positive number whose digital root is X | Function to find the N - th number with digital root as X ; Driver Code | def findAnswer ( X , N ) : NEW_LINE INDENT return ( N - 1 ) * 9 + X ; NEW_LINE DEDENT X = 7 ; NEW_LINE N = 43 ; NEW_LINE print ( findAnswer ( X , N ) ) ; NEW_LINE |
Sum of the natural numbers ( up to N ) whose modulo with K yield R | Function to return the sum ; If current number gives R as the remainder on dividing by K ; Update the sum ; Return the sum ; Driver code | def count ( N , K , R ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i % K == R ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 20 NEW_LINE K = 4 NEW_LINE R = 3 NEW_LINE print ( count ( N , K , R ) ) NEW_LINE DEDENT |
Longest sub | Function to return the length of the longest required sub - sequence ; Find the maximum element from the array ; Insert all lucas numbers below max to the set a and b are first two elements of the Lucas sequence ; If current element is a Lucas number , increment count ; Return the count ; Driver code | def LucasSequence ( arr , n ) : NEW_LINE INDENT max = arr [ 0 ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] > max ) : NEW_LINE INDENT max = arr [ i ] NEW_LINE DEDENT DEDENT s = set ( ) NEW_LINE a = 2 NEW_LINE b = 1 NEW_LINE s . add ( a ) NEW_LINE s . add ( b ) NEW_LINE while ( b < max ) : NEW_LINE INDENT c = a + b NEW_LINE a = b NEW_LINE b = c NEW_LINE s . add ( b ) NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] in s ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 11 , 22 , 4 , 2 , 1 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( LucasSequence ( arr , n ) ) NEW_LINE DEDENT |
Find the number of solutions to the given equation | Function to return the count of valid values of X ; Iterate through all possible sum of digits of X ; Get current value of X for sum of digits i ; Find sum of digits of cr ; If cr is a valid choice for X ; Return the count ; Driver code | def getCount ( a , b , c ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , 82 ) : NEW_LINE INDENT cr = b * pow ( i , a ) + c NEW_LINE tmp = cr NEW_LINE sm = 0 NEW_LINE while ( tmp ) : NEW_LINE INDENT sm += tmp % 10 NEW_LINE tmp //= 10 NEW_LINE DEDENT if ( sm == i and cr < 10 ** 9 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT a , b , c = 3 , 2 , 8 NEW_LINE print ( getCount ( a , b , c ) ) NEW_LINE |
Check if an array of 1 s and 2 s can be divided into 2 parts with equal sum | Function to check if it is possible to split the array in two halfs with equal Sum ; Calculate Sum of elements and count of 1 's ; If total Sum is odd , return False ; If Sum of each half is even , return True ; If Sum of each half is even but there is atleast one 1 ; Driver Code | def isSpiltPossible ( n , a ) : NEW_LINE INDENT Sum = 0 NEW_LINE c1 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum += a [ i ] NEW_LINE if ( a [ i ] == 1 ) : NEW_LINE INDENT c1 += 1 NEW_LINE DEDENT DEDENT if ( Sum % 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( ( Sum // 2 ) % 2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( c1 > 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = 3 NEW_LINE a = [ 1 , 1 , 2 ] NEW_LINE if ( isSpiltPossible ( n , a ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Subsets and Splits