text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Program to find if two numbers and their AM and HM are present in an array using STL | Python3 program to check if two numbers are present in an array then their AM and HM are also present . Finally , find the GM of the numbers ; Function to find the arithmetic mean of 2 numbers ; Function to find the harmonic mean of 2 numbers ; Following function checks and computes the desired results based on the means ; Calculate means ; Hash container ( set ) to store elements ; Insertion of array elements in the set ; Conditionals to check if numbers are present in array by Hashing ; Conditionals to check if the AM and HM of the numbers are present in array ; If all conditions are satisfied , the Geometric Mean is calculated ; If numbers are found but the respective AM and HM are not found in the array ; If none of the conditions are satisfied ; Driver Code
from math import sqrt NEW_LINE def ArithmeticMean ( A , B ) : NEW_LINE INDENT return ( A + B ) / 2 NEW_LINE DEDENT def HarmonicMean ( A , B ) : NEW_LINE INDENT return ( 2 * A * B ) / ( A + B ) NEW_LINE DEDENT def CheckArithmeticHarmonic ( arr , A , B , N ) : NEW_LINE INDENT AM = ArithmeticMean ( A , B ) NEW_LINE HM = HarmonicMean ( A , B ) NEW_LINE Hash = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT Hash . add ( arr [ i ] ) NEW_LINE DEDENT if ( A in Hash and B in Hash ) : NEW_LINE INDENT if ( AM in Hash and HM in Hash ) : NEW_LINE INDENT print ( " GM ▁ = " , round ( sqrt ( AM * HM ) , 2 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " AM ▁ and ▁ HM ▁ not ▁ found " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " Numbers ▁ not ▁ found " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1.0 , 2.0 , 2.5 , 3.0 , 4.0 , 4.5 , 5.0 , 6.0 ] NEW_LINE N = len ( arr ) NEW_LINE A = 3.0 NEW_LINE B = 6.0 NEW_LINE CheckArithmeticHarmonic ( arr , A , B , N ) NEW_LINE DEDENT
Minimum decrements to make integer A divisible by integer B | Function that print number of moves required ; Calculate modulo ; Print the required answer ; Driver Code ; Initialise A and B
def movesRequired ( a , b ) : NEW_LINE INDENT total_moves = a % b NEW_LINE print ( total_moves ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 10 NEW_LINE B = 3 NEW_LINE movesRequired ( A , B ) NEW_LINE DEDENT
Pythagorean Triplet with given sum using single loop | Function to calculate the Pythagorean triplet in O ( n ) ; Iterate a from 1 to N - 1. ; Calculate value of b ; The value of c = n - a - b ; Driver code ; Function call
def PythagoreanTriplet ( n ) : NEW_LINE INDENT flag = 0 NEW_LINE for a in range ( 1 , n , 1 ) : NEW_LINE INDENT b = ( n * n - 2 * n * a ) // ( 2 * n - 2 * a ) NEW_LINE c = n - a - b NEW_LINE if ( a * a + b * b == c * c and b > 0 and c > 0 ) : NEW_LINE INDENT print ( a , b , c ) NEW_LINE flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE PythagoreanTriplet ( N ) NEW_LINE DEDENT
Check if there exists a number with X factors out of which exactly K are prime | Python3 program to check if there exists a number with X factors out of which exactly K are prime ; Function to check if such number exists ; To store the sum of powers of prime factors of X which determines the maximum count of numbers whose product can form X ; Determining the prime factors of X ; To check if the number is prime ; If X is 1 , then we cannot form a number with 1 factor and K prime factor ( as K is atleast 1 ) ; If X itself is prime then it can be represented as a power of only 1 prime factor w0hich is X itself so we return true ; If sum of the powers of prime factors of X is greater than or equal to K , which means X can be represented as a product of K numbers , we return true ; In any other case , we return false as we cannot form a number with X factors and K prime factors ; Driver code
from math import sqrt NEW_LINE def check ( X , K ) : NEW_LINE INDENT prime = 0 NEW_LINE temp = X NEW_LINE sqr = int ( sqrt ( X ) ) NEW_LINE for i in range ( 2 , sqr + 1 , 1 ) : NEW_LINE INDENT while ( temp % i == 0 ) : NEW_LINE INDENT temp = temp // i NEW_LINE prime += 1 NEW_LINE DEDENT DEDENT if ( temp > 2 ) : NEW_LINE INDENT prime += 1 NEW_LINE DEDENT if ( X == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( prime == 1 and K == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( prime >= K ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 4 NEW_LINE K = 2 NEW_LINE if ( check ( X , K ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Print all Coprime path of a Binary Tree | A Tree node ; Utility function to create a new node ; Vector to store all the prime numbers ; Function to store all the prime numbers in an array ; Create a boolean array " prime [ 0 . . N ] " and initialize all the entries in it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiples of p and are less than p ^ 2 are already marked . ; Function to check whether Path is Co - prime or not ; Iterating through the array to find the maximum element in the array ; Incrementing the variable if any of the value has a factor ; If not co - prime ; Function to print a Co - Prime path ; Function to find co - prime paths of binary tree ; Base case ; Store the value in path vector ; Recursively call for left sub tree ; Recursively call for right sub tree ; Condition to check , if leaf node ; Condition to check , if path co - prime or not ; Print co - prime path ; Remove the last element from the path vector ; Function to find Co - Prime paths In a given binary tree ; To save all prime numbers ; Function call ; Driver code ; Create Binary Tree as shown ; Print Co - Prime Paths
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE return temp NEW_LINE DEDENT N = 1000000 NEW_LINE prime = [ ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT check = [ True for i in range ( N + 1 ) ] NEW_LINE p = 2 NEW_LINE while ( p * p <= N ) : NEW_LINE INDENT if ( check [ p ] ) : NEW_LINE INDENT prime . append ( p ) NEW_LINE for i in range ( p * p , N + 1 , p ) : NEW_LINE INDENT check [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def isPathCo_Prime ( path ) : NEW_LINE INDENT max = 0 NEW_LINE for x in path : NEW_LINE INDENT if ( max < x ) : NEW_LINE INDENT max = x NEW_LINE DEDENT DEDENT i = 0 NEW_LINE while ( i * prime [ i ] <= max // 2 ) : NEW_LINE INDENT ct = 0 NEW_LINE for x in path : NEW_LINE INDENT if ( x % prime [ i ] == 0 ) : NEW_LINE INDENT ct += 1 NEW_LINE DEDENT DEDENT if ( ct > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def printCo_PrimePaths ( path ) : NEW_LINE INDENT for x in path : NEW_LINE INDENT print ( x , end = ' ▁ ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def findCo_PrimePaths ( root , path ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return path NEW_LINE DEDENT path . append ( root . key ) NEW_LINE path = findCo_PrimePaths ( root . left , path ) NEW_LINE path = findCo_PrimePaths ( root . right , path ) NEW_LINE if ( root . left == None and root . right == None ) : NEW_LINE INDENT if ( isPathCo_Prime ( path ) ) : NEW_LINE INDENT printCo_PrimePaths ( path ) NEW_LINE DEDENT DEDENT path . pop ( ) NEW_LINE return path NEW_LINE DEDENT def printCo_PrimePath ( node ) : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE path = [ ] NEW_LINE path = findCo_PrimePaths ( node , path ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 48 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 11 ) NEW_LINE root . right . right = newNode ( 37 ) NEW_LINE root . right . left . left = newNode ( 7 ) NEW_LINE root . right . left . right = newNode ( 29 ) NEW_LINE root . right . right . left = newNode ( 42 ) NEW_LINE root . right . right . right = newNode ( 19 ) NEW_LINE root . right . right . right . left = newNode ( 7 ) NEW_LINE printCo_PrimePath ( root ) NEW_LINE DEDENT
Number of subsets with same AND , OR and XOR values in an Array | Python3 implementation to find the number of subsets with equal bitwise AND , OR and XOR values ; Function to find the number of subsets with equal bitwise AND , OR and XOR values ; Traverse through all the subsets ; Finding the subsets with the bits of ' i ' which are set ; Computing the bitwise AND ; Computing the bitwise OR ; Computing the bitwise XOR ; Comparing all the three values ; Driver code
mod = 1000000007 ; NEW_LINE def countSubsets ( a , n ) : NEW_LINE INDENT answer = 0 ; NEW_LINE for i in range ( 1 << n ) : NEW_LINE INDENT bitwiseAND = - 1 ; NEW_LINE bitwiseOR = 0 ; NEW_LINE bitwiseXOR = 0 ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( i & ( 1 << j ) ) : NEW_LINE INDENT if ( bitwiseAND == - 1 ) : NEW_LINE INDENT bitwiseAND = a [ j ] ; NEW_LINE DEDENT else : NEW_LINE INDENT bitwiseAND &= a [ j ] ; NEW_LINE DEDENT bitwiseOR |= a [ j ] ; NEW_LINE bitwiseXOR ^= a [ j ] ; NEW_LINE DEDENT DEDENT if ( bitwiseAND == bitwiseOR and bitwiseOR == bitwiseXOR ) : NEW_LINE INDENT answer = ( answer + 1 ) % mod ; NEW_LINE DEDENT DEDENT return answer ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 ; NEW_LINE A = [ 1 , 3 , 2 , 1 , 2 , 1 ] ; NEW_LINE print ( countSubsets ( A , N ) ) ; NEW_LINE DEDENT
Count of Subsets containing only the given value K | Function to find the number of subsets formed by the given value K ; Count is used to maintain the number of continuous K 's ; Iterating through the array ; If the element in the array is equal to K ; count * ( count + 1 ) / 2 is the total number of subsets with only K as their element ; Change count to 0 because other element apart from K has been found ; To handle the last set of K 's ; Driver code
def count ( arr , N , K ) : NEW_LINE INDENT count = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == K ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( count * ( count + 1 ) ) // 2 NEW_LINE count = 0 NEW_LINE DEDENT DEDENT ans = ans + ( count * ( count + 1 ) ) // 2 NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 0 , 1 , 1 , 0 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE K = 0 NEW_LINE print ( count ( arr , N , K ) ) NEW_LINE DEDENT
Ternary number system or Base 3 numbers | Function to convert a decimal number to a ternary number ; Base case ; Finding the remainder when N is divided by 3 ; Recursive function to call the function for the integer division of the value N / 3 ; Handling the negative cases ; Function to convert the decimal to ternary ; If the number is greater than 0 , compute the ternary representation of the number ; Driver Code
def convertToTernary ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT x = N % 3 ; NEW_LINE N //= 3 ; NEW_LINE if ( x < 0 ) : NEW_LINE INDENT N += 1 ; NEW_LINE DEDENT convertToTernary ( N ) ; NEW_LINE if ( x < 0 ) : NEW_LINE INDENT print ( x + ( 3 * - 1 ) , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( x , end = " " ) ; NEW_LINE DEDENT DEDENT def convert ( Decimal ) : NEW_LINE INDENT print ( " Ternary ▁ number ▁ of ▁ " , Decimal , " ▁ is : ▁ " , end = " " ) ; NEW_LINE if ( Decimal != 0 ) : NEW_LINE INDENT convertToTernary ( Decimal ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( "0" , end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Decimal = 2747 ; NEW_LINE convert ( Decimal ) ; NEW_LINE DEDENT
Largest number less than or equal to Z that leaves a remainder X when divided by Y | Function to get the number ; remainder can ' t ▁ be ▁ larger ▁ ▁ than ▁ the ▁ largest ▁ number , ▁ ▁ if ▁ so ▁ then ▁ answer ▁ doesn ' t exist . ; reduce number by x ; finding the possible number that is divisible by y ; this number is always <= x as we calculated over z - x ; initialise the three integers
def get ( x , y , z ) : NEW_LINE INDENT if ( x > z ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT val = z - x NEW_LINE div = ( z - x ) // y NEW_LINE ans = div * y + x NEW_LINE return ans NEW_LINE DEDENT x = 1 NEW_LINE y = 5 NEW_LINE z = 8 NEW_LINE print ( get ( x , y , z ) ) NEW_LINE
Count of greater elements for each element in the Array | Python 3 implementation of the above approach ; Store the frequency of the array elements ; Store the sum of frequency of elements greater than the current element ; Driver code
def countOfGreaterElements ( arr , n ) : NEW_LINE INDENT mp = { i : 0 for i in range ( 1000 ) } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT x = 0 NEW_LINE p = [ ] NEW_LINE q = [ ] NEW_LINE m = [ ] NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT m . append ( [ key , value ] ) NEW_LINE DEDENT m = m [ : : - 1 ] NEW_LINE for p in m : NEW_LINE INDENT temp = p [ 1 ] NEW_LINE mp [ p [ 0 ] ] = x NEW_LINE x += temp NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( mp [ arr [ i ] ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 9 , 5 , 2 , 1 , 3 , 4 , 8 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE countOfGreaterElements ( arr , n ) NEW_LINE DEDENT
Minimum operations required to make two numbers equal | Python program to find minimum operations required to make two numbers equal ; Function to return the minimum operations required ; Keeping B always greater ; Reduce B such that gcd ( A , B ) becomes 1. ; Driver code
import math NEW_LINE def minOperations ( A , B ) : NEW_LINE INDENT if ( A > B ) : NEW_LINE INDENT swap ( A , B ) NEW_LINE DEDENT B = B // math . gcd ( A , B ) ; NEW_LINE return B - 1 NEW_LINE DEDENT A = 7 NEW_LINE B = 15 NEW_LINE print ( minOperations ( A , B ) ) NEW_LINE
Program to determine the Quadrant of a Complex number | Function to determine the quadrant of a complex number ; Storing the index of '+ ; Storing the index of '- ; Finding the real part of the complex number ; Finding the imaginary part of the complex number ; Driver code
def quadrant ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE DEDENT ' NEW_LINE INDENT if ( ' + ' in s ) : NEW_LINE INDENT i = s . index ( ' + ' ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT else : NEW_LINE INDENT i = s . index ( ' - ' ) NEW_LINE DEDENT real = s [ 0 : i ] NEW_LINE imaginary = s [ i + 1 : l - 1 ] NEW_LINE x = int ( real ) NEW_LINE y = int ( imaginary ) NEW_LINE if ( x > 0 and y > 0 ) : NEW_LINE INDENT print ( " Quadrant ▁ 1" ) NEW_LINE DEDENT elif ( x < 0 and y > 0 ) : NEW_LINE INDENT print ( " Quadrant ▁ 2" ) NEW_LINE DEDENT elif ( x < 0 and y < 0 ) : NEW_LINE INDENT print ( " Quadrant ▁ 3" ) NEW_LINE DEDENT elif ( x > 0 and y < 0 ) : NEW_LINE INDENT print ( " Quadrant ▁ 4" ) NEW_LINE DEDENT elif ( x == 0 and y > 0 ) : NEW_LINE INDENT print ( " Lies ▁ on ▁ positive " , " Imaginary ▁ axis " ) NEW_LINE DEDENT elif ( x == 0 and y < 0 ) : NEW_LINE INDENT print ( " Lies ▁ on ▁ negative " , " Imaginary ▁ axis " ) NEW_LINE DEDENT elif ( y == 0 and x < 0 ) : NEW_LINE INDENT print ( " Lies ▁ on ▁ negative " , " X - axis " ) NEW_LINE DEDENT elif ( y == 0 and x > 0 ) : NEW_LINE INDENT print ( " Lies ▁ on ▁ positive " , " X - axis " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Lies ▁ on ▁ the ▁ Origin " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "5 + 3i " NEW_LINE quadrant ( s ) NEW_LINE DEDENT
Sum and Product of all Fibonacci Nodes of a Singly Linked List | Python3 implementation to find the sum and product of all of the Fibonacci nodes in a singly linked list ; Node of the singly linked list ; Function to insert a node at the beginning of the singly Linked List ; Allocate new node ; Link the old list to the new node ; Move the head to point the new node ; Function that returns the largest element from the linked list . ; Declare a max variable and initialize with INT_MIN ; Check loop while head not equal to NULL ; If max is less then head -> data then assign value of head -> data to max otherwise node points to next node . ; Function to create a hash table to check Fibonacci numbers ; Inserting the first two numbers in the hash ; Loop to add Fibonacci numbers upto the maximum element present in the linked list ; Function to find the required sum and product ; Find the largest node value in Singly Linked List ; Creating a set containing all the fibonacci numbers upto the maximum data value in the Singly Linked List ; Traverse the linked list ; If current node is fibonacci ; Find the sum and the product ; Driver code ; Create the linked list 15 -> 16 -> 8 -> 6 -> 13
import sys NEW_LINE class Node ( ) : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def largestElement ( head_ref ) : NEW_LINE INDENT max = - sys . maxsize NEW_LINE head = head_ref NEW_LINE while ( head != None ) : NEW_LINE INDENT if ( max < head . data ) : NEW_LINE INDENT max = head . data NEW_LINE DEDENT head = head . next NEW_LINE DEDENT return max NEW_LINE DEDENT def createHash ( hash , maxElement ) : NEW_LINE INDENT prev = 0 NEW_LINE curr = 1 NEW_LINE hash . add ( prev ) NEW_LINE hash . add ( curr ) NEW_LINE while ( curr <= maxElement ) : NEW_LINE INDENT temp = curr + prev NEW_LINE hash . add ( temp ) NEW_LINE prev = curr NEW_LINE curr = temp NEW_LINE DEDENT return hash NEW_LINE DEDENT def sumAndProduct ( head_ref ) : NEW_LINE INDENT maxEle = largestElement ( head_ref ) NEW_LINE hash = set ( ) NEW_LINE hash = createHash ( hash , maxEle ) NEW_LINE prod = 1 NEW_LINE sum = 0 NEW_LINE ptr = head_ref NEW_LINE while ( ptr != None ) : NEW_LINE INDENT if ptr . data in hash : NEW_LINE INDENT prod *= ptr . data NEW_LINE sum += ptr . data NEW_LINE DEDENT ptr = ptr . next NEW_LINE DEDENT print ( " Sum ▁ = " , sum ) NEW_LINE print ( " Product ▁ = " , prod ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT head = None ; NEW_LINE head = push ( head , 13 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 16 ) NEW_LINE head = push ( head , 15 ) NEW_LINE sumAndProduct ( head ) NEW_LINE DEDENT
Product of all Subarrays of an Array | Function to find product of all subarrays ; Variable to store the product ; Compute the product while traversing for subarrays ; Printing product of all subarray ; Driver code ; Function call
def product_subarrays ( arr , n ) : NEW_LINE INDENT product = 1 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT for k in range ( i , j + 1 ) : NEW_LINE INDENT product *= arr [ k ] ; NEW_LINE DEDENT DEDENT DEDENT print ( product , " " ) ; NEW_LINE DEDENT arr = [ 10 , 3 , 7 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE product_subarrays ( arr , n ) ; NEW_LINE
Check if a N base number is Even or Odd | To return value of a char . ; Function to convert a number from N base to decimal ; power of base ; Decimal equivaLent is str [ Len - 1 ] * 1 + str [ Len - 1 ] * base + str [ Len - 1 ] * ( base ^ 2 ) + ... ; A digit in input number must be less than number 's base ; Returns true if n is even , else odd ; Driver code
def val ( c ) : NEW_LINE INDENT if ( ord ( c ) >= ord ( '0' ) and ord ( c ) <= ord ( '9' ) ) : NEW_LINE INDENT return ord ( c ) - ord ( '0' ) NEW_LINE DEDENT else : NEW_LINE INDENT return ord ( c ) - ord ( ' A ' ) + 10 NEW_LINE DEDENT DEDENT def toDeci ( str , base ) : NEW_LINE INDENT Len = len ( str ) NEW_LINE power = 1 NEW_LINE num = 0 NEW_LINE for i in range ( Len - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( val ( str [ i ] ) >= base ) : NEW_LINE INDENT print ( " Invalid ▁ Number " ) NEW_LINE return - 1 NEW_LINE DEDENT num += val ( str [ i ] ) * power NEW_LINE power = power * base NEW_LINE DEDENT return num NEW_LINE DEDENT def isEven ( num , N ) : NEW_LINE INDENT deci = toDeci ( num , N ) NEW_LINE return ( deci % 2 == 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num = "11A " NEW_LINE N = 16 NEW_LINE if ( isEven ( num , N ) ) : NEW_LINE INDENT print ( " Even " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Odd " ) NEW_LINE DEDENT DEDENT
Find the next Factorial greater than N | Array that stores the factorial till 20 ; Function to pre - compute the factorial till 20 ; Precomputing factorials ; Function to return the next factorial number greater than N ; Traverse the factorial array ; Find the next just greater factorial than N ; Function to precalculate the factorial till 20 ; Function call
fact = [ 0 ] * 21 NEW_LINE def preCompute ( ) : NEW_LINE INDENT fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , 18 ) : NEW_LINE INDENT fact [ i ] = ( fact [ i - 1 ] * i ) NEW_LINE DEDENT DEDENT def nextFactorial ( N ) : NEW_LINE INDENT for i in range ( 21 ) : NEW_LINE INDENT if N < fact [ i ] : NEW_LINE INDENT print ( fact [ i ] ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT preCompute ( ) NEW_LINE N = 120 NEW_LINE nextFactorial ( N ) NEW_LINE
Find K distinct positive odd integers with sum N | Function to find K odd positive integers such that their summ is N ; Condition to check if there are enough values to check ; Driver Code
def findDistinctOddsumm ( n , k ) : NEW_LINE INDENT if ( ( k * k ) <= n and ( n + k ) % 2 == 0 ) : NEW_LINE INDENT val = 1 NEW_LINE summ = 0 NEW_LINE for i in range ( 1 , k ) : NEW_LINE INDENT print ( val , end = " ▁ " ) NEW_LINE summ += val NEW_LINE val += 2 NEW_LINE DEDENT print ( n - summ ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT n = 100 NEW_LINE k = 4 NEW_LINE findDistinctOddsumm ( n , k ) NEW_LINE
Minimum number of operations to convert array A to array B by adding an integer into a subarray | Function to find the minimum number of operations in which array A can be converted to array B ; Loop to iterate over the array ; if both elements are equal then move to next element ; Calculate the difference between two elements ; loop while the next pair of elements have same difference ; Increase the number of operations by 1 ; Print the number of operations required ; Driver Code
def checkArray ( a , b , n ) : NEW_LINE INDENT operations = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( a [ i ] - b [ i ] == 0 ) : NEW_LINE INDENT i += 1 ; NEW_LINE continue ; NEW_LINE DEDENT diff = a [ i ] - b [ i ] ; NEW_LINE i += 1 ; NEW_LINE while ( i < n and a [ i ] - b [ i ] == diff ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT operations += 1 ; NEW_LINE DEDENT print ( operations ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 3 , 7 , 1 , 4 , 1 , 2 ] ; NEW_LINE b = [ 3 , 7 , 3 , 6 , 3 , 2 ] ; NEW_LINE size = len ( a ) ; NEW_LINE checkArray ( a , b , size ) ; NEW_LINE DEDENT
Perfect Cube | Python3 program to check if a number is a perfect cube using prime factors ; Inserts the prime factor in HashMap if not present if present updates it 's frequency ; A utility function to find all prime factors of a given number N ; Insert the number of 2 s that divide n ; n must be odd at this point So we can skip one element ; while i divides n , insert i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Function to check if a number is perfect cube ; Iteration in Map ; Driver Code ; Function to check if N is perfect cube or not
import math NEW_LINE def insertPF ( primeFact , fact ) : NEW_LINE INDENT if ( fact in primeFact ) : NEW_LINE INDENT primeFact [ fact ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT primeFact [ fact ] = 1 NEW_LINE DEDENT return primeFact NEW_LINE DEDENT def primeFactors ( n ) : NEW_LINE INDENT primeFact = { } NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT primeFact = insertPF ( primeFact , 2 ) NEW_LINE n = n // 2 NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT primeFact = insertPF ( primeFact , i ) NEW_LINE n = n // i NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT primeFact = insertPF ( primeFact , n ) NEW_LINE DEDENT return primeFact NEW_LINE DEDENT def perfectCube ( n ) : NEW_LINE INDENT primeFact = { } NEW_LINE primeFact = primeFactors ( n ) NEW_LINE for x in primeFact : NEW_LINE INDENT if ( primeFact [ x ] % 3 != 0 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT return " Yes " NEW_LINE DEDENT N = 216 NEW_LINE print ( perfectCube ( N ) ) NEW_LINE
Count ways to reach the Nth stair using multiple 1 or 2 steps and a single step 3 | Python3 implementation to find the number the number of ways to reach Nth stair by taking 1 or 2 steps at a time and 3 rd Step exactly once ; Function to find the number of ways ; Base Case ; Count of 2 - steps ; Count of 1 - steps ; Initial length of sequence ; expected count of 2 - steps ; Loop to find the ways for every possible sequence ; Driver Code
import math NEW_LINE def ways ( n ) : NEW_LINE INDENT if n < 3 : NEW_LINE INDENT return 0 NEW_LINE DEDENT c2 = 0 NEW_LINE c1 = n - 3 NEW_LINE l = c1 + 1 NEW_LINE s = 0 NEW_LINE exp_c2 = c1 / 2 NEW_LINE while exp_c2 >= c2 : NEW_LINE INDENT f1 = math . factorial ( l ) NEW_LINE f2 = math . factorial ( c1 ) NEW_LINE f3 = math . factorial ( c2 ) NEW_LINE s += f1 // ( f2 * f3 ) NEW_LINE c2 += 1 NEW_LINE c1 -= 2 NEW_LINE l -= 1 NEW_LINE DEDENT return s NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 NEW_LINE print ( ways ( N ) ) NEW_LINE DEDENT
Find N from the value of N ! | Map to precompute and store the factorials of the numbers ; Function to precompute factorial ; Calculating the factorial for each i and storing in a map ; Driver code ; Precomputing the factorials
m = { } ; NEW_LINE def precompute ( ) : NEW_LINE INDENT fact = 1 ; NEW_LINE for i in range ( 1 , 19 ) : NEW_LINE INDENT fact = fact * i ; NEW_LINE m [ fact ] = i ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT precompute ( ) ; NEW_LINE K = 120 ; NEW_LINE print ( m [ K ] ) ; NEW_LINE K = 6 ; NEW_LINE print ( m [ K ] ) ; NEW_LINE DEDENT
Count of Leap Years in a given year range | Function to calculate the number of leap years in range of ( 1 , year ) ; Function to calculate the number of leap years in given range ; Driver Code
def calNum ( year ) : NEW_LINE INDENT return ( year // 4 ) - ( year // 100 ) + ( year // 400 ) ; NEW_LINE DEDENT def leapNum ( l , r ) : NEW_LINE INDENT l -= 1 ; NEW_LINE num1 = calNum ( r ) ; NEW_LINE num2 = calNum ( l ) ; NEW_LINE print ( num1 - num2 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l1 = 1 ; r1 = 400 ; NEW_LINE leapNum ( l1 , r1 ) ; NEW_LINE l2 = 400 ; r2 = 2000 ; NEW_LINE leapNum ( l2 , r2 ) ; NEW_LINE DEDENT
Find sum of f ( s ) for all the chosen sets from the given array | Python3 implementation of the approach ; To store the factorial and the factorial mod inverse of a number ; Function to find factorial of all the numbers ; Function to find the factorial mod inverse of all the numbers ; Function to return nCr ; Function to find sum of f ( s ) for all the chosen sets from the given array ; Sort the given array ; Calculate the factorial and modinverse of all elements ; For all the possible sets Calculate max ( S ) and min ( S ) ; Driver code
N = 100005 NEW_LINE mod = ( 10 ** 9 + 7 ) NEW_LINE factorial = [ 0 ] * N NEW_LINE modinverse = [ 0 ] * N NEW_LINE def factorialfun ( ) : NEW_LINE INDENT factorial [ 0 ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT factorial [ i ] = ( factorial [ i - 1 ] * i ) % mod NEW_LINE DEDENT DEDENT def modinversefun ( ) : NEW_LINE INDENT modinverse [ N - 1 ] = pow ( factorial [ N - 1 ] , mod - 2 , mod ) % mod NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT modinverse [ i ] = ( modinverse [ i + 1 ] * ( i + 1 ) ) % mod NEW_LINE DEDENT DEDENT def binomial ( n , r ) : NEW_LINE INDENT if ( r > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT a = ( factorial [ n ] * modinverse [ n - r ] ) % mod NEW_LINE a = ( a * modinverse [ r ] ) % mod NEW_LINE return a NEW_LINE DEDENT def max_min ( a , n , k ) : NEW_LINE INDENT a = sorted ( a ) NEW_LINE factorialfun ( ) NEW_LINE modinversefun ( ) NEW_LINE ans = 0 NEW_LINE k -= 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = n - i - 1 NEW_LINE if ( x >= k ) : NEW_LINE INDENT ans -= ( binomial ( x , k ) * a [ i ] ) % mod NEW_LINE DEDENT y = i NEW_LINE if ( y >= k ) : NEW_LINE INDENT ans += ( binomial ( y , k ) * a [ i ] ) % mod NEW_LINE DEDENT ans = ( ans + mod ) % mod NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ 1 , 1 , 3 , 4 ] NEW_LINE k = 2 NEW_LINE n = len ( a ) NEW_LINE print ( max_min ( a , n , k ) ) NEW_LINE
Length of Smallest subarray in range 1 to N with sum greater than a given value | Function to return the count of minimum elements such that the sum of those elements is > S . ; Initialize currentSum = 0 ; Loop from N to 1 to add the numbers and check the condition . ; Driver code
def countNumber ( N , S ) : NEW_LINE INDENT countElements = 0 ; NEW_LINE currSum = 0 ; NEW_LINE while ( currSum <= S ) : NEW_LINE INDENT currSum += N ; NEW_LINE N = N - 1 ; NEW_LINE countElements = countElements + 1 ; NEW_LINE DEDENT return countElements ; NEW_LINE DEDENT N = 5 ; NEW_LINE S = 11 ; NEW_LINE count = countNumber ( N , S ) ; NEW_LINE print ( count ) ; NEW_LINE
Next Number with distinct digits | Python3 program to find next consecutive Number with all distinct digits ; Function to count distinct digits in a number ; To count the occurrence of digits in number from 0 to 9 ; Iterate over the digits of the number Flag those digits as found in the array ; Traverse the array arr and count the distinct digits in the array ; Function to return the total number of digits in the number ; Iterate over the digits of the number ; Function to return the next number with distinct digits ; Count the distinct digits in N + 1 ; Count the total number of digits in N + 1 ; Return the next consecutive number ; Increment Number by 1 ; Driver code
import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def countDistinct ( n ) : NEW_LINE INDENT arr = [ 0 ] * 10 ; NEW_LINE count = 0 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT r = int ( n % 10 ) ; NEW_LINE arr [ r ] = 1 ; NEW_LINE n //= 10 ; NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT def countDigit ( n ) : NEW_LINE INDENT c = 0 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT r = n % 10 ; NEW_LINE c += 1 ; NEW_LINE n //= 10 ; NEW_LINE DEDENT return c ; NEW_LINE DEDENT def nextNumberDistinctDigit ( n ) : NEW_LINE INDENT while ( n < INT_MAX ) : NEW_LINE INDENT distinct_digits = countDistinct ( n + 1 ) ; NEW_LINE total_digits = countDigit ( n + 1 ) ; NEW_LINE if ( distinct_digits == total_digits ) : NEW_LINE INDENT return n + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT n += 1 ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2019 ; NEW_LINE print ( nextNumberDistinctDigit ( n ) ) ; NEW_LINE DEDENT
Minimum possible sum of array B such that AiBi = AjBj for all 1 Γ’ ‰€ i < j Γ’ ‰€ N | Python3 implementation of the approach ; To store least prime factors of all the numbers ; Function to find the least prime factor of all the numbers ; Function to return the sum of elements of array B ; Find the prime factors of all the numbers ; To store each prime count in lcm ; Current number ; Map to store the prime count of a single number ; Basic way to calculate all prime factors ; If it is the first number in the array ; Take the maximum count of prime in a number ; Calculate lcm of given array ; Calculate sum of elements of array B ; Driver code
mod = 10 ** 9 + 7 NEW_LINE N = 1000005 NEW_LINE lpf = [ 0 for i in range ( N ) ] NEW_LINE def least_prime_factor ( ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT lpf [ i ] = i NEW_LINE DEDENT for i in range ( 2 , N ) : NEW_LINE INDENT if ( lpf [ i ] == i ) : NEW_LINE INDENT for j in range ( i * 2 , N , i ) : NEW_LINE INDENT if ( lpf [ j ] == j ) : NEW_LINE INDENT lpf [ j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def sum_of_elements ( a , n ) : NEW_LINE INDENT least_prime_factor ( ) NEW_LINE prime_factor = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = a [ i ] NEW_LINE single_number = dict ( ) NEW_LINE while ( temp > 1 ) : NEW_LINE INDENT x = lpf [ temp ] NEW_LINE single_number [ x ] = single_number . get ( x , 0 ) + 1 NEW_LINE temp //= x NEW_LINE DEDENT if ( i == 0 ) : NEW_LINE INDENT prime_factor = single_number NEW_LINE DEDENT else : NEW_LINE INDENT for x in single_number : NEW_LINE INDENT if x in prime_factor : NEW_LINE INDENT prime_factor [ x ] = max ( prime_factor [ x ] , single_number [ x ] ) NEW_LINE DEDENT else : NEW_LINE INDENT prime_factor [ x ] = single_number [ x ] NEW_LINE DEDENT DEDENT DEDENT DEDENT ans , lcm = 0 , 1 NEW_LINE for x in prime_factor : NEW_LINE INDENT lcm = ( lcm * pow ( x , prime_factor [ x ] , mod ) ) % mod NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT ans = ( ans + ( lcm * pow ( a [ i ] , mod - 2 , mod ) ) % mod ) % mod NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 2 , 3 , 4 ] NEW_LINE n = len ( a ) NEW_LINE print ( sum_of_elements ( a , n ) ) NEW_LINE DEDENT
Find Number of Even cells in a Zero Matrix after Q queries | Function to find the number of even cell in a 2D matrix ; Maintain two arrays , one for rows operation and one for column operation ; Increment operation on row [ i ] ; Increment operation on col [ i ] ; Count odd and even values in both arrays and multiply them ; Count of rows having even numbers ; Count of rows having odd numbers ; Count of columns having even numbers ; Count of columns having odd numbers ; Driver code
def findNumberOfEvenCells ( n , q , size ) : NEW_LINE INDENT row = [ 0 ] * n ; NEW_LINE col = [ 0 ] * n NEW_LINE for i in range ( size ) : NEW_LINE INDENT x = q [ i ] [ 0 ] ; NEW_LINE y = q [ i ] [ 1 ] ; NEW_LINE row [ x - 1 ] += 1 ; NEW_LINE col [ y - 1 ] += 1 ; NEW_LINE DEDENT r1 = 0 ; NEW_LINE r2 = 0 ; NEW_LINE c1 = 0 ; NEW_LINE c2 = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( row [ i ] % 2 == 0 ) : NEW_LINE INDENT r1 += 1 ; NEW_LINE DEDENT if ( row [ i ] % 2 == 1 ) : NEW_LINE INDENT r2 += 1 ; NEW_LINE DEDENT if ( col [ i ] % 2 == 0 ) : NEW_LINE INDENT c1 += 1 ; NEW_LINE DEDENT if ( col [ i ] % 2 == 1 ) : NEW_LINE INDENT c2 += 1 ; NEW_LINE DEDENT DEDENT count = r1 * c1 + r2 * c2 ; NEW_LINE return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; NEW_LINE q = [ [ 1 , 1 ] , [ 1 , 2 ] , [ 2 , 1 ] ] ; NEW_LINE size = len ( q ) ; NEW_LINE print ( findNumberOfEvenCells ( n , q , size ) ) ; NEW_LINE DEDENT
Find maximum unreachable height using two ladders | Function to return the maximum height which can 't be reached ; Driver code
def maxHeight ( h1 , h2 ) : NEW_LINE INDENT return ( ( h1 * h2 ) - h1 - h2 ) NEW_LINE DEDENT h1 = 7 NEW_LINE h2 = 5 NEW_LINE print ( max ( 0 , maxHeight ( h1 , h2 ) ) ) NEW_LINE
Fermat 's Factorization Method | Python 3 implementation of fermat 's factorization ; This function finds the value of a and b and returns a + b and a - b ; since fermat 's factorization applicable for odd positive integers only ; check if n is a even number ; if n is a perfect root , then both its square roots are its factors ; Driver Code
from math import ceil , sqrt NEW_LINE def FermatFactors ( n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return [ n ] NEW_LINE DEDENT if ( n & 1 ) == 0 : NEW_LINE INDENT return [ n / 2 , 2 ] NEW_LINE DEDENT a = ceil ( sqrt ( n ) ) NEW_LINE if ( a * a == n ) : NEW_LINE INDENT return [ a , a ] NEW_LINE DEDENT while ( True ) : NEW_LINE INDENT b1 = a * a - n NEW_LINE b = int ( sqrt ( b1 ) ) NEW_LINE if ( b * b == b1 ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT a += 1 NEW_LINE DEDENT DEDENT return [ a - b , a + b ] NEW_LINE DEDENT print ( FermatFactors ( 6557 ) ) NEW_LINE
Append two elements to make the array satisfy the given condition | Function to find the required numbers ; Find the sum and xor ; Print the required elements ; Driver code
def findNums ( arr , n ) : NEW_LINE INDENT S = 0 ; X = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT S += arr [ i ] ; NEW_LINE X ^= arr [ i ] ; NEW_LINE DEDENT print ( X , X + S ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 7 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findNums ( arr , n ) ; NEW_LINE DEDENT
Satisfy the parabola when point ( A , B ) and the equation is given | Function to find the required values ; Driver code
def solve ( A , B ) : NEW_LINE INDENT p = B / 2 NEW_LINE M = int ( 4 * p ) NEW_LINE N = 1 NEW_LINE O = - 2 * A NEW_LINE Q = int ( A * A + 4 * p * p ) NEW_LINE return [ M , N , O , Q ] NEW_LINE DEDENT a = 1 NEW_LINE b = 1 NEW_LINE print ( * solve ( a , b ) ) NEW_LINE
Largest number dividing maximum number of elements in the array | Python3 implementation of the approach ; Function to return the largest number that divides the maximum elements from the given array ; Finding gcd of all the numbers in the array ; Driver code
from math import gcd as __gcd NEW_LINE def findLargest ( arr , n ) : NEW_LINE INDENT gcd = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT gcd = __gcd ( arr [ i ] , gcd ) NEW_LINE DEDENT return gcd NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findLargest ( arr , n ) ) NEW_LINE DEDENT
Check if the sum of digits of N is palindrome | Function to return the sum of digits of n ; Function that returns true if n is palindrome ; Find the appropriate divisor to extract the leading digit ; If first and last digit not same return false ; Removing the leading and trailing digit from number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Function that returns true if the digit sum of n is palindrome ; Sum of the digits of n ; If the digit sum is palindrome ; Driver code
def digitSum ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT sum += ( n % 10 ) ; NEW_LINE n //= 10 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def isPalindrome ( n ) : NEW_LINE INDENT divisor = 1 ; NEW_LINE while ( n // divisor >= 10 ) : NEW_LINE INDENT divisor *= 10 ; NEW_LINE DEDENT while ( n != 0 ) : NEW_LINE INDENT leading = n // divisor ; NEW_LINE trailing = n % 10 ; NEW_LINE if ( leading != trailing ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT n = ( n % divisor ) // 10 ; NEW_LINE divisor = divisor // 100 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def isDigitSumPalindrome ( n ) : NEW_LINE INDENT sum = digitSum ( n ) ; NEW_LINE if ( isPalindrome ( sum ) ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 56 ; NEW_LINE if ( isDigitSumPalindrome ( n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Find the value of N XOR 'ed to itself K times | Function to return n ^ n ^ ... k times ; If k is odd the answer is the number itself ; Else the answer is 0 ; Driver code
def xorK ( n , k ) : NEW_LINE INDENT if ( k % 2 == 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT return 0 NEW_LINE DEDENT n = 123 NEW_LINE k = 3 NEW_LINE print ( xorK ( n , k ) ) NEW_LINE
Find the sum of the costs of all possible arrangements of the cells | Python3 implementation of the approach ; To store the factorials and factorial mod inverse of the numbers ; Function to return ( a ^ m1 ) % mod ; Function to find the factorials of all the numbers ; Function to find factorial mod inverse of all the numbers ; Function to return nCr ; Function to return the sum of the costs of all the possible arrangements of the cells ; For all possible X 's ; For all possible Y 's ; Driver code
N = 100005 NEW_LINE mod = ( int ) ( 1e9 + 7 ) NEW_LINE factorial = [ 0 ] * N ; NEW_LINE modinverse = [ 0 ] * N ; NEW_LINE def power ( a , m1 ) : NEW_LINE INDENT if ( m1 == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( m1 == 1 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT elif ( m1 == 2 ) : NEW_LINE INDENT return ( a * a ) % mod ; NEW_LINE DEDENT elif ( m1 & 1 ) : NEW_LINE INDENT return ( a * power ( power ( a , m1 // 2 ) , 2 ) ) % mod ; NEW_LINE DEDENT else : NEW_LINE INDENT return power ( power ( a , m1 // 2 ) , 2 ) % mod ; NEW_LINE DEDENT DEDENT def factorialfun ( ) : NEW_LINE INDENT factorial [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT factorial [ i ] = ( factorial [ i - 1 ] * i ) % mod ; NEW_LINE DEDENT DEDENT def modinversefun ( ) : NEW_LINE INDENT modinverse [ N - 1 ] = power ( factorial [ N - 1 ] , mod - 2 ) % mod ; NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT modinverse [ i ] = ( modinverse [ i + 1 ] * ( i + 1 ) ) % mod ; NEW_LINE DEDENT DEDENT def binomial ( n , r ) : NEW_LINE INDENT if ( r > n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT a = ( factorial [ n ] * modinverse [ n - r ] ) % mod ; NEW_LINE a = ( a * modinverse [ r ] ) % mod ; NEW_LINE return a ; NEW_LINE DEDENT def arrange ( n , m , k ) : NEW_LINE INDENT factorialfun ( ) ; NEW_LINE modinversefun ( ) ; NEW_LINE ans = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ans += ( i * ( n - i ) * m * m ) % mod ; NEW_LINE DEDENT for i in range ( 1 , m ) : NEW_LINE INDENT ans += ( i * ( m - i ) * n * n ) % mod ; NEW_LINE DEDENT ans = ( ans * binomial ( n * m - 2 , k - 2 ) ) % mod ; NEW_LINE return int ( ans ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; m = 2 ; k = 2 ; NEW_LINE print ( arrange ( n , m , k ) ) ; NEW_LINE DEDENT
Find the Nth digit in the proper fraction of two numbers | Function to print the Nth digit in the fraction ( p / q ) ; While N > 0 compute the Nth digit by dividing p and q and store the result into variable res and go to next digit ; Driver code
def findNthDigit ( p , q , N ) : NEW_LINE INDENT while ( N > 0 ) : NEW_LINE INDENT N -= 1 ; NEW_LINE p *= 10 ; NEW_LINE res = p // q ; NEW_LINE p %= q ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p = 1 ; q = 2 ; N = 1 ; NEW_LINE print ( findNthDigit ( p , q , N ) ) ; NEW_LINE DEDENT
Sum of the updated array after performing the given operation | Utility function to return the sum of the array ; Function to return the sum of the modified array ; Subtract the subarray sum ; Sum of subarray arr [ i ... n - 1 ] ; Return the sum of the modified array ; Driver code
def sumArr ( arr , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def sumModArr ( arr , n ) : NEW_LINE INDENT subSum = arr [ n - 1 ] ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT curr = arr [ i ] ; NEW_LINE arr [ i ] -= subSum ; NEW_LINE subSum += curr ; NEW_LINE DEDENT return sumArr ( arr , n ) ; NEW_LINE DEDENT arr = [ 40 , 25 , 12 , 10 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( sumModArr ( arr , n ) ) ; NEW_LINE
Find closest integer with the same weight | Python3 implementation of the approach ; Function to return the number closest to x which has equal number of set bits as x ; Loop for each bit in x and compare with the next bit ; Driver code
NumUnsignBits = 64 ; NEW_LINE def findNum ( x ) : NEW_LINE INDENT for i in range ( NumUnsignBits - 1 ) : NEW_LINE INDENT if ( ( ( x >> i ) & 1 ) != ( ( x >> ( i + 1 ) ) & 1 ) ) : NEW_LINE INDENT x ^= ( 1 << i ) | ( 1 << ( i + 1 ) ) ; NEW_LINE return x ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 92 ; NEW_LINE print ( findNum ( n ) ) ; NEW_LINE DEDENT
Cake Distribution Problem | Function to return the remaining count of cakes ; Sum for 1 cycle ; no . of full cycle and remainder ; Driver code
def cntCakes ( n , m ) : NEW_LINE INDENT sum = ( n * ( n + 1 ) ) // 2 NEW_LINE quo , rem = m // sum , m % sum NEW_LINE ans = m - quo * sum NEW_LINE x = int ( ( - 1 + ( 8 * rem + 1 ) ** 0.5 ) / 2 ) NEW_LINE ans = ans - x * ( x + 1 ) // 2 NEW_LINE return ans NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT n = 4 NEW_LINE m = 11 NEW_LINE ans = cntCakes ( n , m ) NEW_LINE print ( ans ) NEW_LINE DEDENT main ( ) NEW_LINE
Find the number of squares inside the given square grid | Function to return the number of squares inside an n * n grid ; Driver code
def cntSquares ( n ) : NEW_LINE INDENT return int ( n * ( n + 1 ) * ( 2 * n + 1 ) / 6 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( cntSquares ( 4 ) ) ; NEW_LINE DEDENT
Find all palindrome numbers of given digits | Function to return the reverse of num ; Function that returns true if num is palindrome ; If the number is equal to the reverse of it then it is a palindrome ; Function to prall the d - digit palindrome numbers ; Smallest and the largest d - digit numbers ; Starting from the smallest d - digit number till the largest ; If the current number is palindrome ; Driver code
def reverse ( num ) : NEW_LINE INDENT rev = 0 ; NEW_LINE while ( num > 0 ) : NEW_LINE INDENT rev = rev * 10 + num % 10 ; NEW_LINE num = num // 10 ; NEW_LINE DEDENT return rev ; NEW_LINE DEDENT def isPalindrome ( num ) : NEW_LINE INDENT if ( num == reverse ( num ) ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def printPalindromes ( d ) : NEW_LINE INDENT if ( d <= 0 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT smallest = pow ( 10 , d - 1 ) ; NEW_LINE largest = pow ( 10 , d ) - 1 ; NEW_LINE for i in range ( smallest , largest + 1 ) : NEW_LINE INDENT if ( isPalindrome ( i ) ) : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT d = 2 ; NEW_LINE printPalindromes ( d ) ; NEW_LINE
Minimum number of moves to reach N starting from ( 1 , 1 ) | Python3 implementation of the approach ; Function to return the minimum number of moves required to reach the cell containing N starting from ( 1 , 1 ) ; To store the required answer ; For all possible values of divisors ; If i is a divisor of n ; Get the moves to reach n ; Return the required answer ; Driver code
import sys NEW_LINE from math import sqrt NEW_LINE def min_moves ( n ) : NEW_LINE INDENT ans = sys . maxsize ; NEW_LINE for i in range ( 1 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT ans = min ( ans , i + n // i - 2 ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 ; NEW_LINE print ( min_moves ( n ) ) ; NEW_LINE DEDENT
Minimum possible value of ( i * j ) % 2019 | Python3 implementation of the approach ; Function to return the minimum possible value of ( i * j ) % 2019 ; If we can get a number divisible by 2019 ; Find the minimum value by running nested loops ; Driver code
MOD = 2019 ; NEW_LINE def min_modulo ( l , r ) : NEW_LINE INDENT if ( r - l >= MOD ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans = MOD - 1 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , r + 1 ) : NEW_LINE INDENT ans = min ( ans , ( i * j ) % MOD ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 2020 ; r = 2040 ; NEW_LINE print ( min_modulo ( l , r ) ) ; NEW_LINE DEDENT
Represent ( 2 / N ) as the sum of three distinct positive integers of the form ( 1 / m ) | Function to find the required fractions ; Base condition ; For N > 1 ; Driver code
def find_numbers ( N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( - 1 , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( N , N + 1 , N * ( N + 1 ) ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 ; NEW_LINE find_numbers ( N ) ; NEW_LINE DEDENT
Count the pairs in an array such that the difference between them and their indices is equal | Function to return the count of all valid pairs ; To store the frequencies of ( arr [ i ] - i ) ; To store the required count ; If cnt is the number of elements whose difference with their index is same then ( ( cnt * ( cnt - 1 ) ) / 2 ) such pairs are possible ; Driver code
def countPairs ( arr , n ) : NEW_LINE INDENT map = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT map [ arr [ i ] - i ] = map . get ( arr [ i ] - i , 0 ) + 1 NEW_LINE DEDENT res = 0 NEW_LINE for x in map : NEW_LINE INDENT cnt = map [ x ] NEW_LINE res += ( ( cnt * ( cnt - 1 ) ) // 2 ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 1 , 5 , 6 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE
Minimum possible number with the given operation | Function to return the minimum possible integer that can be obtained from the given integer after performing the given operations ; For every digit ; Digits less than 5 need not to be changed as changing them will lead to a larger number ; The resulting integer cannot have leading zero ; Driver code
def minInt ( str1 ) : NEW_LINE INDENT for i in range ( len ( str1 ) ) : NEW_LINE INDENT if ( str1 [ i ] >= 5 ) : NEW_LINE INDENT str1 [ i ] = ( 9 - str1 [ i ] ) NEW_LINE DEDENT DEDENT if ( str1 [ 0 ] == 0 ) : NEW_LINE INDENT str1 [ 0 ] = 9 NEW_LINE DEDENT temp = " " NEW_LINE for i in str1 : NEW_LINE INDENT temp += str ( i ) NEW_LINE DEDENT return temp NEW_LINE DEDENT str1 = "589" NEW_LINE str1 = [ int ( i ) for i in str1 ] NEW_LINE print ( minInt ( str1 ) ) NEW_LINE
Reduce N to 1 with minimum number of given operations | Function to return the minimum number of given operations required to reduce n to 1 ; To store the count of operations ; To store the digit ; If n is already then no operation is required ; Extract all the digits except the first digit ; Store the maximum of that digits ; for each digit ; First digit ; Add the value to count ; Driver code
def minOperations ( n ) : NEW_LINE INDENT count = 0 NEW_LINE d = 0 NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( n > 9 ) : NEW_LINE INDENT d = max ( n % 10 , d ) NEW_LINE n //= 10 NEW_LINE count += 10 NEW_LINE DEDENT d = max ( d , n - 1 ) NEW_LINE count += abs ( d ) NEW_LINE return count - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 240 NEW_LINE print ( minOperations ( n ) ) NEW_LINE DEDENT
Find the largest number that can be formed by changing at most K digits | Function to return the maximum number that can be formed by changing at most k digits in str ; For every digit of the number ; If no more digits can be replaced ; If current digit is not already 9 ; Replace it with 9 ; One digit has been used ; Driver code
def findMaximumNum ( st , n , k ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( k < 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( st [ i ] != '9' ) : NEW_LINE INDENT st = st [ 0 : i ] + '9' + st [ i + 1 : ] NEW_LINE k -= 1 NEW_LINE DEDENT DEDENT return st NEW_LINE DEDENT st = "569431" NEW_LINE n = len ( st ) NEW_LINE k = 3 NEW_LINE print ( findMaximumNum ( st , n , k ) ) NEW_LINE
Check if two Integer are anagrams of each other | Function that returns true if a and b are anagarams of each other ; Converting numbers to strings ; Checking if the sorting values of two strings are equal ; Driver code
def areAnagrams ( a , b ) : NEW_LINE INDENT a = str ( a ) NEW_LINE b = str ( b ) NEW_LINE if ( sorted ( a ) == sorted ( b ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT a = 240 NEW_LINE b = 204 NEW_LINE if ( areAnagrams ( a , b ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Number of occurrences of a given angle formed using 3 vertices of a n | Function that calculates occurrences of given angle that can be created using any 3 sides ; Maximum angle in a regular n - gon is equal to the interior angle If the given angle is greater than the interior angle then the given angle cannot be created ; The given angle times n should be divisible by 180 else it cannot be created ; Initialise answer ; Calculate the frequency of given angle for each vertex ; Multiply answer by frequency . ; Multiply answer by the number of vertices . ; Driver code
def solve ( ang , n ) : NEW_LINE INDENT if ( ( ang * n ) > ( 180 * ( n - 2 ) ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( ( ang * n ) % 180 != 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 1 NEW_LINE freq = ( ang * n ) // 180 NEW_LINE ans = ans * ( n - 1 - freq ) NEW_LINE ans = ans * n NEW_LINE return ans NEW_LINE DEDENT ang = 90 NEW_LINE n = 4 NEW_LINE print ( solve ( ang , n ) ) NEW_LINE
Find third number such that sum of all three number becomes prime | Function that will check whether number is prime or not ; Function to print the 3 rd number ; If the summ is odd ; If summ is not prime ; Driver code
def prime ( n ) : NEW_LINE INDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if i * i > n + 1 : NEW_LINE INDENT break NEW_LINE DEDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def thirdNumber ( a , b ) : NEW_LINE INDENT summ = 0 NEW_LINE temp = 0 NEW_LINE summ = a + b NEW_LINE temp = 1 NEW_LINE if ( summ & 1 ) : NEW_LINE INDENT temp = 2 NEW_LINE DEDENT while ( prime ( summ + temp ) == False ) : NEW_LINE INDENT temp += 2 NEW_LINE DEDENT print ( temp ) NEW_LINE DEDENT a = 3 NEW_LINE b = 5 NEW_LINE thirdNumber ( a , b ) NEW_LINE
Total ways of selecting a group of X men from N men with or without including a particular man | Function to return the value of nCr ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the count of ways ; Driver code
def nCr ( n , r ) : NEW_LINE INDENT ans = 1 ; NEW_LINE for i in range ( 1 , r + 1 ) : NEW_LINE INDENT ans *= ( n - r + i ) ; NEW_LINE ans //= i ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def total_ways ( N , X ) : NEW_LINE INDENT return ( nCr ( N - 1 , X - 1 ) + nCr ( N - 1 , X ) ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 ; X = 3 ; NEW_LINE print ( total_ways ( N , X ) ) ; NEW_LINE DEDENT
Compute the maximum power with a given condition | Function to return the largest power ; If n is greater than given M ; If n == m ; Checking for the next power ; Driver 's code
def calculate ( n , k , m , power ) : NEW_LINE INDENT if n > m : NEW_LINE INDENT if power == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return power - 1 NEW_LINE DEDENT DEDENT elif n == m : NEW_LINE INDENT return power NEW_LINE DEDENT else : NEW_LINE INDENT return calculate ( n * k , k , m , power + 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 1 NEW_LINE K = 2 NEW_LINE M = 5 NEW_LINE print ( calculate ( N , K , M , 0 ) ) NEW_LINE DEDENT
Program to find the number from given holes | Function that will find out the number ; If number of holes equal 0 then return 1 ; If number of holes equal 0 then return 0 ; If number of holes is more than 0 or 1. ; If number of holes is odd ; Driver code ; Calling Function
def printNumber ( holes ) : NEW_LINE INDENT if ( holes == 0 ) : NEW_LINE INDENT print ( "1" ) NEW_LINE DEDENT elif ( holes == 1 ) : NEW_LINE INDENT print ( "0" , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT rem = 0 NEW_LINE quo = 0 NEW_LINE rem = holes % 2 NEW_LINE quo = holes // 2 NEW_LINE if ( rem == 1 ) : NEW_LINE INDENT print ( "4" , end = " " ) NEW_LINE DEDENT for i in range ( quo ) : NEW_LINE INDENT print ( "8" , end = " " ) NEW_LINE DEDENT DEDENT DEDENT holes = 3 NEW_LINE printNumber ( holes ) NEW_LINE
Minimum cost to make all array elements equal | Function to return the minimum cost to make each array element equal ; To store the count of even numbers present in the array ; To store the count of odd numbers present in the array ; Iterate through the array and find the count of even numbers and odd numbers ; Driver code
def minCost ( arr , n ) : NEW_LINE INDENT count_even = 0 NEW_LINE count_odd = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT count_even += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_odd += 1 NEW_LINE DEDENT DEDENT return min ( count_even , count_odd ) NEW_LINE DEDENT arr = [ 2 , 4 , 3 , 1 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minCost ( arr , n ) ) NEW_LINE
Number of Subarrays with positive product | Function to return the count of subarrays with negative product ; Replace current element with 1 if it is positive else replace it with - 1 instead ; Take product with previous element to form the prefix product ; Count positive and negative elements in the prefix product array ; Return the required count of subarrays ; Function to return the count of subarrays with positive product ; Total subarrays possible ; Count to subarrays with negative product ; Return the count of subarrays with positive product ; Driver code
def negProdSubArr ( arr , n ) : NEW_LINE INDENT positive = 1 NEW_LINE negative = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = - 1 NEW_LINE DEDENT if ( i > 0 ) : NEW_LINE INDENT arr [ i ] *= arr [ i - 1 ] NEW_LINE DEDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT positive += 1 NEW_LINE DEDENT else : NEW_LINE INDENT negative += 1 NEW_LINE DEDENT DEDENT return ( positive * negative ) NEW_LINE DEDENT def posProdSubArr ( arr , n ) : NEW_LINE INDENT total = ( n * ( n + 1 ) ) / 2 ; NEW_LINE cntNeg = negProdSubArr ( arr , n ) ; NEW_LINE return ( total - cntNeg ) ; NEW_LINE DEDENT arr = [ 5 , - 4 , - 3 , 2 , - 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( posProdSubArr ( arr , n ) ) NEW_LINE
Find the XOR of first N Prime Numbers | Python3 implementation of the approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false + if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Set all multiples of p to non - prime ; Function to return the xor of 1 st N prime numbers ; Count of prime numbers ; XOR of prime numbers ; If the number is prime xor it ; Increment the count ; Get to the next number ; Create the sieve ; Find the xor of 1 st n prime numbers
MAX = 10000 NEW_LINE prime = [ True for i in range ( MAX + 1 ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime [ 1 ] = False NEW_LINE for p in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( 2 * p , MAX + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def xorFirstNPrime ( n ) : NEW_LINE INDENT count = 0 NEW_LINE num = 1 NEW_LINE xorVal = 0 NEW_LINE while ( count < n ) : NEW_LINE INDENT if ( prime [ num ] ) : NEW_LINE INDENT xorVal ^= num NEW_LINE count += 1 NEW_LINE DEDENT num += 1 NEW_LINE DEDENT return xorVal NEW_LINE DEDENT SieveOfEratosthenes ( ) NEW_LINE n = 4 NEW_LINE print ( xorFirstNPrime ( n ) ) NEW_LINE
Sum of all natural numbers from L to R ( for large values of L and R ) | Python3 implementation of the approach ; Value of inverse modulo 2 with 10 ^ 9 + 7 ; Function to return num % 1000000007 where num is a large number ; Initialize result ; One by one process all the digits of string 'num ; Function to return the sum of the integers from the given range modulo 1000000007 ; a stores the value of L modulo 10 ^ 9 + 7 ; b stores the value of R modulo 10 ^ 9 + 7 ; l stores the sum of natural numbers from 1 to ( a - 1 ) ; r stores the sum of natural numbers from 1 to b ; If the result is negative ; Driver code
mod = 1000000007 NEW_LINE inv2 = 500000004 ; NEW_LINE def modulo ( num ) : NEW_LINE INDENT res = 0 ; NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( len ( num ) ) : NEW_LINE INDENT res = ( res * 10 + int ( num [ i ] ) - 0 ) % mod ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def findSum ( L , R ) : NEW_LINE INDENT a = modulo ( L ) ; NEW_LINE b = modulo ( R ) ; NEW_LINE l = ( ( a * ( a - 1 ) ) % mod * inv2 ) % mod ; NEW_LINE r = ( ( b * ( b + 1 ) ) % mod * inv2 ) % mod ; NEW_LINE ret = ( r % mod - l % mod ) ; NEW_LINE if ( ret < 0 ) : NEW_LINE INDENT ret = ret + mod ; NEW_LINE DEDENT else : NEW_LINE INDENT ret = ret % mod ; NEW_LINE DEDENT return ret ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = "88949273204" ; NEW_LINE R = "98429729474298592" ; NEW_LINE print ( findSum ( L , R ) ) ; NEW_LINE DEDENT
Maximum subsequence sum such that all elements are K distance apart | Function to return the maximum subarray sum for the array { a [ i ] , a [ i + k ] , a [ i + 2 k ] , ... } ; Function to return the sum of the maximum required subsequence ; To store the result ; Run a loop from 0 to k ; Find the maximum subarray sum for the array { a [ i ] , a [ i + k ] , a [ i + 2 k ] , ... } ; Return the maximum value ; Driver code
import sys NEW_LINE def maxSubArraySum ( a , n , k , i ) : NEW_LINE INDENT max_so_far = - sys . maxsize ; NEW_LINE max_ending_here = 0 ; NEW_LINE while ( i < n ) : 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 i += k ; NEW_LINE DEDENT return max_so_far ; NEW_LINE DEDENT def find ( arr , n , k ) : NEW_LINE INDENT maxSum = 0 ; NEW_LINE for i in range ( 0 , min ( n , k ) + 1 ) : NEW_LINE INDENT sum = 0 ; NEW_LINE maxSum = max ( maxSum , maxSubArraySum ( arr , n , k , i ) ) ; NEW_LINE DEDENT return maxSum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , - 3 , - 1 , - 1 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE print ( find ( arr , n , k ) ) ; NEW_LINE DEDENT
Generate N integers satisfying the given conditions | Python3 implementation of the approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Set all multiples of p to non - prime ; Function to find the first n odd prime numbers ; To store the current count of prime numbers ; Starting with 3 as 2 is an even prime number ; If i is prime ; Print i and increment count ; Driver code ; Create the sieve
from math import sqrt NEW_LINE MAX = 1000000 NEW_LINE prime = [ True ] * ( MAX + 1 ) ; NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime [ 1 ] = False ; NEW_LINE for p in range ( 2 , int ( sqrt ( MAX ) ) + 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , MAX + 1 , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def solve ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE i = 3 ; NEW_LINE while count < n : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE count += 1 ; NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT SieveOfEratosthenes ( ) ; NEW_LINE n = 6 ; NEW_LINE solve ( n ) ; NEW_LINE DEDENT
Probability that a N digit number is palindrome | Find the probability that a n digit number is palindrome ; Denominator ; Assign 10 ^ ( floor ( n / 2 ) ) to denominator ; Display the answer ; Driver code
def solve ( n ) : NEW_LINE INDENT n_2 = n // 2 ; NEW_LINE den = "1" ; NEW_LINE while ( n_2 ) : NEW_LINE INDENT den += '0' ; NEW_LINE n_2 -= 1 NEW_LINE DEDENT print ( str ( 1 ) + " / " + str ( den ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 ; NEW_LINE solve ( N ) ; NEW_LINE DEDENT
Ways to choose balls such that at least one ball is chosen | Python3 implementation of the approach ; Function to return the count of ways to choose the balls ; Return ( ( 2 ^ n ) - 1 ) % MOD ; Driver code
MOD = 1000000007 NEW_LINE def countWays ( n ) : NEW_LINE INDENT return ( ( ( 2 ** n ) - 1 ) % MOD ) NEW_LINE DEDENT n = 3 NEW_LINE print ( countWays ( n ) ) NEW_LINE
Minimize the sum of the array according the given condition | Function to return the minimum sum ; sort the array to find the minimum element ; finding the number to divide ; Checking to what instance the sum has decreased ; getting the max difference ; Driver Code
def findMin ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum = sum + arr [ i ] NEW_LINE DEDENT arr . sort ( ) NEW_LINE min = arr [ 0 ] NEW_LINE max = 0 NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT num = arr [ i ] NEW_LINE total = num + min NEW_LINE for j in range ( 2 , num + 1 ) : NEW_LINE INDENT if ( num % j == 0 ) : NEW_LINE INDENT d = j NEW_LINE now = ( num // d ) + ( min * d ) NEW_LINE reduce = total - now NEW_LINE if ( reduce > max ) : NEW_LINE INDENT max = reduce NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( sum - max ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE findMin ( arr , n ) NEW_LINE
Print all the permutation of length L using the elements of an array | Iterative | Convert the number to Lth base and print the sequence ; Sequence is of Length L ; Print the ith element of sequence ; Print all the permuataions ; There can be ( Len ) ^ l permutations ; Convert i to Len th base ; Driver code ; function call
def convert_To_Len_th_base ( n , arr , Len , L ) : NEW_LINE INDENT for i in range ( L ) : NEW_LINE INDENT print ( arr [ n % Len ] , end = " " ) NEW_LINE n //= Len NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def printf ( arr , Len , L ) : NEW_LINE INDENT for i in range ( pow ( Len , L ) ) : NEW_LINE INDENT convert_To_Len_th_base ( i , arr , Len , L ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE Len = len ( arr ) NEW_LINE L = 2 NEW_LINE printf ( arr , Len , L ) NEW_LINE
Number of possible permutations when absolute difference between number of elements to the right and left are given | Function to find the number of permutations possible of the original array to satisfy the given absolute differences ; To store the count of each a [ i ] in a map ; if n is odd ; check the count of each whether it satisfy the given criteria or not ; there is only 1 way for middle element . ; for others there are 2 ways . ; now find total ways ; When n is even . ; there will be no middle element so for each a [ i ] there will be 2 ways ; Driver Code
def totalways ( arr , n ) : NEW_LINE INDENT cnt = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt [ arr [ i ] ] = cnt . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT if ( n % 2 == 1 ) : NEW_LINE INDENT start , endd = 0 , n - 1 NEW_LINE for i in range ( start , endd + 1 , 2 ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT if ( cnt [ i ] != 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( cnt [ i ] != 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT DEDENT ways = 1 NEW_LINE start = 2 NEW_LINE endd = n - 1 NEW_LINE for i in range ( start , endd + 1 , 2 ) : NEW_LINE INDENT ways = ways * 2 NEW_LINE DEDENT return ways NEW_LINE DEDENT elif ( n % 2 == 0 ) : NEW_LINE INDENT start = 1 NEW_LINE endd = n - 1 NEW_LINE for i in range ( 1 , endd + 1 , 2 ) : NEW_LINE INDENT if ( cnt [ i ] != 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT ways = 1 NEW_LINE for i in range ( start , endd + 1 , 2 ) : NEW_LINE INDENT ways = ways * 2 NEW_LINE DEDENT return ways NEW_LINE DEDENT DEDENT N = 5 NEW_LINE arr = [ 2 , 4 , 4 , 0 , 2 ] NEW_LINE print ( totalways ( arr , N ) ) NEW_LINE
Proizvolov 's Identity | Function to implement proizvolov 's identity ; According to proizvolov 's identity ; Driver code ; Function call
def proizvolov ( a , b , n ) : NEW_LINE INDENT return n * n NEW_LINE DEDENT a = [ 1 , 5 , 6 , 8 , 10 ] NEW_LINE b = [ 9 , 7 , 4 , 3 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( proizvolov ( a , b , n , ) ) NEW_LINE
Find the ln ( X ) and log10X with the help of expansion | Function to calculate ln x using expansion ; terminating value of the loop can be increased to improve the precision ; Function to calculate log10 x ; Driver Code ; setprecision ( 3 ) is used to display the output up to 3 decimal places
from math import pow NEW_LINE def calculateLnx ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE num = ( n - 1 ) / ( n + 1 ) NEW_LINE for i in range ( 1 , 1001 , 1 ) : NEW_LINE INDENT mul = ( 2 * i ) - 1 NEW_LINE cal = pow ( num , mul ) NEW_LINE cal = cal / mul NEW_LINE sum = sum + cal NEW_LINE DEDENT sum = 2 * sum NEW_LINE return sum NEW_LINE DEDENT def calculateLogx ( lnx ) : NEW_LINE INDENT return ( lnx / 2.303 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE lnx = calculateLnx ( n ) NEW_LINE logx = calculateLogx ( lnx ) NEW_LINE print ( " ln " , " { 0 : . 3f } " . format ( n ) , " = " , " { 0 : . 3f } " . format ( lnx ) ) NEW_LINE print ( " log10" , " { 0 : . 3f } " . format ( n ) , " = " , " { 0 : . 3f } " . format ( logx ) ) NEW_LINE DEDENT
Find the sum of elements of the Matrix generated by the given rules | Function to return the required ssum ; To store the ssum ; For every row ; Update the ssum as A appears i number of times in the current row ; Update A for the next row ; Return the ssum ; Driver code
def Sum ( A , B , R ) : NEW_LINE INDENT ssum = 0 NEW_LINE for i in range ( 1 , R + 1 ) : NEW_LINE INDENT ssum = ssum + ( i * A ) NEW_LINE A = A + B NEW_LINE DEDENT return ssum NEW_LINE DEDENT A , B , R = 5 , 3 , 3 NEW_LINE print ( Sum ( A , B , R ) ) NEW_LINE
EuclidΓ’ β‚¬β€œ Mullin Sequence | Function to return the smallest prime factor of n ; Initialize i = 2 ; While i <= sqrt ( n ) ; If n is divisible by i ; Increment i ; Function to print the first n terms of the required sequence ; To store the product of the previous terms ; Traverse the prime numbers ; Current term will be smallest prime factor of ( 1 + product of all previous terms ) ; Print the current term ; Update the product ; Find the first 14 terms of the sequence
def smallestPrimeFactor ( n ) : NEW_LINE INDENT i = 2 NEW_LINE while ( i * i ) <= n : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT return i NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return n NEW_LINE DEDENT def solve ( n ) : NEW_LINE INDENT product = 1 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT num = smallestPrimeFactor ( product + 1 ) NEW_LINE print ( num , end = ' ▁ ' ) NEW_LINE product = product * num NEW_LINE i += 1 NEW_LINE DEDENT DEDENT b = 14 NEW_LINE solve ( b ) NEW_LINE
Count total set bits in all numbers from 1 to n | Set 2 | Function to return the sum of the count of set bits in the integers from 1 to n ; Ignore 0 as all the bits are unset ; To store the powers of 2 ; To store the result , it is initialized with n / 2 because the count of set least significant bits in the integers from 1 to n is n / 2 ; Loop for every bit required to represent n ; Total count of pairs of 0 s and 1 s ; totalPairs / 2 gives the complete count of the pairs of 1 s Multiplying it with the current power of 2 will give the count of 1 s in the current bit ; If the count of pairs was odd then add the remaining 1 s which could not be groupped together ; Next power of 2 ; Return the result ; Driver code
def countSetBits ( n ) : NEW_LINE INDENT n += 1 ; NEW_LINE powerOf2 = 2 ; NEW_LINE cnt = n // 2 ; NEW_LINE while ( powerOf2 <= n ) : NEW_LINE INDENT totalPairs = n // powerOf2 ; NEW_LINE cnt += ( totalPairs // 2 ) * powerOf2 ; NEW_LINE if ( totalPairs & 1 ) : NEW_LINE INDENT cnt += ( n % powerOf2 ) NEW_LINE DEDENT else : NEW_LINE INDENT cnt += 0 NEW_LINE DEDENT powerOf2 <<= 1 ; NEW_LINE DEDENT return cnt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 14 ; NEW_LINE print ( countSetBits ( n ) ) ; NEW_LINE DEDENT
Find the height of a right | Function to return the height of the right - angled triangle whose area is X times its base ; Driver code
def getHeight ( X ) : NEW_LINE INDENT return ( 2 * X ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 35 NEW_LINE print ( getHeight ( X ) ) NEW_LINE DEDENT
Find sum of inverse of the divisors when sum of divisors and the number is given | Function to return the sum of inverse of divisors ; Calculating the answer ; Return the answer ; Driver code ; Function call
def SumofInverseDivisors ( N , Sum ) : NEW_LINE INDENT ans = float ( Sum ) * 1.0 / float ( N ) ; NEW_LINE return round ( ans , 2 ) ; NEW_LINE DEDENT N = 9 ; NEW_LINE Sum = 13 ; NEW_LINE print SumofInverseDivisors ( N , Sum ) ; NEW_LINE
Number of triplets such that each value is less than N and each pair sum is a multiple of K | Function to return the number of triplets ; Initializing the count array ; Storing the frequency of each modulo class ; If K is odd ; If K is even ; Driver Code ; Function Call
def NoofTriplets ( N , K ) : NEW_LINE INDENT cnt = [ 0 ] * K ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT cnt [ i % K ] += 1 ; NEW_LINE DEDENT if ( K & 1 ) : NEW_LINE INDENT rslt = cnt [ 0 ] * cnt [ 0 ] * cnt [ 0 ] ; NEW_LINE return rslt NEW_LINE DEDENT else : NEW_LINE INDENT rslt = ( cnt [ 0 ] * cnt [ 0 ] * cnt [ 0 ] + cnt [ K // 2 ] * cnt [ K // 2 ] * cnt [ K // 2 ] ) ; NEW_LINE return rslt NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 ; K = 2 ; NEW_LINE print ( NoofTriplets ( N , K ) ) ; NEW_LINE DEDENT
Find a number containing N | Function to compute number using our deduced formula ; Initialize num to n - 1 ; Driver code
def findNumber ( n ) : NEW_LINE INDENT num = n - 1 ; NEW_LINE num = 2 * ( 4 ** num ) ; NEW_LINE num = num // 3 ; NEW_LINE return num ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; NEW_LINE print ( findNumber ( n ) ) ; NEW_LINE DEDENT
Find XOR of numbers from the range [ L , R ] | Python3 implementation of the approach ; Function to return the XOR of elements from the range [ 1 , n ] ; 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 ; Function to return the XOR of elements from the range [ l , r ] ; Driver code
from operator import xor NEW_LINE def findXOR ( n ) : NEW_LINE INDENT mod = n % 4 ; NEW_LINE if ( mod == 0 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT elif ( mod == 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( mod == 2 ) : NEW_LINE INDENT return n + 1 ; NEW_LINE DEDENT elif ( mod == 3 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT def findXORFun ( l , r ) : NEW_LINE INDENT return ( xor ( findXOR ( l - 1 ) , findXOR ( r ) ) ) ; NEW_LINE DEDENT l = 4 ; r = 8 ; NEW_LINE print ( findXORFun ( l , r ) ) ; NEW_LINE
Number of elements from the array which are reachable after performing given operations on D | Function to return the GCD of a and b ; Function to return the count of reachable integers from the given array ; GCD of A and B ; To store the count of reachable integers ; If current element can be reached ; Return the count ; Driver code
def GCD ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT return GCD ( b , a % b ) ; NEW_LINE DEDENT def findReachable ( arr , D , A , B , n ) : NEW_LINE INDENT gcd_AB = GCD ( A , B ) ; NEW_LINE count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( arr [ i ] - D ) % gcd_AB == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT arr = [ 4 , 5 , 6 , 7 , 8 , 9 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE D = 4 ; A = 4 ; B = 6 ; NEW_LINE print ( findReachable ( arr , D , A , B , n ) ) ; NEW_LINE
Number of trees whose sum of degrees of all the vertices is L | Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize result ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Function to return the count of required trees ; number of nodes ; Return the result ; Driver code
def power ( x , y ) : NEW_LINE INDENT res = 1 ; NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y % 2 == 1 ) : NEW_LINE INDENT res = ( res * x ) ; NEW_LINE DEDENT y = int ( y ) >> 1 ; NEW_LINE x = ( x * x ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def solve ( L ) : NEW_LINE INDENT n = L / 2 + 1 ; NEW_LINE ans = power ( n , n - 2 ) ; NEW_LINE return int ( ans ) ; NEW_LINE DEDENT L = 6 ; NEW_LINE print ( solve ( L ) ) ; NEW_LINE
Change one element in the given array to make it an Arithmetic Progression | Python program to change one element of an array such that the resulting array is in arithmetic progression . ; Finds the initial term and common difference and prints the resulting array . ; Check if the first three elements are in arithmetic progression ; Check if the first element is not in arithmetic progression ; The first and fourth element are in arithmetic progression ; Print the arithmetic progression ; Driver code
def makeAP ( arr , n ) : NEW_LINE INDENT initial_term , common_difference = 0 , 0 NEW_LINE if ( n == 3 ) : NEW_LINE INDENT common_difference = arr [ 2 ] - arr [ 1 ] NEW_LINE initial_term = arr [ 1 ] - common_difference NEW_LINE DEDENT elif ( ( arr [ 1 ] - arr [ 0 ] ) == arr [ 2 ] - arr [ 1 ] ) : NEW_LINE INDENT initial_term = arr [ 0 ] NEW_LINE common_difference = arr [ 1 ] - arr [ 0 ] NEW_LINE DEDENT elif ( ( arr [ 2 ] - arr [ 1 ] ) == ( arr [ 3 ] - arr [ 2 ] ) ) : NEW_LINE INDENT common_difference = arr [ 2 ] - arr [ 1 ] NEW_LINE initial_term = arr [ 1 ] - common_difference NEW_LINE DEDENT else : NEW_LINE INDENT common_difference = ( arr [ 3 ] - arr [ 0 ] ) / 3 NEW_LINE initial_term = arr [ 0 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( int ( initial_term + ( i * common_difference ) ) , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT arr = [ 1 , 3 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE makeAP ( arr , n ) NEW_LINE
Find if nCr is divisible by the given prime | Function to return the highest power of p that divides n ! implementing Legendre Formula ; Return the highest power of p which divides n ! ; Function that returns true if nCr is divisible by p ; Find the highest powers of p that divide n ! , r ! and ( n - r ) ! ; If nCr is divisible by p ; Driver code
def getfactor ( n , p ) : NEW_LINE INDENT pw = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT n //= p ; NEW_LINE pw += n ; NEW_LINE DEDENT return pw ; NEW_LINE DEDENT def isDivisible ( n , r , p ) : NEW_LINE INDENT x1 = getfactor ( n , p ) ; NEW_LINE x2 = getfactor ( r , p ) ; NEW_LINE x3 = getfactor ( n - r , p ) ; NEW_LINE if ( x1 > x2 + x3 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 7 ; r = 2 ; p = 7 ; NEW_LINE if ( isDivisible ( n , r , p ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Check if the number is even or odd whose digits and base ( radix ) is given | Function that returns true if the number represented by arr [ ] is even in base r ; If the base is even , then the last digit is checked ; If base is odd , then the number of odd digits are checked ; To store the count of odd digits ; Number is odd ; Driver code
def isEven ( arr , n , r ) : NEW_LINE INDENT if ( r % 2 == 0 ) : NEW_LINE INDENT if ( arr [ n - 1 ] % 2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT oddCount = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 != 0 ) : NEW_LINE INDENT oddCount += 1 NEW_LINE DEDENT DEDENT if ( oddCount % 2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE r = 2 NEW_LINE if ( isEven ( arr , n , r ) ) : NEW_LINE INDENT print ( " Even " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Odd " ) NEW_LINE DEDENT DEDENT
Bitwise AND of sub | Python implementation of the approach ; Function to return the minimum possible value of | K - X | where X is the bitwise AND of the elements of some sub - array ; Check all possible sub - arrays ; Find the overall minimum ; No need to perform more AND operations as | k - X | will increase ; Driver code
import sys NEW_LINE def closetAND ( arr , n , k ) : NEW_LINE INDENT ans = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT X = arr [ i ] ; NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT X &= arr [ j ] ; NEW_LINE ans = min ( ans , abs ( k - X ) ) ; NEW_LINE if ( X <= k ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT arr = [ 4 , 7 , 10 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE print ( closetAND ( arr , n , k ) ) ; NEW_LINE
Count of quadruplets from range [ L , R ] having GCD equal to K | Function to return the gcd of a and b ; Function to return the count of quadruplets having gcd = k ; Count the frequency of every possible gcd value in the range ; To store the required count ; Calculate the answer using frequency values ; Return the required count ; Driver code
def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT return gcd ( b , a % b ) ; NEW_LINE DEDENT def countQuadruplets ( l , r , k ) : NEW_LINE INDENT frequency = [ 0 ] * ( r + 1 ) ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT for j in range ( l , r + 1 ) : NEW_LINE INDENT frequency [ gcd ( i , j ) ] += 1 ; NEW_LINE DEDENT DEDENT answer = 0 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT for j in range ( l , r + 1 ) : NEW_LINE INDENT if ( gcd ( i , j ) == k ) : NEW_LINE INDENT answer += ( frequency [ i ] * frequency [ j ] ) ; NEW_LINE DEDENT DEDENT DEDENT return answer ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l , r , k = 1 , 10 , 2 ; NEW_LINE print ( countQuadruplets ( l , r , k ) ) ; NEW_LINE DEDENT
Rearrange the array to maximize the number of primes in prefix sum of the array | Function to print the re - arranged array ; Count the number of ones and twos in a [ ] ; If the array element is 1 ; Array element is 2 ; If it has at least one 2 Fill up first 2 ; Decrease the cnt of ones if even ; Fill up with odd count of ones ; Fill up with remaining twos ; If even ones , then fill last position ; Print the rearranged array ; Driver code
def solve ( a , n ) : NEW_LINE INDENT ones , twos = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT else : NEW_LINE INDENT twos += 1 NEW_LINE DEDENT DEDENT ind = 0 NEW_LINE if ( twos ) : NEW_LINE INDENT a [ ind ] = 2 NEW_LINE ind += 1 NEW_LINE DEDENT if ones % 2 == 0 : NEW_LINE INDENT evenOnes = True NEW_LINE DEDENT else : NEW_LINE INDENT evenOnes = False NEW_LINE DEDENT if ( evenOnes ) : NEW_LINE INDENT ones -= 1 NEW_LINE DEDENT for i in range ( ones ) : NEW_LINE INDENT a [ ind ] = 1 NEW_LINE ind += 1 NEW_LINE DEDENT for i in range ( twos - 1 ) : NEW_LINE INDENT a [ ind ] = 2 NEW_LINE ind += 1 NEW_LINE DEDENT if ( evenOnes ) : NEW_LINE INDENT a [ ind ] = 1 NEW_LINE ind += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT a = [ 1 , 2 , 1 , 2 , 1 ] NEW_LINE n = len ( a ) NEW_LINE solve ( a , n ) NEW_LINE
Generate an Array in which count of even and odd sum sub | Function to generate and print the required array ; Find the number of odd prefix sums ; If no odd prefix sum found ; Calculating the number of even prefix sums ; Stores the current prefix sum ; If current prefix sum is even ; Print 0 until e = EvenPreSums - 1 ; Print 1 when e = EvenPreSums ; Print 0 for rest of the values ; Driver code
def CreateArray ( N , even , odd ) : NEW_LINE INDENT temp = - 1 NEW_LINE for i in range ( N + 2 ) : NEW_LINE INDENT if ( i * ( ( N + 1 ) - i ) == odd ) : NEW_LINE INDENT temp = 0 NEW_LINE OddPreSums = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( temp == - 1 ) : NEW_LINE INDENT print ( temp ) NEW_LINE DEDENT else : NEW_LINE INDENT EvenPreSums = ( N + 1 ) - OddPreSums NEW_LINE e = 1 NEW_LINE o = 0 NEW_LINE CurrSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( CurrSum % 2 == 0 ) : NEW_LINE INDENT if ( e < EvenPreSums ) : NEW_LINE INDENT e += 1 NEW_LINE print ( "0 ▁ " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT o += 1 NEW_LINE print ( "1 ▁ " , end = " " ) NEW_LINE CurrSum += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( e < EvenPreSums ) : NEW_LINE INDENT e += 1 NEW_LINE print ( "1 ▁ " ) NEW_LINE CurrSum += 1 NEW_LINE DEDENT else : NEW_LINE INDENT o += 1 NEW_LINE print ( "0 ▁ " , end = " " ) NEW_LINE DEDENT DEDENT DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 15 NEW_LINE even = 60 NEW_LINE odd = 60 NEW_LINE CreateArray ( N , even , odd ) NEW_LINE DEDENT
Minimum operations required to change the array such that | arr [ i ] | Python3 implementation of the approach ; Function to return the minimum number of operations required ; Minimum and maximum elements from the array ; To store the minimum number of operations required ; To store the number of operations required to change every element to either ( num - 1 ) , num or ( num + 1 ) ; If current element is not already num ; Add the count of operations required to change arr [ i ] ; Update the minimum operations so far ; Driver code
import math NEW_LINE import sys NEW_LINE def changeTheArray ( arr , n ) : NEW_LINE INDENT minEle = min ( arr ) NEW_LINE maxEle = max ( arr ) NEW_LINE minOperations = sys . maxsize NEW_LINE for num in range ( minEle , maxEle + 1 ) : NEW_LINE INDENT operations = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] != num : NEW_LINE INDENT operations += ( abs ( num - arr [ i ] ) - 1 ) NEW_LINE DEDENT DEDENT minOperations = min ( minOperations , operations ) NEW_LINE DEDENT return minOperations NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 1 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( changeTheArray ( arr , n ) ) NEW_LINE DEDENT
Choose X such that ( A xor X ) + ( B xor X ) is minimized | Function to return the integer X such that ( A xor X ) + ( B ^ X ) is minimized ; While either A or B is non - zero ; Position at which both A and B have a set bit ; Inserting a set bit in x ; Right shifting both numbers to traverse all the bits ; Driver code
def findX ( A , B ) : NEW_LINE INDENT j = 0 NEW_LINE x = 0 NEW_LINE while ( A or B ) : NEW_LINE INDENT if ( ( A & 1 ) and ( B & 1 ) ) : NEW_LINE INDENT x += ( 1 << j ) NEW_LINE DEDENT A >>= 1 NEW_LINE B >>= 1 NEW_LINE j += 1 NEW_LINE DEDENT return x NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 2 NEW_LINE B = 3 NEW_LINE X = findX ( A , B ) NEW_LINE print ( " X ▁ = " , X , " , ▁ Sum ▁ = " , ( A ^ X ) + ( B ^ X ) ) NEW_LINE DEDENT
Choose X such that ( A xor X ) + ( B xor X ) is minimized | finding X ; finding Sum ; Driver code
def findX ( A , B ) : NEW_LINE INDENT return A & B NEW_LINE DEDENT def findSum ( A , B ) : NEW_LINE INDENT return A ^ B NEW_LINE DEDENT A , B = 2 , 3 NEW_LINE print ( " X ▁ = " , findX ( A , B ) , " , ▁ Sum ▁ = " , findSum ( A , B ) ) NEW_LINE
Compare sum of first N | Function that returns true if sum of first n - 1 elements of the array is equal to the last element ; Find the sum of first n - 1 elements of the array ; If sum equals to the last element ; Driver code
def isSumEqual ( ar , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT sum += ar [ i ] NEW_LINE DEDENT if ( sum == ar [ n - 1 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE if ( isSumEqual ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Count number of 1 s in the array after N moves | Python3 implementation of the above approach ; Function to count number of perfect squares ; Counting number of perfect squares between a and b ; Function to count number of 1 s in array after N moves ; Driver Code ; Initialize array size ; Initialize all elements to 0
from math import sqrt , ceil , floor ; NEW_LINE def perfectSquares ( a , b ) : NEW_LINE INDENT return ( floor ( sqrt ( b ) ) - ceil ( sqrt ( a ) ) + 1 ) ; NEW_LINE DEDENT def countOnes ( arr , n ) : NEW_LINE INDENT return perfectSquares ( 1 , n ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 10 ; NEW_LINE arr = [ 0 ] * 10 ; NEW_LINE print ( countOnes ( arr , N ) ) ; NEW_LINE DEDENT
Find the position of box which occupies the given ball | Python3 implementation of the approach ; Function to print the position of each boxes where a ball has to be placed ; Find the cumulative sum of array A [ ] ; Find the position of box for each ball ; Row number ; Column ( position of box in particular row ) ; Row + 1 denotes row if indexing of array start from 1 ; Driver code
import bisect NEW_LINE def printPosition ( A , B , sizeOfA , sizeOfB ) : NEW_LINE INDENT for i in range ( 1 , sizeOfA ) : NEW_LINE INDENT A [ i ] += A [ i - 1 ] NEW_LINE DEDENT for i in range ( sizeOfB ) : NEW_LINE INDENT row = bisect . bisect_left ( A , B [ i ] ) NEW_LINE if row >= 1 : NEW_LINE INDENT boxNumber = B [ i ] - A [ row - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT boxNumber = B [ i ] NEW_LINE DEDENT print ( row + 1 , " , " , boxNumber ) NEW_LINE DEDENT DEDENT A = [ 2 , 2 , 2 , 2 ] NEW_LINE B = [ 1 , 2 , 3 , 4 ] NEW_LINE sizeOfA = len ( A ) NEW_LINE sizeOfB = len ( B ) NEW_LINE printPosition ( A , B , sizeOfA , sizeOfB ) NEW_LINE
Highest power of a number that divides other number | Python program to implement the above approach ; Function to get the prime factors and its count of times it divides ; Count the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , count i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Function to return the highest power ; Initialize two arrays ; Get the prime factors of n and m ; Iterate and find the maximum power ; If i not a prime factor of n and m ; If i is a prime factor of n and m If count of i dividing m is more than i dividing n , then power will be 0 ; If i is a prime factor of M ; get the maximum power ; Drivers code
import math NEW_LINE def primeFactors ( n , freq ) : NEW_LINE INDENT cnt = 0 NEW_LINE while n % 2 == 0 : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE n = int ( n // 2 ) NEW_LINE DEDENT freq [ 2 ] = cnt NEW_LINE i = 3 NEW_LINE while i <= math . sqrt ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE n = int ( n // i ) NEW_LINE DEDENT freq [ int ( i ) ] = cnt NEW_LINE i = i + 2 NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT freq [ int ( n ) ] = 1 NEW_LINE DEDENT DEDENT def getMaximumPower ( n , m ) : NEW_LINE INDENT freq1 = [ 0 ] * ( n + 1 ) NEW_LINE freq2 = [ 0 ] * ( m + 1 ) NEW_LINE primeFactors ( n , freq1 ) NEW_LINE primeFactors ( m , freq2 ) NEW_LINE maxi = 0 NEW_LINE i = 2 NEW_LINE while i <= m : NEW_LINE INDENT if ( freq1 [ i ] == 0 and freq2 [ i ] == 0 ) : NEW_LINE INDENT i = i + 1 NEW_LINE continue NEW_LINE DEDENT if ( freq2 [ i ] > freq1 [ i ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( freq2 [ i ] ) : NEW_LINE INDENT maxi = max ( maxi , int ( freq1 [ i ] // freq2 [ i ] ) ) NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT return maxi NEW_LINE DEDENT n = 48 NEW_LINE m = 4 NEW_LINE print ( getMaximumPower ( n , m ) ) NEW_LINE
Find the number of divisors of all numbers in the range [ 1 , n ] | Function to find the number of divisors of all numbers in the range [ 1 , n ] ; List to store the count of divisors ; For every number from 1 to n ; Increase divisors count for every number divisible by i ; Print the divisors ; Driver Code
def findDivisors ( n ) : NEW_LINE INDENT div = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if j * i <= n : NEW_LINE INDENT div [ i * j ] += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( div [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 NEW_LINE findDivisors ( n ) NEW_LINE DEDENT
Predict the winner of the game on the basis of absolute difference of sum by selecting numbers | Function to decide the winner ; Iterate for all numbers in the array ; If mod gives 0 ; If mod gives 1 ; If mod gives 2 ; If mod gives 3 ; Check the winning condition for X ; Driver code
def decideWinner ( a , n ) : NEW_LINE INDENT count0 = 0 NEW_LINE count1 = 0 NEW_LINE count2 = 0 NEW_LINE count3 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 4 == 0 ) : NEW_LINE INDENT count0 += 1 NEW_LINE DEDENT elif ( a [ i ] % 4 == 1 ) : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT elif ( a [ i ] % 4 == 2 ) : NEW_LINE INDENT count2 += 1 NEW_LINE DEDENT elif ( a [ i ] % 4 == 3 ) : NEW_LINE INDENT count3 += 1 NEW_LINE DEDENT DEDENT if ( count0 % 2 == 0 and count1 % 2 == 0 and count2 % 2 == 0 and count3 == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 2 NEW_LINE DEDENT DEDENT a = [ 4 , 8 , 5 , 9 ] NEW_LINE n = len ( a ) NEW_LINE if ( decideWinner ( a , n ) == 1 ) : NEW_LINE INDENT print ( " X ▁ wins " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Y ▁ wins " ) 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 ; Instead of converting all prefixes to decimal , take reminder with x ; If number is divisible by x then reminder = 0 ; Driver code
def CntDivbyX ( arr , n , x ) : NEW_LINE INDENT number = 0 NEW_LINE count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT number = ( number * 2 + arr [ i ] ) % x NEW_LINE if number == 0 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 0 , 1 , 0 , 1 , 1 , 0 ] NEW_LINE n = 7 NEW_LINE x = 2 NEW_LINE print ( CntDivbyX ( arr , n , x ) ) NEW_LINE
Length of the smallest number which is divisible by K and formed by using 1 's only | Function to return length of the resultant number ; If K is a multiple of 2 or 5 ; Instead of generating all possible numbers 1 , 11 , 111 , 111 , ... , K 1 's Take remainder with K ; If number is divisible by k then remainder will be 0 ; Driver code
def numLen ( K ) : NEW_LINE INDENT if ( K % 2 == 0 or K % 5 == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT number = 0 NEW_LINE len = 1 NEW_LINE for len in range ( 1 , K + 1 ) : NEW_LINE INDENT number = ( number * 10 + 1 ) % K NEW_LINE if number == 0 : NEW_LINE INDENT return len NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT K = 7 NEW_LINE print ( numLen ( K ) ) NEW_LINE
Sum of multiplication of triplet of divisors of a number | Global array declaration global max_Element ; Function to find the sum of multiplication of every triplet in the divisors of a number ; global max_Element sum1 [ x ] represents the sum of all the divisors of x ; Adding i to sum1 [ j ] because i is a divisor of j ; sum2 [ x ] represents the sum of all the divisors of x ; Here i is divisor of j and sum1 [ j ] - i represents sum of all divisors of j which do not include i so we add i * ( sum1 [ j ] - i ) to sum2 [ j ] ; In the above implementation we have considered every pair two times so we have to divide every sum2 array element by 2 ; Here i is the divisor of j and we are trying to add the sum of multiplication of all triplets of divisors of j such that one of the divisors is i ; In the above implementation we have considered every triplet three times so we have to divide every sum3 array element by 3 ; Print the results ; Driver code ; Precomputing
max_Element = 100005 NEW_LINE sum1 = [ 0 for i in range ( max_Element ) ] NEW_LINE sum2 = [ 0 for i in range ( max_Element ) ] NEW_LINE sum3 = [ 0 for i in range ( max_Element ) ] NEW_LINE def precomputation ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , max_Element , 1 ) : NEW_LINE INDENT for j in range ( i , max_Element , i ) : NEW_LINE INDENT sum1 [ j ] += i NEW_LINE DEDENT DEDENT for i in range ( 1 , max_Element , 1 ) : NEW_LINE INDENT for j in range ( i , max_Element , i ) : NEW_LINE INDENT sum2 [ j ] += ( sum1 [ j ] - i ) * i NEW_LINE DEDENT DEDENT for i in range ( 1 , max_Element , 1 ) : NEW_LINE INDENT sum2 [ i ] = int ( sum2 [ i ] / 2 ) NEW_LINE DEDENT for i in range ( 1 , max_Element , 1 ) : NEW_LINE INDENT for j in range ( i , max_Element , i ) : NEW_LINE INDENT sum3 [ j ] += i * ( sum2 [ j ] - i * ( sum1 [ j ] - i ) ) NEW_LINE DEDENT DEDENT for i in range ( 1 , max_Element , 1 ) : NEW_LINE INDENT sum3 [ i ] = int ( sum3 [ i ] / 3 ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( sum3 [ arr [ i ] ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE precomputation ( arr , n ) NEW_LINE DEDENT
Sum of Fibonacci Numbers in a range | Python3 implementation of the approach ; Function to return the nth Fibonacci number ; Function to return the required sum ; Using our deduced result ; Driver code
import math NEW_LINE def fib ( n ) : NEW_LINE INDENT phi = ( 1 + math . sqrt ( 5 ) ) / 2 ; NEW_LINE return int ( round ( pow ( phi , n ) / math . sqrt ( 5 ) ) ) ; NEW_LINE DEDENT def calculateSum ( l , r ) : NEW_LINE INDENT sum = fib ( r + 2 ) - fib ( l + 1 ) ; NEW_LINE return sum ; NEW_LINE DEDENT l = 4 ; NEW_LINE r = 8 ; NEW_LINE print ( calculateSum ( l , r ) ) ; NEW_LINE
Print the balanced bracket expression using given brackets | Function to print balanced bracket expression if it is possible ; If the condition is met ; Print brackets of type - 1 ; Print brackets of type - 3 ; Print brackets of type - 4 ; Print brackets of type - 2 ; If the condition is not met ; Driver code
def printBalancedExpression ( a , b , c , d ) : NEW_LINE INDENT if ( ( a == d and a ) or ( a == 0 and c == 0 and d == 0 ) ) : NEW_LINE INDENT for i in range ( 1 , a + 1 ) : NEW_LINE INDENT print ( " ( ( " , end = " " ) NEW_LINE DEDENT for i in range ( 1 , c + 1 ) : NEW_LINE INDENT print ( " ) ( " , end = " " ) NEW_LINE DEDENT for i in range ( 1 , d + 1 ) : NEW_LINE INDENT print ( " ) ) " , end = " " ) NEW_LINE DEDENT for i in range ( 1 , b + 1 ) : NEW_LINE INDENT print ( " ( ) " , end = " " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a , b , c , d = 3 , 1 , 4 , 3 NEW_LINE printBalancedExpression ( a , b , c , d ) NEW_LINE DEDENT
Count numbers having N 0 ' s ▁ and ▁ and ▁ M ▁ 1' s with no leading zeros | Function to return the factorial of a number ; Function to return the count of distinct ( N + M ) digit numbers having N 0 ' s ▁ and ▁ and ▁ M ▁ 1' s with no leading zeros ; Driver code
def factorial ( f ) : NEW_LINE INDENT fact = 1 NEW_LINE for i in range ( 2 , f + 1 ) : NEW_LINE INDENT fact *= i NEW_LINE DEDENT return fact NEW_LINE DEDENT def findPermuatation ( N , M ) : NEW_LINE INDENT permutation = ( factorial ( N + M - 1 ) // ( factorial ( N ) * factorial ( M - 1 ) ) ) NEW_LINE return permutation NEW_LINE DEDENT N = 3 ; M = 3 NEW_LINE print ( findPermuatation ( N , M ) ) NEW_LINE
Maximum value of | arr [ 0 ] | Function to return the maximum required value ; Driver code
def maxValue ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( ( n * n // 2 ) - 1 ) NEW_LINE DEDENT n = 4 NEW_LINE print ( maxValue ( n ) ) NEW_LINE