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 = ...
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 ...
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 D...
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 ...
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...
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...
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 , ...
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 " ...
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 sm...
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 ( ...
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 o...
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 ...
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 =...
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 item...
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 ( or...
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 =...
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 s...
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_e...
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...
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...
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 ; ...
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 c...
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...
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 NE...
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 d...
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 ) : N...
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 ; Co...
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 ] [...
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 answe...
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 ]...
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 numbe...
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 + le...
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 ...
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 DE...
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 IN...
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 ) )...
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...
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 Binom...
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 DEDEN...
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...
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 = i...
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 m...
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 ...
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 ; Func...
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 coun...
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 ; T...
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 ...
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...
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 = ...
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 len...
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...
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 R...
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 ...
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 __na...
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_...
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__ == ...
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 )...
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...
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 ; radiu...
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...
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 -...
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...
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_L...
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 )...
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_LIN...
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 o...
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 ...
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 ...
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...
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 cod...
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...
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 ;...
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 ...
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 ...
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...
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 ; Ext...
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 ...
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 (...
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 = [ ...
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 ...
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_LIN...
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 ...
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_LIN...
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 INDE...
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...
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 , ...
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 ...
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 ] - ar...
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 ; Retu...
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 ( ) : ...
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 d...
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_LIN...
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 th...
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 ...
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 ...
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...
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 pari...
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 ...
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...
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 ^...
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 a...
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 retur...
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 ,...
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 ) : N...
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 += ...
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 bu...
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 INDEN...