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 ... | 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 = H... |
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... |
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 wh... | 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_LIN... |
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... | 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 SieveOf... |
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 ... | 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 ... |
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... | 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 * ( ... |
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 ;... | 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 e... |
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... | 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 ,... |
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 ... |
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... | 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_L... |
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 ... |
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 tru... | 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 =... |
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 precalcula... | 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 ( fac... |
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 : NE... |
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 ... | 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 ) : N... |
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 w... | 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 whi... |
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 ; In... | 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 = m... |
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 ; N... |
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 INDE... |
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... | 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 ( ... |
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 = coun... |
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 a... | 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 ] !=... |
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 th... | 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 , ... |
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 t... | 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 =... |
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 it... | 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 whil... |
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 ( a... |
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 ... |
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 b... | 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 wh... |
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 n... | 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 re... |
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 ) ) ; ... |
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_L... |
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 _ _ " : NE... |
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... |
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 th... | 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... |
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 mov... | 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__... |
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_LI... |
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 -... | 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 re... |
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 ... | 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 ... |
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 ... | 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... |
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 ; D... | 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 = le... |
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 ( ... |
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 creat... | 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 a... |
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 su... |
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__ == ... |
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 , po... |
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_... |
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 ... | 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 a... |
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 arr... | 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_LIN... |
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 ... | 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 ... |
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 su... | 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 ... |
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 ... | 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 ; ... |
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 al... | 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... |
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 ... |
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 ... | 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_... |
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... | 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 ) : N... |
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 ret... |
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... | 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 = smalles... |
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 f... | 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... |
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 ]... |
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... | 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 ... |
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 coun... | 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... |
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 = p... |
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... | 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... |
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 ... | 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_LI... |
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 ... | 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 DEDEN... |
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... | 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... |
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 req... | 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 I... |
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... | 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... |
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 ... | 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_... |
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... | 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 [ ... |
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 = ... |
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... |
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 = 1... |
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... | 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 [ ... |
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 a... | 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 INDE... |
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... |
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 ]... |
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 ... |
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 b... | 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 NE... |
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 ... | 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_... |
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 =... |
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... |
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... |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.