text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Make a tree with n vertices , d diameter and at most vertex degree k | Function to Make a tree with n vertices , d as it 's diameter and degree of each vertex is at most k ; If diameter > n - 1 impossible to build tree ; To store the degree of each vertex ; To store the edge between vertices ; To store maximum distance among all the paths from a vertex ; Make diameter of tree equals to d ; Add an edge between them ; Store maximum distance of each vertex from other vertices ; For next ( n - d - 1 ) edges ; If the vertex already has the degree k ; If not possible ; Increase the degree of vertices ; Add an edge between them ; Store the maximum distance of this vertex from other vertices ; Prall the edges of the built tree ; Driver code | def Make_tree ( n , d , k ) : NEW_LINE INDENT if ( d > n - 1 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT deg = [ 0 ] * ( n ) NEW_LINE ans = [ ] NEW_LINE q = { } NEW_LINE for i in range ( d ) : NEW_LINE INDENT deg [ i ] += 1 NEW_LINE deg [ i + 1 ] += 1 NEW_LINE if ( deg [ i ] > k or deg [ i + 1 ] > k ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE return NEW_LINE DEDENT ans . append ( ( i , i + 1 ) ) NEW_LINE DEDENT for i in range ( 1 , d ) : NEW_LINE INDENT q [ ( max ( i , d - i ) , i ) ] = 1 NEW_LINE DEDENT for i in range ( d + 1 , n ) : NEW_LINE INDENT arr = list ( q . keys ( ) ) NEW_LINE while ( len ( q ) > 0 and deg [ arr [ 0 ] [ 1 ] ] == k ) : NEW_LINE INDENT del q [ arr [ 0 ] ] NEW_LINE DEDENT if ( len ( q ) == 0 or arr [ 0 ] [ 0 ] == d ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT deg [ i ] += 1 NEW_LINE deg [ arr [ 0 ] [ 1 ] ] += 1 NEW_LINE ans . append ( ( i , arr [ 0 ] [ 1 ] ) ) NEW_LINE q [ ( arr [ 0 ] [ 0 ] + 1 , i ) ] = 1 NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT print ( ans [ i ] [ 0 ] + 1 , ans [ i ] [ 1 ] + 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n , d , k = 6 , 3 , 4 NEW_LINE Make_tree ( n , d , k ) NEW_LINE DEDENT |
Sum of all Submatrices of a Given Matrix | Python3 program to find the sum of all possible submatrices of a given Matrix ; Function to find the sum of all possible submatrices of a given Matrix ; Variable to store the required sum ; Nested loop to find the number of submatrices , each number belongs to ; Number of ways to choose from top - left elements ; Number of ways to choose from bottom - right elements ; Driver Code | n = 3 NEW_LINE def matrixSum ( arr ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT top_left = ( i + 1 ) * ( j + 1 ) ; NEW_LINE bottom_right = ( n - i ) * ( n - j ) ; NEW_LINE sum += ( top_left * bottom_right * arr [ i ] [ j ] ) ; NEW_LINE DEDENT DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] ] ; NEW_LINE print ( matrixSum ( arr ) ) NEW_LINE DEDENT |
Maximum Bitwise AND pair from given range | Function to return the maximum bitwise AND possible among all the possible pairs ; Maximum among all ( i , j ) pairs ; Driver code | def maxAND ( L , R ) : NEW_LINE INDENT maximum = L & R NEW_LINE for i in range ( L , R , 1 ) : NEW_LINE INDENT for j in range ( i + 1 , R + 1 , 1 ) : NEW_LINE INDENT maximum = max ( maximum , ( i & j ) ) NEW_LINE DEDENT DEDENT return maximum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 1 NEW_LINE R = 632 NEW_LINE print ( maxAND ( L , R ) ) NEW_LINE DEDENT |
Split the array into odd number of segments of odd lengths | Function to check ; Check the result by processing the first & last element and size ; Driver code | def checkArray ( arr , n ) : NEW_LINE INDENT return ( ( arr [ 0 ] % 2 ) and ( arr [ n - 1 ] % 2 ) and ( n % 2 ) ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) ; NEW_LINE if checkArray ( arr , n ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT |
Minimum removals to make array sum odd | Function to find minimum removals ; Count odd numbers ; If the counter is odd return 0 otherwise return 1 ; Driver Code | def findCount ( arr , n ) : NEW_LINE INDENT countOdd = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT countOdd += 1 ; NEW_LINE DEDENT DEDENT if ( countOdd % 2 == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 5 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findCount ( arr , n ) ) ; NEW_LINE DEDENT |
Check whether the number can be made perfect square after adding 1 | Python3 implementation of the approach ; Function that returns true if x is a perfect square ; Find floating po value of square root of x ; If square root is an eger ; Function that returns true if n is a sunny number ; If ( n + 1 ) is a perfect square ; Driver code | import math as mt NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sr = mt . sqrt ( x ) NEW_LINE return ( ( sr - mt . floor ( sr ) ) == 0 ) NEW_LINE DEDENT def isSunnyNum ( n ) : NEW_LINE INDENT if ( isPerfectSquare ( n + 1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT n = 3 NEW_LINE if ( isSunnyNum ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Minimum operations to make counts of remainders same in an array | Function to return the minimum number of operations required ; To store modulos values ; If it 's size greater than k it needed to be decreased ; If it 's size is less than k it needed to be increased ; Driver code | def minOperations ( n , a , m ) : NEW_LINE INDENT k = n // m NEW_LINE val = [ [ ] for i in range ( m ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT val [ a [ i ] % m ] . append ( i ) NEW_LINE DEDENT ans = 0 NEW_LINE extra = [ ] NEW_LINE for i in range ( 0 , 2 * m ) : NEW_LINE INDENT cur = i % m NEW_LINE while len ( val [ cur ] ) > k : NEW_LINE INDENT elem = val [ cur ] . pop ( ) NEW_LINE extra . append ( ( elem , i ) ) NEW_LINE DEDENT while ( len ( val [ cur ] ) < k and len ( extra ) > 0 ) : NEW_LINE INDENT elem = extra [ - 1 ] [ 0 ] NEW_LINE mmod = extra [ - 1 ] [ 1 ] NEW_LINE extra . pop ( ) NEW_LINE val [ cur ] . append ( elem ) NEW_LINE ans += i - mmod NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m = 3 NEW_LINE a = [ 3 , 2 , 0 , 6 , 10 , 12 ] NEW_LINE n = len ( a ) NEW_LINE print ( minOperations ( n , a , m ) ) NEW_LINE DEDENT |
Count primes that can be expressed as sum of two consecutive primes and 1 | Python3 implementation of the approach ; To check if a number is prime or not ; To store possible numbers ; Function to return all prime numbers ; 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 multiple of p and are less than p ^ 2 are already been marked . ; Function to count all possible prime numbers that can be expressed as the sum of two consecutive primes and one ; All possible prime numbers below N ; Driver code | from math import sqrt ; NEW_LINE N = 100005 ; NEW_LINE isprime = [ True ] * N ; NEW_LINE can = [ False ] * N ; NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT for p in range ( 2 , int ( sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( isprime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , N , p ) : NEW_LINE INDENT isprime [ i ] = False ; NEW_LINE DEDENT DEDENT DEDENT primes = [ ] ; NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT if ( isprime [ i ] ) : NEW_LINE INDENT primes . append ( i ) ; NEW_LINE DEDENT DEDENT return primes ; NEW_LINE DEDENT def Prime_Numbers ( n ) : NEW_LINE INDENT primes = SieveOfEratosthenes ( ) ; NEW_LINE for i in range ( len ( primes ) - 1 ) : NEW_LINE INDENT if ( primes [ i ] + primes [ i + 1 ] + 1 < N ) : NEW_LINE INDENT can [ primes [ i ] + primes [ i + 1 ] + 1 ] = True ; NEW_LINE DEDENT DEDENT ans = 0 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( can [ i ] and isprime [ i ] ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 50 ; NEW_LINE print ( Prime_Numbers ( n ) ) ; NEW_LINE DEDENT |
Sum of bitwise AND of all subarrays | Python3 program to find Sum of bitwise AND of all subarrays ; Function to find the Sum of bitwise AND of all subarrays ; variable to store the final Sum ; multiplier ; variable to check if counting is on ; variable to store the length of the subarrays ; loop to find the contiguous segments ; updating the multiplier ; returning the Sum ; Driver Code | import math as mt NEW_LINE def findAndSum ( arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE mul = 1 NEW_LINE for i in range ( 30 ) : NEW_LINE INDENT count_on = 0 NEW_LINE l = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) : NEW_LINE INDENT if ( count_on ) : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_on = 1 NEW_LINE l += 1 NEW_LINE DEDENT DEDENT elif ( count_on ) : NEW_LINE INDENT Sum += ( ( mul * l * ( l + 1 ) ) // 2 ) NEW_LINE count_on = 0 NEW_LINE l = 0 NEW_LINE DEDENT DEDENT if ( count_on ) : NEW_LINE INDENT Sum += ( ( mul * l * ( l + 1 ) ) // 2 ) NEW_LINE count_on = 0 NEW_LINE l = 0 NEW_LINE DEDENT mul *= 2 NEW_LINE DEDENT return Sum NEW_LINE DEDENT arr = [ 7 , 1 , 1 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findAndSum ( arr , n ) ) NEW_LINE |
Source to destination in 2 | Function that returns true if it is possible to move from source to the destination with the given moves ; Driver code | def isPossible ( Sx , Sy , Dx , Dy , x , y ) : NEW_LINE INDENT if ( abs ( Sx - Dx ) % x == 0 and abs ( Sy - Dy ) % y == 0 and ( abs ( Sx - Dx ) / x ) % 2 == ( abs ( Sy - Dy ) / y ) % 2 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT Sx = 0 ; NEW_LINE Sy = 0 ; NEW_LINE Dx = 0 ; NEW_LINE Dy = 0 ; NEW_LINE x = 3 ; NEW_LINE y = 4 ; NEW_LINE if ( isPossible ( Sx , Sy , Dx , Dy , x , y ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Count of pairs ( x , y ) in an array such that x < y | Function to return the number of pairs ( x , y ) such that x < y ; To store the number of valid pairs ; If a valid pair is found ; Return the count of valid pairs ; Driver code | def getPairs ( a ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT for j in range ( len ( a ) ) : NEW_LINE INDENT if ( a [ i ] < a [ j ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 4 , 3 , 1 ] NEW_LINE print ( getPairs ( a ) ) NEW_LINE DEDENT |
Composite numbers with digit sum 1 | Function that returns true if number n is a composite number ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function that returns true if the eventual digit sum of number nm is 1 ; Loop till the sum is not single digit number ; Intitialize the sum as zero ; Find the sum of digits ; If sum is eventually 1 ; Function to print the required numbers from the given range ; If i is one of the required numbers ; Driver code | def isComposite ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return False NEW_LINE DEDENT def isDigitSumOne ( nm ) : NEW_LINE INDENT while ( nm > 9 ) : NEW_LINE INDENT sum_digit = 0 NEW_LINE while ( nm != 0 ) : NEW_LINE INDENT digit = nm % 10 NEW_LINE sum_digit = sum_digit + digit NEW_LINE nm = nm // 10 NEW_LINE DEDENT nm = sum_digit NEW_LINE DEDENT if ( nm == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def printValidNums ( m , n ) : NEW_LINE INDENT for i in range ( m , n + 1 ) : NEW_LINE INDENT if ( isComposite ( i ) and isDigitSumOne ( i ) ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT l = 10 NEW_LINE r = 100 NEW_LINE printValidNums ( m , n ) NEW_LINE |
Determine the count of Leaf nodes in an N | Function to calculate leaf nodes in n - ary tree ; Driver Code | def calcNodes ( N , I ) : NEW_LINE INDENT result = 0 NEW_LINE result = I * ( N - 1 ) + 1 NEW_LINE return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE I = 2 NEW_LINE print ( " Leaf β nodes β = β " , calcNodes ( N , I ) ) NEW_LINE DEDENT |
An application on Bertrand 's ballot theorem | Python3 implementation of the approach ; Function to calculate factorial of a number mod 1000000007 ; Factorial of i = factorial of ( i - 1 ) * i ; Taking mod along with calculation . ; Function for modular exponentiation ; If p is odd ; If p is even ; Function to return the count of required permutations ; Calculating multiplicative modular inverse for x ! and multiplying with ans ; Calculating multiplicative modular inverse for y ! and multiplying with ans ; Driver Code ; Pre - compute factorials | mod = 1000000007 NEW_LINE arr = [ 0 ] * ( 1000001 ) NEW_LINE def cal_factorial ( ) : NEW_LINE INDENT arr [ 0 ] = 1 NEW_LINE for i in range ( 1 , 1000001 ) : NEW_LINE INDENT arr [ i ] = ( arr [ i - 1 ] * i ) % mod NEW_LINE DEDENT DEDENT def mod_exponent ( num , p ) : NEW_LINE INDENT if ( p == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( p & 1 ) : NEW_LINE INDENT return ( ( num % mod ) * ( mod_exponent ( ( num * num ) % mod , p // 2 ) ) % mod ) % mod NEW_LINE DEDENT elif ( not ( p & 1 ) ) : NEW_LINE INDENT return ( mod_exponent ( ( num * num ) % mod , p // 2 ) ) % mod NEW_LINE DEDENT DEDENT def getCount ( x , y ) : NEW_LINE INDENT ans = arr [ x + y - 1 ] NEW_LINE ans *= mod_exponent ( arr [ x ] , mod - 2 ) NEW_LINE ans %= mod NEW_LINE ans *= mod_exponent ( arr [ y ] , mod - 2 ) NEW_LINE ans %= mod NEW_LINE ans *= ( x - y ) NEW_LINE ans %= mod NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT cal_factorial ( ) NEW_LINE x = 3 NEW_LINE y = 1 NEW_LINE print ( getCount ( x , y ) ) NEW_LINE DEDENT |
Find the values of X and Y in the Given Equations | Function to find the values of X and Y ; base condition ; required answer ; Driver Code | def findValues ( a , b ) : NEW_LINE INDENT if ( ( a - b ) % 2 == 1 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT print ( ( a - b ) // 2 , ( a + b ) // 2 ) ; NEW_LINE DEDENT a = 12 ; b = 8 ; NEW_LINE findValues ( a , b ) ; NEW_LINE |
Program to implement Inverse Interpolation using Lagrange Formula | Consider a structure to keep each pair of x and y together ; Function to calculate the inverse interpolation ; Initialize final x ; Calculate each term of the given formula ; Add term to final result ; Driver Code ; Sample dataset of 4 points Here we find the value of x when y = 4.5 ; Size of dataset ; Sample y value ; Using the Inverse Interpolation function to find the value of x when y = 4.5 | class Data : NEW_LINE INDENT def __init__ ( self , x , y ) : NEW_LINE INDENT self . x = x NEW_LINE self . y = y NEW_LINE DEDENT DEDENT def inv_interpolate ( d : list , n : int , y : float ) -> float : NEW_LINE INDENT x = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT xi = d [ i ] . x NEW_LINE for j in range ( n ) : NEW_LINE INDENT if j != i : NEW_LINE INDENT xi = ( xi * ( y - d [ j ] . y ) / ( d [ i ] . y - d [ j ] . y ) ) NEW_LINE DEDENT DEDENT x += xi NEW_LINE DEDENT return x NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT d = [ Data ( 1.27 , 2.3 ) , Data ( 2.25 , 2.95 ) , Data ( 2.5 , 3.5 ) , Data ( 3.6 , 5.1 ) ] NEW_LINE n = 4 NEW_LINE y = 4.5 NEW_LINE print ( " Value β of β x β at β y β = β 4.5 β : " , round ( inv_interpolate ( d , n , y ) , 5 ) ) NEW_LINE DEDENT |
Count triplet pairs ( A , B , C ) of points in 2 | Function to return the count of possible triplets ; Insert all the points in a set ; If the mid point exists in the set ; Return the count of valid triplets ; Driver code | def countTriplets ( n , points ) : NEW_LINE INDENT pts = [ ] NEW_LINE ct = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT pts . append ( points [ i ] ) ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT x = points [ i ] [ 0 ] + points [ j ] [ 0 ] ; NEW_LINE y = points [ i ] [ 1 ] + points [ j ] [ 1 ] ; NEW_LINE if ( x % 2 == 0 and y % 2 == 0 ) : NEW_LINE INDENT if [ x // 2 , y // 2 ] in pts : NEW_LINE INDENT ct += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return ct NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT points = [ [ 1 , 1 ] , [ 2 , 2 ] , [ 3 , 3 ] ] NEW_LINE n = len ( points ) NEW_LINE print ( countTriplets ( n , points ) ) NEW_LINE DEDENT |
Concentration of juice after mixing n glasses in equal proportion | Function to return the concentration of the resultant mixture ; Driver code | def mixtureConcentration ( n , p ) : NEW_LINE INDENT res = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT res += p [ i ] ; NEW_LINE DEDENT res /= n ; NEW_LINE return res ; NEW_LINE DEDENT arr = [ 0 , 20 , 20 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( round ( mixtureConcentration ( n , arr ) , 4 ) ) ; NEW_LINE |
Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B | Python 3 implementation of the approach ; Function that returns true if the num contains a and b digits only ; Modular Exponentiation ; Function to return the modular inverse of x modulo MOD ; Function to return the required count of numbers ; Generating factorials of all numbers ; Generating inverse of factorials modulo MOD of all numbers ; Keeping a as largest number ; Iterate over all possible values of s and if it is a valid S then proceed further ; Check for invalid cases in the equation ; Find answer using combinatorics ; Add this result to final answer ; Driver Code | MAX = 100005 ; NEW_LINE MOD = 1000000007 NEW_LINE def check ( num , a , b ) : NEW_LINE INDENT while ( num ) : NEW_LINE INDENT rem = num % 10 NEW_LINE num = int ( num / 10 ) NEW_LINE if ( rem != a and rem != b ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def power ( x , y ) : NEW_LINE INDENT ans = 1 NEW_LINE while ( y ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT ans = ( ans * x ) % MOD NEW_LINE DEDENT y >>= 1 NEW_LINE x = ( x * x ) % MOD NEW_LINE DEDENT return ans % MOD NEW_LINE DEDENT def modInverse ( x ) : NEW_LINE INDENT return power ( x , MOD - 2 ) NEW_LINE DEDENT def countNumbers ( n , a , b ) : NEW_LINE INDENT fact = [ 0 for i in range ( MAX ) ] NEW_LINE inv = [ 0 for i in range ( MAX ) ] NEW_LINE ans = 0 NEW_LINE fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , MAX , 1 ) : NEW_LINE INDENT fact [ i ] = ( 1 * fact [ i - 1 ] * i ) NEW_LINE fact [ i ] %= MOD NEW_LINE DEDENT inv [ MAX - 1 ] = modInverse ( fact [ MAX - 1 ] ) NEW_LINE i = MAX - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT inv [ i ] = ( inv [ i + 1 ] * ( i + 1 ) ) NEW_LINE inv [ i ] %= MOD NEW_LINE i -= 1 NEW_LINE DEDENT if ( a < b ) : NEW_LINE INDENT temp = a NEW_LINE a = b NEW_LINE b = temp NEW_LINE DEDENT for s in range ( n , 9 * n + 1 , 1 ) : NEW_LINE INDENT if ( check ( s , a , b ) == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( s < n * b or ( s - n * b ) % ( a - b ) != 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT numDig = int ( ( s - n * b ) / ( a - b ) ) NEW_LINE if ( numDig > n ) : NEW_LINE INDENT continue NEW_LINE DEDENT curr = fact [ n ] NEW_LINE curr = ( curr * inv [ numDig ] ) % MOD NEW_LINE curr = ( curr * inv [ n - numDig ] ) % MOD NEW_LINE ans = ( ans + curr ) % MOD NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE a = 1 NEW_LINE b = 3 NEW_LINE print ( countNumbers ( n , a , b ) ) NEW_LINE DEDENT |
Number of elements with even factors in the given range | Function to count the perfect squares ; Driver code | def countOddSquares ( n , m ) : NEW_LINE INDENT return ( int ( pow ( m , 0.5 ) ) - int ( pow ( n - 1 , 0.5 ) ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; m = 100 ; NEW_LINE print ( " Count β is " , ( m - n + 1 ) - countOddSquares ( n , m ) ) NEW_LINE DEDENT |
Total position where king can reach on a chessboard in exactly M moves | Function to return the number of squares that the king can reach in the given number of moves ; Calculate initial and final coordinates ; Since chessboard is of size 8 X8 so if any coordinate is less than 1 or greater than 8 make it 1 or 8. ; Calculate total positions ; Driver code | def Square ( row , column , moves ) : NEW_LINE INDENT a = 0 ; b = 0 ; c = 0 ; NEW_LINE d = 0 ; total = 0 ; NEW_LINE a = row - moves ; NEW_LINE b = row + moves ; NEW_LINE c = column - moves ; NEW_LINE d = column + moves ; NEW_LINE if ( a < 1 ) : NEW_LINE INDENT a = 1 ; NEW_LINE DEDENT if ( c < 1 ) : NEW_LINE INDENT c = 1 ; NEW_LINE DEDENT if ( b > 8 ) : NEW_LINE INDENT b = 8 ; NEW_LINE DEDENT if ( d > 8 ) : NEW_LINE INDENT d = 8 ; NEW_LINE DEDENT total = ( b - a + 1 ) * ( d - c + 1 ) - 1 ; NEW_LINE return total ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT R = 4 ; C = 5 ; M = 2 ; NEW_LINE print ( Square ( R , C , M ) ) ; NEW_LINE DEDENT |
Find M | Function to find the M - th number whosesum till one digit is N ; Driver Code | def findNumber ( n , m ) : NEW_LINE INDENT num = ( m - 1 ) * 9 + n ; NEW_LINE return num ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; NEW_LINE m = 5 ; NEW_LINE print ( findNumber ( n , m ) ) NEW_LINE DEDENT |
Check if a number can be represented as a sum of 2 triangular numbers | Function to check if it is possible or not ; Store all triangular numbers up to N in a Set ; Check if a pair exists ; Driver Code | def checkTriangularSumRepresentation ( n ) : NEW_LINE INDENT tri = list ( ) ; NEW_LINE i = 1 ; NEW_LINE while ( 1 ) : NEW_LINE INDENT x = i * ( i + 1 ) // 2 ; NEW_LINE if ( x >= n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT tri . append ( x ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT for tm in tri : NEW_LINE INDENT if n - tm in tri : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 24 ; NEW_LINE if checkTriangularSumRepresentation ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Absolute difference between the first X and last X Digits of N | Function to find the number of digits in the integer ; Function to find the absolute difference ; Store the last x digits in last ; Count the no . of digits in N ; Remove the digits except the first x ; Store the first x digits in first ; Return the absolute difference between the first and last ; Driver code | def digitsCount ( n ) : NEW_LINE INDENT length = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT length += 1 ; NEW_LINE n //= 10 ; NEW_LINE DEDENT return length ; NEW_LINE DEDENT def absoluteFirstLast ( n , x ) : NEW_LINE INDENT i = 0 ; NEW_LINE mod = 1 ; NEW_LINE while ( i < x ) : NEW_LINE INDENT mod *= 10 ; NEW_LINE i += 1 ; NEW_LINE DEDENT last = n % mod ; NEW_LINE length = digitsCount ( n ) ; NEW_LINE while ( length != x ) : NEW_LINE INDENT n //= 10 ; NEW_LINE length -= 1 ; NEW_LINE DEDENT first = n ; NEW_LINE return abs ( first - last ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 21546 ; NEW_LINE x = 2 ; NEW_LINE print ( absoluteFirstLast ( n , x ) ) ; NEW_LINE DEDENT |
Generate minimum sum sequence of integers with even elements greater | Function to print the required sequence ; arr [ ] will hold the sequence sum variable will store the sum of the sequence ; If sum of the sequence is odd ; Print the sequence ; Driver Code | def make_sequence ( N ) : NEW_LINE INDENT arr = [ 0 ] * ( N + 1 ) NEW_LINE sum = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i % 2 == 1 ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = 2 NEW_LINE DEDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum % 2 == 1 ) : NEW_LINE INDENT arr [ 2 ] = 3 NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 9 NEW_LINE make_sequence ( N ) NEW_LINE DEDENT |
Count Odd and Even numbers in a range from L to R | Return the number of odd numbers in the range [ L , R ] ; if either R or L is odd ; Driver code | def countOdd ( L , R ) : NEW_LINE INDENT N = ( R - L ) // 2 NEW_LINE if ( R % 2 != 0 or L % 2 != 0 ) : NEW_LINE INDENT N += 1 NEW_LINE DEDENT return N NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 3 NEW_LINE R = 7 NEW_LINE odds = countOdd ( L , R ) NEW_LINE evens = ( R - L + 1 ) - odds NEW_LINE print ( " Count β of β odd β numbers β is " , odds ) NEW_LINE print ( " Count β of β even β numbers β is " , evens ) NEW_LINE DEDENT |
Cost of painting n * m grid | Function to return the minimum cost ; Driver code | def getMinCost ( n , m ) : NEW_LINE INDENT cost = ( n - 1 ) * m + ( m - 1 ) * n NEW_LINE return cost NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , m = 4 , 5 NEW_LINE print ( getMinCost ( n , m ) ) NEW_LINE DEDENT |
Minimum operations required to make all the array elements equal | Function to return the minimum number of given operation required to make all the array elements equal ; Check if all the elements from kth index to last are equal ; Finding the 1 st element which is not equal to the kth element ; Driver code | def minOperation ( n , k , a ) : NEW_LINE INDENT for i in range ( k , n ) : NEW_LINE INDENT if ( a [ i ] != a [ k - 1 ] ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT for i in range ( k - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] != a [ k - 1 ] ) : NEW_LINE INDENT return i + 1 NEW_LINE DEDENT DEDENT DEDENT n = 5 NEW_LINE k = 3 NEW_LINE a = [ 2 , 1 , 1 , 1 , 1 ] NEW_LINE print ( minOperation ( n , k , a ) ) NEW_LINE |
Number of Simple Graph with N Vertices and M Edges | Function to return the value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate the value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * ... * 1 ] ; Driver Code | def binomialCoeff ( n , k ) : NEW_LINE INDENT if ( k > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = 1 NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT res *= ( n - i ) NEW_LINE res //= ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE M = 1 NEW_LINE P = ( N * ( N - 1 ) ) // 2 NEW_LINE print ( binomialCoeff ( P , M ) ) NEW_LINE DEDENT |
Increasing sequence with given GCD | Function to print the required sequence ; Driver Code | def generateSequence ( n , g ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( i * g , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , g = 6 , 5 NEW_LINE generateSequence ( n , g ) NEW_LINE DEDENT |
Program to find LCM of two Fibonnaci Numbers | Python 3 Program to find LCM of Fib ( a ) and Fib ( b ) ; Create an array for memoization ; Function to return the n 'th Fibonacci number using table f[]. ; Base cases ; If fib ( n ) is already computed ; Applying recursive formula Note value n & 1 is 1 if n is odd , else 0. ; Function to return gcd of a and b ; Function to return the LCM of Fib ( a ) and Fib ( a ) ; Driver code | MAX = 1000 NEW_LINE f = [ 0 ] * MAX NEW_LINE def fib ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == 1 or n == 2 ) : NEW_LINE INDENT f [ n ] = 1 NEW_LINE return f [ n ] NEW_LINE DEDENT if ( f [ n ] ) : NEW_LINE INDENT return f [ n ] NEW_LINE DEDENT k = ( n + 1 ) // 2 if ( n & 1 ) else n // 2 NEW_LINE if ( n & 1 ) : NEW_LINE INDENT f [ n ] = ( fib ( k ) * fib ( k ) + fib ( k - 1 ) * fib ( k - 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT f [ n ] = ( 2 * fib ( k - 1 ) + fib ( k ) ) * fib ( k ) NEW_LINE DEDENT return f [ n ] NEW_LINE DEDENT def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def findLCMFibonacci ( a , b ) : NEW_LINE INDENT return ( fib ( a ) * fib ( b ) ) // fib ( gcd ( a , b ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 3 NEW_LINE b = 12 NEW_LINE print ( findLCMFibonacci ( a , b ) ) NEW_LINE DEDENT |
Check whether XOR of all numbers in a given range is even or odd | Function to check if XOR of all numbers in range [ L , R ] is Even or Odd ; Count odd Numbers in range [ L , R ] ; Check if count of odd Numbers is even or odd ; Driver Code | def isEvenOrOdd ( L , R ) : NEW_LINE INDENT oddCount = ( R - L ) / 2 NEW_LINE if ( R % 2 == 1 or L % 2 == 1 ) : NEW_LINE INDENT oddCount = oddCount + 1 NEW_LINE DEDENT if ( oddCount % 2 == 0 ) : NEW_LINE INDENT return " Even " NEW_LINE DEDENT else : NEW_LINE INDENT return " Odd " NEW_LINE DEDENT DEDENT L = 5 NEW_LINE R = 15 NEW_LINE print ( isEvenOrOdd ( L , R ) ) ; NEW_LINE |
Count number of trailing zeros in ( 1 ^ 1 ) * ( 2 ^ 2 ) * ( 3 ^ 3 ) * ( 4 ^ 4 ) * . . | Function to return the number of trailing zeros ; To store the number of 2 s and 5 s ; If we get a factor 2 then we have i number of 2 s because the power of the number is raised to i ; If we get a factor 5 then we have i number of 5 s because the power of the number is raised to i ; Take the minimum of them ; Driver code | def trailing_zeros ( N ) : NEW_LINE INDENT count_of_two = 0 NEW_LINE count_of_five = 0 NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT val = i NEW_LINE while ( val % 2 == 0 and val > 0 ) : NEW_LINE INDENT val /= 2 NEW_LINE count_of_two += i NEW_LINE DEDENT while ( val % 5 == 0 and val > 0 ) : NEW_LINE INDENT val /= 5 NEW_LINE count_of_five += i NEW_LINE DEDENT DEDENT ans = min ( count_of_two , count_of_five ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE print ( trailing_zeros ( N ) ) NEW_LINE DEDENT |
Print numbers such that no two consecutive numbers are co | Python3 implementation of the above approach ; Function to generate Sieve of Eratosthenes ; If prime [ p ] is not changed , then it is a prime ; Add the prime numbers to the array b ; Function to return the gcd of a and b ; Function to print the required sequence of integers ; Including the primes in a series of primes which will be later multiplied ; This is done to mark a product as existing ; Maximum number of primes that we consider ; For different interval ; For different starting index of jump ; For storing the numbers ; Checking for occurrence of a product . Also checking for the same prime occurring consecutively ; Including the primes in a series of primes which will be later multiplied ; Driver Code | limit = 1000000000 NEW_LINE MAX_PRIME = 2000000 NEW_LINE MAX = 1000000 NEW_LINE I_MAX = 50000 NEW_LINE mp = { } NEW_LINE b = [ 0 ] * MAX NEW_LINE p = [ 0 ] * MAX NEW_LINE j = 0 NEW_LINE prime = [ True ] * ( MAX_PRIME + 1 ) NEW_LINE def SieveOfEratosthenes ( n ) : NEW_LINE INDENT global j NEW_LINE p = 2 NEW_LINE while p * p <= n : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT b [ j ] = p NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT 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 printSeries ( n ) : NEW_LINE INDENT SieveOfEratosthenes ( MAX_PRIME ) NEW_LINE ar = [ 0 ] * ( I_MAX + 2 ) NEW_LINE for i in range ( j ) : NEW_LINE INDENT if ( ( b [ i ] * b [ i + 1 ] ) > limit ) : NEW_LINE INDENT break NEW_LINE DEDENT p [ i ] = b [ i ] NEW_LINE mp [ b [ i ] * b [ i + 1 ] ] = 1 NEW_LINE DEDENT d = 550 NEW_LINE flag = False NEW_LINE k = 2 NEW_LINE while ( k < d - 1 ) and not flag : NEW_LINE INDENT m = 2 NEW_LINE while ( m < d ) and not flag : NEW_LINE INDENT for l in range ( m + k , d , k ) : NEW_LINE INDENT if ( ( ( b [ l ] * b [ l + k ] ) < limit ) and ( l + k ) < d and p [ i - 1 ] != b [ l + k ] and p [ i - 1 ] != b [ l ] and ( ( b [ l ] * b [ l + k ] in mp ) and mp [ b [ l ] * b [ l + k ] ] != 1 ) ) : NEW_LINE INDENT if ( mp [ p [ i - 1 ] * b [ l ] ] != 1 ) : NEW_LINE INDENT p [ i ] = b [ l ] NEW_LINE mp [ p [ i - 1 ] * b [ l ] ] = 1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if ( i >= I_MAX ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT m += 1 NEW_LINE DEDENT k += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT ar [ i ] = p [ i ] * p [ i + 1 ] NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT print ( ar [ i ] , end = " β " ) NEW_LINE DEDENT g = gcd ( ar [ n - 1 ] , ar [ n - 2 ] ) NEW_LINE print ( g * 2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE printSeries ( n ) NEW_LINE DEDENT |
Print numbers such that no two consecutive numbers are co | Python3 program for the above approach ; Function for Sieve of Eratosthenes ; Function to print the required sequence ; Store only the required primes ; Base condition ; First integer in the list ; Second integer in the list ; Third integer in the list ; Generate ( N - 1 ) th term ; Generate Nth term ; Modify first term ; Print the sequence ; Driver code | MAX = 620000 NEW_LINE prime = [ 0 ] * MAX NEW_LINE def Sieve ( ) : NEW_LINE INDENT for i in range ( 2 , MAX ) : NEW_LINE INDENT if ( prime [ i ] == 0 ) : NEW_LINE INDENT for j in range ( 2 * i , MAX , i ) : NEW_LINE INDENT prime [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def printSequence ( n ) : NEW_LINE INDENT Sieve ( ) NEW_LINE v = [ ] NEW_LINE u = [ ] NEW_LINE for i in range ( 13 , MAX ) : NEW_LINE INDENT if ( prime [ i ] == 0 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT if ( n == 3 ) : NEW_LINE INDENT print ( 6 , 10 , 15 ) NEW_LINE return NEW_LINE DEDENT k = 0 NEW_LINE for k in range ( n - 2 ) : NEW_LINE INDENT if ( k % 3 == 0 ) : NEW_LINE INDENT u . append ( v [ k ] * 6 ) NEW_LINE DEDENT elif ( k % 3 == 1 ) : NEW_LINE INDENT u . append ( v [ k ] * 15 ) NEW_LINE DEDENT else : NEW_LINE INDENT u . append ( v [ k ] * 10 ) NEW_LINE DEDENT DEDENT u . append ( v [ k ] * 7 ) NEW_LINE u . append ( 7 * 11 ) NEW_LINE u [ 0 ] = u [ 0 ] * 11 NEW_LINE print ( * u ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE printSequence ( n ) NEW_LINE DEDENT |
Midpoint ellipse drawing algorithm | Python3 program for implementing Mid - Point Ellipse Drawing Algorithm ; Initial decision parameter of region 1 ; For region 1 ; Print points based on 4 - way symmetry ; Checking and updating value of decision parameter based on algorithm ; Decision parameter of region 2 ; Plotting points of region 2 ; printing points based on 4 - way symmetry ; Checking and updating parameter value based on algorithm ; To draw a ellipse of major and minor radius 15 , 10 centred at ( 50 , 50 ) | def midptellipse ( rx , ry , xc , yc ) : NEW_LINE INDENT x = 0 ; NEW_LINE y = ry ; NEW_LINE d1 = ( ( ry * ry ) - ( rx * rx * ry ) + ( 0.25 * rx * rx ) ) ; NEW_LINE dx = 2 * ry * ry * x ; NEW_LINE dy = 2 * rx * rx * y ; NEW_LINE while ( dx < dy ) : NEW_LINE INDENT print ( " ( " , x + xc , " , " , y + yc , " ) " ) ; NEW_LINE print ( " ( " , - x + xc , " , " , y + yc , " ) " ) ; NEW_LINE print ( " ( " , x + xc , " , " , - y + yc , " ) " ) ; NEW_LINE print ( " ( " , - x + xc , " , " , - y + yc , " ) " ) ; NEW_LINE if ( d1 < 0 ) : NEW_LINE INDENT x += 1 ; NEW_LINE dx = dx + ( 2 * ry * ry ) ; NEW_LINE d1 = d1 + dx + ( ry * ry ) ; NEW_LINE DEDENT else : NEW_LINE INDENT x += 1 ; NEW_LINE y -= 1 ; NEW_LINE dx = dx + ( 2 * ry * ry ) ; NEW_LINE dy = dy - ( 2 * rx * rx ) ; NEW_LINE d1 = d1 + dx - dy + ( ry * ry ) ; NEW_LINE DEDENT DEDENT d2 = ( ( ( ry * ry ) * ( ( x + 0.5 ) * ( x + 0.5 ) ) ) + ( ( rx * rx ) * ( ( y - 1 ) * ( y - 1 ) ) ) - ( rx * rx * ry * ry ) ) ; NEW_LINE while ( y >= 0 ) : NEW_LINE INDENT print ( " ( " , x + xc , " , " , y + yc , " ) " ) ; NEW_LINE print ( " ( " , - x + xc , " , " , y + yc , " ) " ) ; NEW_LINE print ( " ( " , x + xc , " , " , - y + yc , " ) " ) ; NEW_LINE print ( " ( " , - x + xc , " , " , - y + yc , " ) " ) ; NEW_LINE if ( d2 > 0 ) : NEW_LINE INDENT y -= 1 ; NEW_LINE dy = dy - ( 2 * rx * rx ) ; NEW_LINE d2 = d2 + ( rx * rx ) - dy ; NEW_LINE DEDENT else : NEW_LINE INDENT y -= 1 ; NEW_LINE x += 1 ; NEW_LINE dx = dx + ( 2 * ry * ry ) ; NEW_LINE dy = dy - ( 2 * rx * rx ) ; NEW_LINE d2 = d2 + dx - dy + ( rx * rx ) ; NEW_LINE DEDENT DEDENT DEDENT midptellipse ( 10 , 15 , 50 , 50 ) ; NEW_LINE |
Program to check if a number is divisible by sum of its digits | Function to check if the given number is divisible by sum of its digits ; Find sum of digits ; check if sum of digits divides n ; Driver Code | def isDivisible ( n ) : NEW_LINE INDENT temp = n NEW_LINE sum = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT k = n % 10 ; NEW_LINE sum += k ; NEW_LINE n /= 10 ; NEW_LINE DEDENT if ( temp % sum == 0 ) : NEW_LINE INDENT return " YES " ; NEW_LINE DEDENT return " NO " ; NEW_LINE DEDENT n = 123 ; NEW_LINE print ( isDivisible ( n ) ) ; NEW_LINE |
Program to check if a number is divisible by sum of its digits | Python implementation of above approach ; Converting integer to string ; Initialising sum to 0 ; Traversing through the string ; Converting character to int ; Comparing number and sum ; Driver Code ; passing this number to get result function | def getResult ( n ) : NEW_LINE INDENT st = str ( n ) NEW_LINE sum = 0 NEW_LINE length = len ( st ) NEW_LINE for i in st : NEW_LINE INDENT sum = sum + int ( i ) NEW_LINE DEDENT if ( n % sum == 0 ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT n = 123 NEW_LINE print ( getResult ( n ) ) NEW_LINE |
Find the final X and Y when they are Altering under given condition | Python3 tp implement above approach ; Function to get final value of X and Y ; Following the sequence but by replacing minus with modulo ; Step 1 ; Step 2 ; Step 3 ; Otherwise terminate ; Get the initial X and Y values ; Find the result | import math as mt NEW_LINE def alter ( x , y ) : NEW_LINE INDENT while ( True ) : NEW_LINE INDENT if ( x == 0 or y == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( x >= 2 * y ) : NEW_LINE INDENT x = x % ( 2 * y ) NEW_LINE DEDENT elif ( y >= 2 * x ) : NEW_LINE INDENT y = y % ( 2 * x ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( " X β = " , x , " , β " , " Y β = " , y ) NEW_LINE DEDENT x , y = 12 , 5 NEW_LINE alter ( x , y ) NEW_LINE |
Print all multiplicative primes <= N | Python 3 implementation of the approach ; Function to return the digit product of n ; Function to print all multiplicative primes <= n ; Create a boolean array " prime [ 0 . . n + 1 ] " . 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 ; If i is prime and its digit sum is also prime i . e . i is a multiplicative prime ; Driver code | from math import sqrt NEW_LINE def digitProduct ( n ) : NEW_LINE INDENT prod = 1 NEW_LINE while ( n ) : NEW_LINE INDENT prod = prod * ( n % 10 ) NEW_LINE n = int ( n / 10 ) NEW_LINE DEDENT return prod NEW_LINE DEDENT def printMultiplicativePrimes ( n ) : NEW_LINE INDENT prime = [ True for i in range ( n + 1 ) ] NEW_LINE prime [ 0 ] = prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT if ( prime [ i ] and prime [ digitProduct ( i ) ] ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE printMultiplicativePrimes ( n ) NEW_LINE DEDENT |
Largest number less than or equal to N / 2 which is coprime to N | Python3 implementation of the above approacdh ; Function to calculate gcd of two number ; Function to check if two numbers are coprime or not ; two numbers are coprime if their gcd is 1 ; Function to find largest integer less than or equal to N / 2 and coprime with N ; Check one by one a numbers less than or equal to N / 2 ; Driver code | import math as mt NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( b , a % b ) NEW_LINE DEDENT DEDENT def coPrime ( n1 , n2 ) : NEW_LINE INDENT if ( gcd ( n1 , n2 ) == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def largestCoprime ( N ) : NEW_LINE INDENT half = mt . floor ( N / 2 ) NEW_LINE while ( coPrime ( N , half ) == False ) : NEW_LINE INDENT half -= 1 NEW_LINE DEDENT return half NEW_LINE DEDENT n = 50 NEW_LINE print ( largestCoprime ( n ) ) NEW_LINE |
Largest number less than or equal to N / 2 which is coprime to N | Function to find largest integer less than or equal to N / 2 and is coprime with N ; Handle the case for N = 6 ; Driver code | def largestCoprime ( N ) : NEW_LINE INDENT if N == 6 : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif N % 4 == 0 : NEW_LINE INDENT return N // 2 - 1 NEW_LINE DEDENT elif N % 2 == 0 : NEW_LINE INDENT return N // 2 - 2 NEW_LINE DEDENT else : NEW_LINE INDENT return ( N - 1 ) // 2 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 50 NEW_LINE print ( largestCoprime ( n ) ) NEW_LINE DEDENT |
Print all safe primes below N | Python 3 implementation of the approach ; Function to print first n safe primes ; Initialize all entries of integer array as 1. A value in prime [ i ] will finally be 0 if i is Not a prime , else 1 ; 0 and 1 are not primes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; If i is prime ; 2 p + 1 ; If 2 p + 1 is also a prime then set prime [ 2 p + 1 ] = 2 ; i is a safe prime ; Driver code | from math import sqrt NEW_LINE def printSafePrimes ( n ) : NEW_LINE INDENT prime = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT prime [ i ] = 1 NEW_LINE DEDENT prime [ 0 ] = prime [ 1 ] = 0 NEW_LINE for p in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ p ] == 1 ) : NEW_LINE INDENT for i in range ( p * 2 , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = 0 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT if ( prime [ i ] != 0 ) : NEW_LINE INDENT temp = ( 2 * i ) + 1 NEW_LINE if ( temp <= n and prime [ temp ] != 0 ) : NEW_LINE INDENT prime [ temp ] = 2 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 5 , n + 1 ) : NEW_LINE INDENT if ( prime [ i ] == 2 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 20 NEW_LINE printSafePrimes ( n ) NEW_LINE DEDENT |
Minimum multiplications with { 2 , 3 , 7 } to make two numbers equal | Function to find powers of 2 , 3 and 7 in x ; To keep count of each divisor ; To store the result ; Count powers of 2 in x ; Count powers of 3 in x ; Count powers of 7 in x ; Remaining number which is not divisible by 2 , 3 or 7 ; Function to return the minimum number of given operations required to make a and b equal ; a = x * 2 ^ a1 * 3 ^ a2 * 7 ^ a3 va [ 0 ] = a1 va [ 1 ] = a2 va [ 2 ] = a3 va [ 3 ] = x ; Similarly for b ; If a and b cannot be made equal with the given operation . Note that va [ 3 ] and vb [ 3 ] contain remaining numbers after repeated divisions with 2 , 3 and 7. If remaining numbers are not same then we cannot make them equal . ; Minimum number of operations required ; Driver code | def Divisors ( x ) : NEW_LINE INDENT c = 0 NEW_LINE v = [ ] NEW_LINE while ( x % 2 == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE x /= 2 NEW_LINE DEDENT v . append ( c ) NEW_LINE c = 0 NEW_LINE while ( x % 3 == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE x /= 3 NEW_LINE DEDENT v . append ( c ) NEW_LINE c = 0 NEW_LINE while ( x % 7 == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE x /= 7 NEW_LINE DEDENT v . append ( c ) NEW_LINE v . append ( x ) NEW_LINE return v NEW_LINE DEDENT def MinOperations ( a , b ) : NEW_LINE INDENT va = Divisors ( a ) NEW_LINE vb = Divisors ( b ) NEW_LINE if ( va [ 3 ] != vb [ 3 ] ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT minOperations = abs ( va [ 0 ] - vb [ 0 ] ) + abs ( va [ 1 ] - vb [ 1 ] ) + abs ( va [ 2 ] - vb [ 2 ] ) NEW_LINE return minOperations NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 14 NEW_LINE b = 28 NEW_LINE print ( MinOperations ( a , b ) ) NEW_LINE DEDENT |
Product of N with its largest odd digit | Function to return the largest odd digit in n ; If all digits are even then - 1 will be returned ; Last digit from n ; If current digit is odd and > maxOdd ; Remove last digit ; Return the maximum odd digit ; Function to return the product of n with its largest odd digit ; If there are no odd digits in n ; Product of n with its largest odd digit ; Driver code | def largestOddDigit ( n ) : NEW_LINE INDENT maxOdd = - 1 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit = n % 10 NEW_LINE if ( digit % 2 == 1 and digit > maxOdd ) : NEW_LINE INDENT maxOdd = digit NEW_LINE DEDENT n = n // 10 NEW_LINE DEDENT return maxOdd NEW_LINE DEDENT def getProduct ( n ) : NEW_LINE INDENT maxOdd = largestOddDigit ( n ) NEW_LINE if ( maxOdd == - 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return ( n * maxOdd ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 12345 NEW_LINE print ( getProduct ( n ) ) NEW_LINE DEDENT |
Check if a number is perfect square without finding square root | Program to find if x is a perfect square . ; Check if mid is perfect square ; Mid is small -> go right to increase mid ; Mid is large -> to left to decrease mid ; Driver code ; Function Call | def isPerfectSquare ( x ) : NEW_LINE INDENT left = 1 NEW_LINE right = x NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = ( left + right ) >> 1 NEW_LINE if ( ( mid * mid ) == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( mid * mid < x ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 2500 NEW_LINE if ( isPerfectSquare ( x ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Find k numbers which are powers of 2 and have sum N | Set 1 | function to prnumbers ; Count the number of set bits ; Not - possible condition ; Stores the number ; Get the set bits ; Iterate till we get K elements ; Get the topmost element ; append the elements / 2 into priority queue ; Prall elements ; Driver Code | def printNum ( n , k ) : NEW_LINE INDENT x = 0 NEW_LINE m = n NEW_LINE while ( m ) : NEW_LINE INDENT x += m & 1 NEW_LINE m >>= 1 NEW_LINE DEDENT if k < x or k > n : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT pq = [ ] NEW_LINE two = 1 NEW_LINE while ( n ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT pq . append ( two ) NEW_LINE DEDENT two = two * 2 NEW_LINE n = n >> 1 NEW_LINE DEDENT while ( len ( pq ) < k ) : NEW_LINE INDENT el = pq [ - 1 ] NEW_LINE pq . pop ( ) NEW_LINE pq . append ( el // 2 ) NEW_LINE pq . append ( el // 2 ) NEW_LINE DEDENT ind = 0 NEW_LINE pq . sort ( ) NEW_LINE while ( ind < k ) : NEW_LINE INDENT print ( pq [ - 1 ] , end = " β " ) NEW_LINE pq . pop ( ) NEW_LINE ind += 1 NEW_LINE DEDENT DEDENT n = 9 NEW_LINE k = 4 NEW_LINE printNum ( n , k ) NEW_LINE |
Sum of LCM ( 1 , n ) , LCM ( 2 , n ) , LCM ( 3 , n ) , ... , LCM ( n , n ) | Python3 implementation of the approach ; Euler totient Function ; Function to return the required LCM sum ; Summation of d * ETF ( d ) where d belongs to set of divisors of n ; Driver code | n = 100002 ; NEW_LINE phi = [ 0 ] * ( n + 2 ) ; NEW_LINE ans = [ 0 ] * ( n + 2 ) ; NEW_LINE def ETF ( ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT phi [ i ] = i ; NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( phi [ i ] == i ) : NEW_LINE INDENT phi [ i ] = i - 1 ; NEW_LINE for j in range ( 2 * i , n + 1 , i ) : NEW_LINE INDENT phi [ j ] = ( phi [ j ] * ( i - 1 ) ) // i ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def LcmSum ( m ) : NEW_LINE INDENT ETF ( ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( i , n + 1 , i ) : NEW_LINE INDENT ans [ j ] += ( i * phi [ i ] ) ; NEW_LINE DEDENT DEDENT answer = ans [ m ] ; NEW_LINE answer = ( answer + 1 ) * m ; NEW_LINE answer = answer // 2 ; NEW_LINE return answer ; NEW_LINE DEDENT m = 5 ; NEW_LINE print ( LcmSum ( m ) ) ; NEW_LINE |
Permutations of string such that no two vowels are adjacent | Factorial of a number ; Function to find c ( n , r ) ; Function to count permutations of string such that no two vowels are adjacent ; Finding the frequencies of the characters ; finding the no . of vowels and consonants in given word ; finding places for the vowels ; ways to fill consonants 6 ! / 2 ! ; ways to put vowels 7 C5 x 5 ! ; Driver code | def factorial ( n ) : NEW_LINE INDENT fact = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT fact = fact * i NEW_LINE DEDENT return fact NEW_LINE DEDENT def ncr ( n , r ) : NEW_LINE INDENT return factorial ( n ) // ( factorial ( r ) * factorial ( n - r ) ) NEW_LINE DEDENT def countWays ( string ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE nvowels , nconsonants = 0 , 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT freq [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( i == 0 or i == 4 or i == 8 or i == 14 or i == 20 ) : NEW_LINE INDENT nvowels += freq [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT nconsonants += freq [ i ] NEW_LINE DEDENT DEDENT vplaces = nconsonants + 1 NEW_LINE cways = factorial ( nconsonants ) NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( i != 0 and i != 4 and i != 8 and i != 14 and i != 20 and freq [ i ] > 1 ) : NEW_LINE INDENT cways = cways // factorial ( freq [ i ] ) NEW_LINE DEDENT DEDENT vways = ncr ( vplaces , nvowels ) * factorial ( nvowels ) NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( i == 0 or i == 4 or i == 8 or i == 14 or i == 20 and freq [ i ] > 1 ) : NEW_LINE INDENT vways = vways // factorial ( freq [ i ] ) NEW_LINE DEDENT DEDENT return cways * vways ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " permutation " NEW_LINE print ( countWays ( string ) ) NEW_LINE DEDENT |
Pairs from an array that satisfy the given condition | Function to return the number of set bits in n ; Function to return the count of required pairs ; Set bits for first element of the pair ; Set bits for second element of the pair ; Set bits of the resultant number which is the XOR of both the elements of the pair ; If the condition is satisfied ; Increment the count ; Return the total count ; Driver code | def setBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n = n & ( n - 1 ) NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def countPairs ( a , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n - 1 , 1 ) : NEW_LINE INDENT setbits_x = setBits ( a [ i ] ) NEW_LINE for j in range ( i + 1 , n , 1 ) : NEW_LINE INDENT setbits_y = setBits ( a [ j ] ) NEW_LINE setbits_xor_xy = setBits ( a [ i ] ^ a [ j ] ) ; NEW_LINE if ( setbits_x + setbits_y == setbits_xor_xy ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( countPairs ( a , n ) ) NEW_LINE DEDENT |
Number of array elements derivable from D after performing certain operations | Function to return gcd of a and b ; Function to Return the number of elements of arr [ ] which can be derived from D by performing ( + A , - A , + B , - B ) ; find the gcd of A and B ; counter stores the number of array elements which can be derived from D ; arr [ i ] can be derived from D only if | arr [ i ] - D | is divisible by gcd of A and B ; Driver Code | def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) ; NEW_LINE DEDENT def findPossibleDerivables ( arr , n , D , A , B ) : NEW_LINE INDENT gcdAB = gcd ( A , B ) NEW_LINE counter = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( abs ( arr [ i ] - D ) % gcdAB ) == 0 ) : NEW_LINE INDENT counter += 1 NEW_LINE DEDENT DEDENT return counter NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 7 , 13 ] NEW_LINE n = len ( arr ) NEW_LINE D , A , B = 5 , 4 , 2 NEW_LINE print ( findPossibleDerivables ( arr , n , D , A , B ) ) NEW_LINE a = [ 1 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE D , A , B = 6 , 3 , 2 NEW_LINE print ( findPossibleDerivables ( a , n , D , A , B ) ) NEW_LINE DEDENT |
Find the sum of first N terms of the series 2 * 3 * 5 , 3 * 5 * 7 , 4 * 7 * 9 , ... | Function to return the sum of the first n terms of the given series ; As described in the approach ; Driver Code | def calSum ( n ) : NEW_LINE INDENT return ( n * ( 2 * n * n * n + 12 * n * n + 25 * n + 21 ) ) / 2 ; NEW_LINE DEDENT n = 3 NEW_LINE print ( calSum ( n ) ) NEW_LINE |
Find elements of array using XOR of consecutive elements | Function to find the array elements using XOR of consecutive elements ; array to store the original elements ; first elements a i . e elements [ 0 ] = a ; To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements . e . g . if a ^ b = k1 so to get b xor a both side . b = k1 ^ a ; Printing the original array elements ; Driver code | def getElements ( a , arr , n ) : NEW_LINE INDENT elements = [ 1 for i in range ( n + 1 ) ] NEW_LINE elements [ 0 ] = a NEW_LINE for i in range ( n ) : NEW_LINE INDENT elements [ i + 1 ] = arr [ i ] ^ elements [ i ] NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT print ( elements [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 13 , 2 , 6 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE a = 5 NEW_LINE getElements ( a , arr , n ) NEW_LINE |
Maximum GCD of N integers with given product | Python3 implementation of above approach ; Function to find maximum GCD of N integers with product P ; map to store prime factors of P ; prime factorization of P ; traverse all prime factors and multiply its 1 / N power to the result ; Driver code | from math import sqrt NEW_LINE def maxGCD ( N , P ) : NEW_LINE INDENT ans = 1 NEW_LINE prime_factors = { } NEW_LINE for i in range ( 2 , int ( sqrt ( P ) + 1 ) ) : NEW_LINE INDENT while ( P % i == 0 ) : NEW_LINE INDENT if i not in prime_factors : NEW_LINE INDENT prime_factors [ i ] = 0 NEW_LINE DEDENT prime_factors [ i ] += 1 NEW_LINE P //= i NEW_LINE DEDENT DEDENT if ( P != 1 ) : NEW_LINE INDENT prime_factors [ P ] += 1 NEW_LINE DEDENT for key , value in prime_factors . items ( ) : NEW_LINE INDENT ans *= pow ( key , value // N ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N , P = 3 , 24 NEW_LINE print ( maxGCD ( N , P ) ) NEW_LINE DEDENT |
Check if the sum of distinct digits of two integers are equal | Function to return the sum of distinct digits of a number ; Take last digit ; If digit has not been used before ; Set digit as used ; Remove last digit ; Function to check whether the sum of distinct digits of two numbers are equal ; Driver code | def distinctDigitSum ( n ) : NEW_LINE INDENT used = [ False ] * 10 NEW_LINE sum = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit = n % 10 NEW_LINE if ( not used [ digit ] ) : NEW_LINE INDENT used [ digit ] = True NEW_LINE sum += digit NEW_LINE DEDENT n = n // 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def checkSum ( m , n ) : NEW_LINE INDENT sumM = distinctDigitSum ( m ) NEW_LINE sumN = distinctDigitSum ( n ) NEW_LINE if ( sumM == sumN ) : NEW_LINE INDENT return " YES " NEW_LINE DEDENT return " NO " NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m = 2452 NEW_LINE n = 9222 NEW_LINE print ( checkSum ( m , n ) ) NEW_LINE DEDENT |
All pairs whose xor gives unique prime | Function that returns true if n is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to return the count of valid pairs ; If xor ( a [ i ] , a [ j ] ) is prime and unique ; Driver code | def isPrime ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if n <= 3 : NEW_LINE INDENT return True NEW_LINE DEDENT if n % 2 == 0 or n % 3 == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while i * i <= n : NEW_LINE INDENT if n % i == 0 or n % ( i + 2 ) == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT i += 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def countPairs ( a , n ) : NEW_LINE INDENT count = 0 NEW_LINE m = dict ( ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if isPrime ( a [ i ] ^ a [ j ] ) and m . get ( a [ i ] ^ a [ j ] , 0 ) == 0 : NEW_LINE INDENT m [ ( a [ i ] ^ a [ j ] ) ] = 1 NEW_LINE count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT a = [ 10 , 12 , 23 , 45 , 5 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( countPairs ( a , n ) ) NEW_LINE |
Sum of element whose prime factors are present in array | Python program to find the sum of the elements of an array whose prime factors are present in the same array ; Stores smallest prime factor for every number ; Function to calculate SPF ( Smallest Prime Factor ) for every number till MAXN ; Marking smallest prime factor for every number to be itself . ; Separately marking spf for every even number as 2 ; If i is prime ; Marking SPF for all numbers divisible by i ; Marking spf [ j ] if it is not previously marked ; Function to return the sum of the elements of an array whose prime factors are present in the same array ; Function call to calculate smallest prime factors of all the numbers upto MAXN ; Create map for each element ; If smallest prime factor of num is present in array ; Each factor of arr [ i ] is present in the array ; Driver Code ; Function call to print required answer | from collections import defaultdict NEW_LINE MAXN = 1000001 NEW_LINE MAXN_sqrt = int ( MAXN ** ( 0.5 ) ) NEW_LINE spf = [ None ] * ( MAXN ) NEW_LINE def sieve ( ) : NEW_LINE INDENT spf [ 1 ] = 1 NEW_LINE for i in range ( 2 , MAXN ) : NEW_LINE INDENT spf [ i ] = i NEW_LINE DEDENT for i in range ( 4 , MAXN , 2 ) : NEW_LINE INDENT spf [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , MAXN_sqrt ) : NEW_LINE INDENT if spf [ i ] == i : NEW_LINE INDENT for j in range ( i * i , MAXN , i ) : NEW_LINE INDENT if spf [ j ] == j : NEW_LINE INDENT spf [ j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def sumFactors ( arr , n ) : NEW_LINE INDENT sieve ( ) NEW_LINE Map = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Map [ arr [ i ] ] = 1 NEW_LINE DEDENT Sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT num = arr [ i ] NEW_LINE while num != 1 and Map [ spf [ num ] ] == 1 : NEW_LINE INDENT num = num // spf [ num ] NEW_LINE DEDENT if num == 1 : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE DEDENT DEDENT return Sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 11 , 55 , 25 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE print ( sumFactors ( arr , n ) ) NEW_LINE DEDENT |
Find nth Hermite number | Python 3 program to find nth Hermite number ; Utility function to calculate double factorial of a number ; Function to return nth Hermite number ; If n is even then return 0 ; If n is odd ; Calculate double factorial of ( n - 1 ) and multiply it with 2 ^ ( n / 2 ) ; If n / 2 is odd then nth Hermite number will be negative ; Return nth Hermite number ; Driver Code ; Print nth Hermite number | from math import pow NEW_LINE def doubleFactorial ( n ) : NEW_LINE INDENT fact = 1 NEW_LINE for i in range ( 1 , n + 1 , 2 ) : NEW_LINE INDENT fact = fact * i NEW_LINE DEDENT return fact NEW_LINE DEDENT def hermiteNumber ( n ) : NEW_LINE INDENT if ( n % 2 == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT number = ( ( pow ( 2 , n / 2 ) ) * doubleFactorial ( n - 1 ) ) NEW_LINE if ( ( n / 2 ) % 2 == 1 ) : NEW_LINE INDENT number = number * - 1 NEW_LINE DEDENT return number NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE print ( int ( hermiteNumber ( n ) ) ) NEW_LINE DEDENT |
Count numbers in a range having GCD of powers of prime factors equal to 1 | Python3 implementation of the approach ; Vector to store powers greater than 3 ; Set to store perfect squares ; Set to store powers other than perfect squares ; Pushing squares ; if the values is already a perfect square means present in the set ; Run loop until some power of current number doesn 't exceed MAX ; Pushing only odd powers as even power of a number can always be expressed as a perfect square which is already present in set squares ; Inserting those sorted values of set into a vector ; Precompute the powers ; Calculate perfect squares in range using sqrtl function ; Calculate upper value of R in vector using binary search ; Calculate lower value of L in vector using binary search ; Calculate perfect powers ; Compute final answer ; Driver Code | from bisect import bisect as upper_bound NEW_LINE from bisect import bisect_left as lower_bound NEW_LINE from math import floor NEW_LINE N = 1000005 NEW_LINE MAX = 10 ** 18 NEW_LINE powers = [ ] NEW_LINE squares = dict ( ) NEW_LINE s = dict ( ) NEW_LINE def powersPrecomputation ( ) : NEW_LINE INDENT for i in range ( 2 , N ) : NEW_LINE INDENT squares [ i * i ] = 1 NEW_LINE if ( i not in squares . keys ( ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT temp = i NEW_LINE while ( i * i <= ( MAX // temp ) ) : NEW_LINE INDENT temp *= ( i * i ) NEW_LINE s [ temp ] = 1 NEW_LINE DEDENT DEDENT for x in s : NEW_LINE INDENT powers . append ( x ) NEW_LINE DEDENT DEDENT def calculateAnswer ( L , R ) : NEW_LINE INDENT powersPrecomputation ( ) NEW_LINE perfectSquares = floor ( ( R ) ** ( .5 ) ) - floor ( ( L - 1 ) ** ( .5 ) ) NEW_LINE high = upper_bound ( powers , R ) NEW_LINE low = lower_bound ( powers , L ) NEW_LINE perfectPowers = perfectSquares + ( high - low ) NEW_LINE ans = ( R - L + 1 ) - perfectPowers NEW_LINE return ans NEW_LINE DEDENT L = 13 NEW_LINE R = 20 NEW_LINE print ( calculateAnswer ( L , R ) ) NEW_LINE |
Sum of integers upto N with given unit digit | Function to return the required sum ; If the unit digit is d ; Driver code | def getSum ( n , d ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( i % 10 == d ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , d = 30 , 3 NEW_LINE print ( getSum ( n , d ) ) NEW_LINE DEDENT |
Split a number into 3 parts such that none of the parts is divisible by 3 | Python3 program to split a number into three parts such than none of them is divisible by 3. ; Print x = 1 , y = 1 and z = N - 2 ; Otherwise , print x = 1 , y = 2 and z = N - 3 ; Driver code | def printThreeParts ( N ) : NEW_LINE INDENT if ( N % 3 == 0 ) : NEW_LINE INDENT print ( " β x β = β 1 , β y β = β 1 , β z β = β " , N - 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " β x β = β 1 , β y β = β 2 , β z β = β " , N - 3 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 10 NEW_LINE printThreeParts ( N ) NEW_LINE DEDENT |
Minimum absolute difference of a number and its closest prime | Python 3 program to find the minimum absolute difference between a number and its closest prime ; Function to check if a number is prime or not ; Function to find the minimum absolute difference between a number and its closest prime ; Variables to store first prime above and below N ; Finding first prime number greater than N ; Finding first prime number less than N ; Variables to store the differences ; Driver code | from math import sqrt NEW_LINE def isPrime ( N ) : NEW_LINE INDENT k = int ( sqrt ( N ) ) + 1 NEW_LINE for i in range ( 2 , k , 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def getDifference ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT elif ( N == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( isPrime ( N ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT aboveN = - 1 NEW_LINE belowN = - 1 NEW_LINE n1 = N + 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( isPrime ( n1 ) ) : NEW_LINE INDENT aboveN = n1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT n1 += 1 NEW_LINE DEDENT DEDENT n1 = N - 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( isPrime ( n1 ) ) : NEW_LINE INDENT belowN = n1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT n1 -= 1 NEW_LINE DEDENT DEDENT diff1 = aboveN - N NEW_LINE diff2 = N - belowN NEW_LINE return min ( diff1 , diff2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 25 NEW_LINE print ( getDifference ( N ) ) NEW_LINE DEDENT |
Check if the sum of perfect squares in an array is divisible by x | Python3 implementation of the approach ; Function that returns true if the the sum of all the perfect squares of the given array is divisible by x ; If a [ i ] is a perfect square ; Driver code | import math NEW_LINE def check ( a , y ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT x = math . sqrt ( a [ i ] ) NEW_LINE if ( math . floor ( x ) == math . ceil ( x ) ) : NEW_LINE INDENT sum = sum + a [ i ] NEW_LINE DEDENT DEDENT if ( sum % y == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT a = [ 2 , 3 , 4 , 9 , 10 ] NEW_LINE x = 13 NEW_LINE if check ( a , x ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Largest Divisor of a Number not divisible by a perfect square | Python3 Program to find the largest divisor not divisible by any perfect square greater than 1 ; Function to find the largest divisor not divisible by any perfect square greater than 1 ; set to store divisors in descending order ; If the number is divisible by i , then insert it ; Vector to store perfect squares ; Check for each divisor , if it is not divisible by any perfect square , simply return it as the answer . ; Driver Code | MAX = 10 ** 5 NEW_LINE def findLargestDivisor ( n ) : NEW_LINE INDENT m = n NEW_LINE s = set ( ) NEW_LINE s . add ( 1 ) NEW_LINE s . add ( n ) NEW_LINE for i in range ( 2 , int ( n ** ( 0.5 ) ) + 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT s . add ( n // i ) NEW_LINE s . add ( i ) NEW_LINE while m % i == 0 : NEW_LINE INDENT m //= i NEW_LINE DEDENT DEDENT DEDENT if m > 1 : NEW_LINE INDENT s . add ( m ) NEW_LINE DEDENT vec = [ i ** 2 for i in range ( 2 , MAX + 1 ) ] NEW_LINE for d in sorted ( s , reverse = True ) : NEW_LINE INDENT divi , j = 0 , 0 NEW_LINE while j < len ( vec ) and vec [ j ] <= d : NEW_LINE INDENT if d % vec [ j ] == 0 : NEW_LINE INDENT divi = 1 NEW_LINE break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if not divi : NEW_LINE INDENT return d NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 12 NEW_LINE print ( findLargestDivisor ( n ) ) NEW_LINE n = 97 NEW_LINE print ( findLargestDivisor ( n ) ) NEW_LINE DEDENT |
Find the Number of Maximum Product Quadruples | Python3 program to find the number of Quadruples having maximum product ; Returns the number of ways to select r objects out of available n choices ; ncr = ( n * ( n - 1 ) * ( n - 2 ) * ... . . ... ( n - r + 1 ) ) / ( r * ( r - 1 ) * ... * 1 ) ; Returns the number of quadruples having maximum product ; stores the frequency of each element ; remaining_choices denotes the remaining elements to select inorder to form quadruple ; traverse the elements of the map in reverse order ; If Frequency of element < remaining choices , select all of these elements , else select only the number of elements required ; Decrement remaining_choices acc to the number of the current elements selected ; if the quadruple is formed stop the algorithm ; Driver Code | from collections import defaultdict NEW_LINE def NCR ( n , r ) : NEW_LINE INDENT numerator = 1 NEW_LINE denominator = 1 NEW_LINE while ( r > 0 ) : NEW_LINE INDENT numerator *= n NEW_LINE denominator *= r NEW_LINE n -= 1 NEW_LINE r -= 1 NEW_LINE DEDENT return ( numerator // denominator ) NEW_LINE DEDENT def findWays ( arr , n ) : NEW_LINE INDENT count = defaultdict ( int ) NEW_LINE if ( n < 4 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT remaining_choices = 4 NEW_LINE ans = 1 NEW_LINE for it in reversed ( sorted ( count . keys ( ) ) ) : NEW_LINE INDENT number = it NEW_LINE frequency = count [ it ] NEW_LINE toSelect = min ( remaining_choices , frequency ) NEW_LINE ans = ans * NCR ( frequency , toSelect ) NEW_LINE remaining_choices -= toSelect NEW_LINE if ( not remaining_choices ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 3 , 3 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE maxQuadrupleWays = findWays ( arr , n ) NEW_LINE print ( maxQuadrupleWays ) NEW_LINE DEDENT |
Minimum and Maximum number of pairs in m teams of n people | Python3 program to find minimum and maximum no . of pairs ; Driver code | from math import ceil NEW_LINE def MinimumMaximumPairs ( n , m ) : NEW_LINE INDENT max_pairs = ( ( n - m + 1 ) * ( n - m ) ) // 2 ; NEW_LINE min_pairs = ( m * ( ( ( n - m ) // m + 1 ) * ( ( n - m ) // m ) ) // 2 + ceil ( ( n - m ) / ( m ) ) * ( ( n - m ) % m ) ) NEW_LINE print ( " Minimum β no . β of β pairs β = β " , min_pairs ) NEW_LINE print ( " Maximum β no . β of β pairs β = β " , max_pairs ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , m = 5 , 2 NEW_LINE MinimumMaximumPairs ( n , m ) NEW_LINE DEDENT |
Larger of a ^ b or b ^ a ( a raised to power b or b raised to power a ) | Python 3 code for finding greater between the a ^ b and b ^ a ; Function to find the greater value ; Driver code | import math NEW_LINE def findGreater ( a , b ) : NEW_LINE INDENT x = a * ( math . log ( b ) ) ; NEW_LINE y = b * ( math . log ( a ) ) ; NEW_LINE if ( y > x ) : NEW_LINE INDENT print ( " a ^ b β is β greater " ) ; NEW_LINE DEDENT elif ( y < x ) : NEW_LINE INDENT print ( " b ^ a β is β greater " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Both β are β equal " ) ; NEW_LINE DEDENT DEDENT a = 3 ; NEW_LINE b = 5 ; NEW_LINE c = 2 ; NEW_LINE d = 4 ; NEW_LINE findGreater ( a , b ) ; NEW_LINE findGreater ( c , d ) ; NEW_LINE |
Expressing a fraction as a natural number under modulo ' m ' | Python3 implementation of the approach ; Function to return the GCD of given numbers ; Recursive function to return ( x ^ n ) % m ; Function to return the fraction modulo mod ; ( b ^ m - 2 ) % m ; Final answer ; Driver code | m = 1000000007 NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def modexp ( x , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( n % 2 == 0 ) : NEW_LINE INDENT return modexp ( ( x * x ) % m , n // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( x * modexp ( ( x * x ) % m , ( n - 1 ) / 2 ) % m ) NEW_LINE DEDENT DEDENT def getFractionModulo ( a , b ) : NEW_LINE INDENT c = gcd ( a , b ) NEW_LINE a = a // c NEW_LINE b = b // c NEW_LINE d = modexp ( b , m - 2 ) NEW_LINE ans = ( ( a % m ) * ( d % m ) ) % m NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 2 NEW_LINE b = 6 NEW_LINE print ( getFractionModulo ( a , b ) ) NEW_LINE DEDENT |
Find sum of a number and its maximum prime factor | Python 3 program to find sum of n and it 's largest prime factor ; Function to return the sum of n and it 's largest prime factor ; Initialise maxPrime to - 1. ; n must be odd at this point , thus skip the even numbers and iterate only odd numbers ; This condition is to handle the case when n is a prime number greater than 2 ; finally return the sum . ; Driver Code | from math import sqrt NEW_LINE def maxPrimeFactors ( n ) : NEW_LINE INDENT num = n NEW_LINE maxPrime = - 1 ; NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT maxPrime = 2 NEW_LINE n = n / 2 NEW_LINE DEDENT p = int ( sqrt ( n ) + 1 ) NEW_LINE for i in range ( 3 , p , 2 ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT maxPrime = i NEW_LINE n = n / i NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT maxPrime = n NEW_LINE DEDENT sum = maxPrime + num NEW_LINE return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 19 NEW_LINE print ( maxPrimeFactors ( n ) ) NEW_LINE DEDENT |
Largest number less than N with digit sum greater than the digit sum of N | Function to return the sum of the digits of n ; Loop for each digit of the number ; Function to return the greatest number less than n such that the sum of its digits is greater than the sum of the digits of n ; Starting from n - 1 ; Check until 1 ; If i satisfies the given condition ; If the condition is not satisfied ; Driver code | def sumOfDigits ( n ) : NEW_LINE INDENT res = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT res += n % 10 NEW_LINE n /= 10 NEW_LINE DEDENT return res ; NEW_LINE DEDENT def findNumber ( n ) : NEW_LINE INDENT i = n - 1 ; NEW_LINE while ( i > 0 ) : NEW_LINE INDENT if ( sumOfDigits ( i ) > sumOfDigits ( n ) ) : NEW_LINE INDENT return i NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 824 ; NEW_LINE print ( findNumber ( n ) ) NEW_LINE DEDENT |
Find the Nth term of the series 14 , 28 , 20 , 40 , ... . . | Function to find the N - th term ; initializing the 1 st number ; loop from 2 nd term to nth term ; if i is even , double the previous number ; if i is odd , subtract 8 from previous number ; Driver Code | def findNth ( N ) : NEW_LINE INDENT b = 14 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT b = b * 2 NEW_LINE DEDENT else : NEW_LINE INDENT b = b - 8 NEW_LINE DEDENT DEDENT return b NEW_LINE DEDENT N = 6 NEW_LINE print ( findNth ( N ) ) NEW_LINE |
Problem of 8 Neighbours of an element in a 2 | Dimension of Array ; Count of 1 s ; Counting all neighbouring 1 s ; Comparing the number of neighbouring 1 s with given ranges ; Copying changes to the main matrix ; Driver code ; Function call to calculate the resultant matrix after ' K ' iterations . ; Printing Result | N = 4 NEW_LINE def predictMatrix ( arr , range1a , range1b , range0a , range0b , K , b ) : NEW_LINE INDENT c = 0 NEW_LINE while ( K ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT c = 0 NEW_LINE if ( i > 0 and arr [ i - 1 ] [ j ] == 1 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( j > 0 and arr [ i ] [ j - 1 ] == 1 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( i > 0 and j > 0 and arr [ i - 1 ] [ j - 1 ] == 1 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( i < N - 1 and arr [ i + 1 ] [ j ] == 1 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( j < N - 1 and arr [ i ] [ j + 1 ] == 1 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( i < N - 1 and j < N - 1 and arr [ i + 1 ] [ j + 1 ] == 1 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( i < N - 1 and j > 0 and arr [ i + 1 ] [ j - 1 ] == 1 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( i > 0 and j < N - 1 and arr [ i - 1 ] [ j + 1 ] == 1 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( arr [ i ] [ j ] == 1 ) : NEW_LINE INDENT if ( c >= range1a and c <= range1b ) : NEW_LINE INDENT b [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT b [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT if ( arr [ i ] [ j ] == 0 ) : NEW_LINE INDENT if ( c >= range0a and c <= range0b ) : NEW_LINE INDENT b [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT b [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT DEDENT K -= 1 NEW_LINE for k in range ( N ) : NEW_LINE INDENT for m in range ( N ) : NEW_LINE INDENT arr [ k ] [ m ] = b [ k ] [ m ] NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 0 , 0 , 0 , 0 ] , [ 0 , 1 , 1 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 1 , 0 , 1 ] ] NEW_LINE range1a = 2 NEW_LINE range1b = 2 NEW_LINE range0a = 2 NEW_LINE range0b = 3 NEW_LINE K = 3 NEW_LINE b = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE predictMatrix ( arr , range1a , range1b , range0a , range0b , K , b ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( ) NEW_LINE for j in range ( N ) : NEW_LINE INDENT print ( b [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT |
Number of moves required to guess a permutation . | Function that returns the required moves ; Final move ; Driver Code | def countMoves ( n ) : NEW_LINE INDENT ct = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ct += i * ( n - i ) NEW_LINE DEDENT ct += n NEW_LINE return ct NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE print ( countMoves ( n ) ) NEW_LINE DEDENT |
Count number of triplets ( a , b , c ) such that a ^ 2 + b ^ 2 = c ^ 2 and 1 <= a <= b <= c <= n | Python3 implementation of the approach ; Function to return an ArrayList containing all the perfect squares upto n ; while current perfect square is less than or equal to n ; Function to return the count of triplet ( a , b , c ) pairs such that a ^ 2 + b ^ 2 = c ^ 2 and 1 <= a <= b <= c <= n ; List of perfect squares upto n ^ 2 ; Since , a ^ 2 + b ^ 2 = c ^ 2 ; If c < a or bSquare is not a perfect square ; If triplet pair ( a , b , c ) satisfy the given condition ; Driver code | import math NEW_LINE def getPerfectSquares ( n ) : NEW_LINE INDENT perfectSquares = [ ] NEW_LINE current = 1 NEW_LINE i = 1 NEW_LINE while ( current <= n ) : NEW_LINE INDENT perfectSquares . append ( current ) NEW_LINE i += 1 NEW_LINE current = i ** 2 NEW_LINE DEDENT return perfectSquares NEW_LINE DEDENT def countTriplets ( n ) : NEW_LINE INDENT perfectSquares = getPerfectSquares ( n ** 2 ) NEW_LINE count = 0 NEW_LINE for a in range ( 1 , n + 1 ) : NEW_LINE INDENT aSquare = a ** 2 NEW_LINE for i in range ( len ( perfectSquares ) ) : NEW_LINE INDENT cSquare = perfectSquares [ i ] NEW_LINE bSquare = abs ( cSquare - aSquare ) NEW_LINE b = math . sqrt ( bSquare ) NEW_LINE b = int ( b ) NEW_LINE c = math . sqrt ( cSquare ) NEW_LINE c = int ( c ) NEW_LINE if ( c < a or ( bSquare not in perfectSquares ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( ( b >= a ) and ( b <= c ) and ( aSquare + bSquare == cSquare ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 NEW_LINE print ( countTriplets ( n ) ) NEW_LINE DEDENT |
Count Numbers with N digits which consists of even number of 0 β s | Function to count Numbers with N digits which consists of odd number of 0 's ; Driver code | def countNumber ( n ) : NEW_LINE INDENT return ( pow ( 10 , n ) - 1 ) - ( pow ( 10 , n ) - pow ( 8 , n ) ) // 2 NEW_LINE DEDENT n = 2 NEW_LINE print ( countNumber ( n ) ) NEW_LINE |
Find determinant of matrix generated by array rotation | Function to calculate determinant ; Driver code | def calcDeterminant ( arr , n ) : NEW_LINE INDENT determinant = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT determinant += pow ( arr [ i ] , 3 ) NEW_LINE DEDENT determinant -= 3 * arr [ 0 ] * arr [ 1 ] * arr [ 2 ] NEW_LINE return determinant NEW_LINE DEDENT arr = [ 4 , 5 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( calcDeterminant ( arr , n ) ) NEW_LINE |
Minimum elements to be added in a range so that count of elements is divisible by K | Python 3 implementation of the approach ; Total elements in the range ; If total elements are already divisible by k ; Value that must be added to count in order to make it divisible by k ; Driver Program to test above function | def minimumMoves ( k , l , r ) : NEW_LINE INDENT count = r - l + 1 NEW_LINE if ( count % k == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( k - ( count % k ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 3 NEW_LINE l = 10 NEW_LINE r = 10 NEW_LINE print ( minimumMoves ( k , l , r ) ) NEW_LINE DEDENT |
Sum of all even numbers in range L and R | Function to return the sum of all natural numbers ; Function to return sum of even numbers in range L and R ; Driver Code | def sumNatural ( n ) : NEW_LINE INDENT sum = ( n * ( n + 1 ) ) NEW_LINE return int ( sum ) NEW_LINE DEDENT def sumEven ( l , r ) : NEW_LINE INDENT return ( sumNatural ( int ( r / 2 ) ) - sumNatural ( int ( ( l - 1 ) / 2 ) ) ) NEW_LINE DEDENT l , r = 2 , 5 NEW_LINE print ( " Sum β of β Natural β numbers " , " from β L β to β R β is " , sumEven ( l , r ) ) NEW_LINE |
Check if N is divisible by a number which is composed of the digits from the set { A , B } | Function to check whether n is divisible by a number whose digits are either a or b ; base condition ; recursive call ; Check for all numbers beginning with ' a ' or 'b ; Driver Code | def isDivisibleRec ( x , a , b , n ) : NEW_LINE INDENT if ( x > n ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n % x == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return ( isDivisibleRec ( x * 10 + a , a , b , n ) or isDivisibleRec ( x * 10 + b , a , b , n ) ) NEW_LINE DEDENT def isDivisible ( a , b , n ) : NEW_LINE ' NEW_LINE INDENT return ( isDivisibleRec ( a , a , b , n ) or isDivisibleRec ( b , a , b , n ) ) NEW_LINE DEDENT a = 3 ; b = 5 ; n = 53 ; NEW_LINE if ( isDivisible ( a , b , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Minimum number of moves required to reach the destination by the king in a chess board | function to Find the minimum number of moves required to reach the destination by the king in a chess board ; minimum number of steps ; while the king is not in the same row or column as the destination ; Go up ; Go down ; Go left ; Go right ; Driver code | def MinSteps ( SourceX , SourceY , DestX , DestY ) : NEW_LINE INDENT print ( max ( abs ( SourceX - DestX ) , abs ( SourceY - DestY ) ) ) NEW_LINE while ( ( SourceX != DestX ) or ( SourceY != DestY ) ) : NEW_LINE INDENT if ( SourceX < DestX ) : NEW_LINE INDENT print ( ' U ' , end = " " ) NEW_LINE SourceX += 1 NEW_LINE DEDENT if ( SourceX > DestX ) : NEW_LINE INDENT print ( ' D ' , end = " " ) NEW_LINE SourceX -= 1 NEW_LINE DEDENT if ( SourceY > DestY ) : NEW_LINE INDENT print ( ' L ' ) NEW_LINE SourceY -= 1 NEW_LINE DEDENT if ( SourceY < DestY ) : NEW_LINE INDENT print ( ' R ' , end = " " ) NEW_LINE SourceY += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT sourceX = 4 NEW_LINE sourceY = 4 NEW_LINE destinationX = 7 NEW_LINE destinationY = 0 NEW_LINE MinSteps ( sourceX , sourceY , destinationX , destinationY ) NEW_LINE DEDENT |
Count of pairs in an array whose sum is a perfect square | Function to return an ArrayList containing all the perfect squares upto n ; while current perfect square is less than or equal to n ; Function to print the sum of maximum two elements from the array ; Function to return the count of numbers that when added with n give a perfect square ; temp > n is checked so that pairs ( x , y ) and ( y , x ) don 't get counted twice ; Function to count the pairs whose sum is a perfect square ; Sum of the maximum two elements from the array ; List of perfect squares upto max ; Contains all the array elements ; Add count of the elements that when added with arr [ i ] give a perfect square ; Driver code | def getPerfectSquares ( n ) : NEW_LINE INDENT perfectSquares = [ ] ; NEW_LINE current = 1 ; NEW_LINE i = 1 ; NEW_LINE while ( current <= n ) : NEW_LINE INDENT perfectSquares . append ( current ) ; NEW_LINE i += 1 ; NEW_LINE current = int ( pow ( i , 2 ) ) ; NEW_LINE DEDENT return perfectSquares ; NEW_LINE DEDENT def maxPairSum ( arr ) : NEW_LINE INDENT n = len ( arr ) ; NEW_LINE max = 0 ; NEW_LINE secondMax = 0 ; NEW_LINE if ( arr [ 0 ] > arr [ 1 ] ) : NEW_LINE INDENT max = arr [ 0 ] ; NEW_LINE secondMax = arr [ 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT max = arr [ 1 ] ; NEW_LINE secondMax = arr [ 0 ] ; NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT if ( arr [ i ] > max ) : NEW_LINE INDENT secondMax = max ; NEW_LINE max = arr [ i ] ; NEW_LINE DEDENT elif ( arr [ i ] > secondMax ) : NEW_LINE INDENT secondMax = arr [ i ] ; NEW_LINE DEDENT DEDENT return ( max + secondMax ) ; NEW_LINE DEDENT def countPairsWith ( n , perfectSquares , nums ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( len ( perfectSquares ) ) : NEW_LINE INDENT temp = perfectSquares [ i ] - n ; NEW_LINE if ( temp > n and ( temp in nums ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT def countPairs ( arr ) : NEW_LINE INDENT n = len ( arr ) ; NEW_LINE max = maxPairSum ( arr ) ; NEW_LINE perfectSquares = getPerfectSquares ( max ) ; NEW_LINE nums = [ ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT nums . append ( arr [ i ] ) ; NEW_LINE DEDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT count += countPairsWith ( arr [ i ] , perfectSquares , nums ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT arr = [ 2 , 3 , 6 , 9 , 10 , 20 ] ; NEW_LINE print ( countPairs ( arr ) ) ; NEW_LINE |
Element equal to the sum of all the remaining elements | Function to find the element ; sum is use to store sum of all elements of array ; iterate over all elements ; Driver Code | def findEle ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] == sum - arr [ i ] : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findEle ( arr , n ) ) NEW_LINE DEDENT |
Sum of all natural numbers in range L to R | Function to return the sum of all natural numbers ; Function to return the sum of all numbers in range L and R ; Driver Code | def sumNatural ( n ) : NEW_LINE INDENT sum = ( n * ( n + 1 ) ) // 2 NEW_LINE return sum NEW_LINE DEDENT def suminRange ( l , r ) : NEW_LINE INDENT return sumNatural ( r ) - sumNatural ( l - 1 ) NEW_LINE DEDENT l = 2 ; r = 5 NEW_LINE print ( " Sum β of β Natural β numbers β from β L β to β R β is β " , suminRange ( l , r ) ) NEW_LINE |
Check if a large number is divisible by 75 or not | check divisibleBy3 ; to store sum of Digit ; traversing through each digit ; summing up Digit ; check if sumOfDigit is divisibleBy3 ; check divisibleBy25 ; if a single digit number ; length of the number ; taking the last two digit ; checking if the lastTwo digit is divisibleBy25 ; Function to check divisibleBy75 or not ; check if divisibleBy3 and divisibleBy25 ; Driver Code ; divisible ; if divisibleBy75 | def divisibleBy3 ( number ) : NEW_LINE INDENT sumOfDigit = 0 NEW_LINE for i in range ( 0 , len ( number ) , 1 ) : NEW_LINE INDENT sumOfDigit += ord ( number [ i ] ) - ord ( '0' ) NEW_LINE DEDENT if ( sumOfDigit % 3 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def divisibleBy25 ( number ) : NEW_LINE INDENT if ( len ( number ) < 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT length = len ( number ) NEW_LINE lastTwo = ( ( ord ( number [ length - 2 ] ) - ord ( '0' ) ) * 10 + ( ord ( number [ length - 1 ] ) - ord ( '0' ) ) ) NEW_LINE if ( lastTwo % 25 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def divisibleBy75 ( number ) : NEW_LINE INDENT if ( divisibleBy3 ( number ) and divisibleBy25 ( number ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT number = "754586672150" NEW_LINE divisible = divisibleBy75 ( number ) NEW_LINE if ( divisible ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Find the other number when LCM and HCF given | Function that will calculates the zeroes at the end ; Driver code ; Calling function | def otherNumber ( a , Lcm , Hcf ) : NEW_LINE INDENT return ( Lcm * Hcf ) // A NEW_LINE DEDENT A = 8 ; Lcm = 8 ; Hcf = 1 NEW_LINE result = otherNumber ( A , Lcm , Hcf ) NEW_LINE print ( " B β = " , result ) NEW_LINE |
Overall percentage change from successive changes | Python implementation of above approach ; Calculate successive change of 1 st 2 change ; Calculate successive change for rest of the value ; Driver code ; Calling function | def successiveChange ( arr , N ) : NEW_LINE INDENT result = 0 ; NEW_LINE var1 = arr [ 0 ] ; NEW_LINE var2 = arr [ 1 ] ; NEW_LINE result = float ( var1 + var2 + ( float ( var1 * var2 ) / 100 ) ) ; NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT result = ( result + arr [ i ] + ( float ( result * arr [ i ] ) / 100 ) ) ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT arr = [ 10 , 20 , 30 , 10 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE result = successiveChange ( arr , N ) ; NEW_LINE print ( " Percentage β change β is β = β % .2f " % ( result ) , " % " ) ; NEW_LINE |
Minimum numbers ( smaller than or equal to N ) with sum S | Function to find the minimum numbers required to get to S ; Driver Code | def minimumNumbers ( n , s ) : NEW_LINE INDENT if ( s % n ) : NEW_LINE INDENT return s / n + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return s / n ; NEW_LINE DEDENT DEDENT n = 5 ; NEW_LINE s = 11 ; NEW_LINE print ( int ( minimumNumbers ( n , s ) ) ) ; NEW_LINE |
Sum of multiples of A and B less than N | Python 3 program to find the sum of all multiples of A and B below N ; Function to find sum of AP series ; Number of terms ; Function to find the sum of all multiples of A and B below N ; Since , we need the sum of multiples less than N ; common factors of A and B ; Driver code | from math import gcd , sqrt NEW_LINE def sumAP ( n , d ) : NEW_LINE INDENT n = int ( n / d ) NEW_LINE return ( n ) * ( 1 + n ) * d / 2 NEW_LINE DEDENT def sumMultiples ( A , B , n ) : NEW_LINE INDENT n -= 1 NEW_LINE common = int ( ( A * B ) / gcd ( A , B ) ) NEW_LINE return ( sumAP ( n , A ) + sumAP ( n , B ) - sumAP ( n , common ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 100 NEW_LINE A = 5 NEW_LINE B = 10 NEW_LINE print ( " Sum β = " , int ( sumMultiples ( A , B , n ) ) ) NEW_LINE DEDENT |
Check if a prime number can be expressed as sum of two Prime Numbers | Python3 program to check if a prime number can be expressed as sum of two Prime Numbers ; Function to check whether a number is prime or not ; Function to check if a prime number can be expressed as sum of two Prime Numbers ; if the number is prime , and number - 2 is also prime ; Driver code | import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if n == 2 : NEW_LINE INDENT return True NEW_LINE DEDENT if n % 2 == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isPossible ( n ) : NEW_LINE INDENT if isPrime ( n ) and isPrime ( n - 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = 13 NEW_LINE if isPossible ( n ) == True : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Count pairs from two arrays whose modulo operation yields K | Function to return the total pairs of elements whose modulo yield K ; set is used to avoid duplicate pairs ; check which element is greater and proceed according to it ; check if modulo is equal to K ; return size of the set ; Driver code | def totalPairs ( arr1 , arr2 , K , n , m ) : NEW_LINE INDENT s = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( arr1 [ i ] > arr2 [ j ] ) : NEW_LINE INDENT if ( arr1 [ i ] % arr2 [ j ] == K ) : NEW_LINE INDENT s [ ( arr1 [ i ] , arr2 [ j ] ) ] = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( arr2 [ j ] % arr1 [ i ] == K ) : NEW_LINE INDENT s [ ( arr2 [ j ] , arr1 [ i ] ) ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return len ( s ) NEW_LINE DEDENT arr1 = [ 8 , 3 , 7 , 50 ] NEW_LINE arr2 = [ 5 , 1 , 10 , 4 ] NEW_LINE K = 3 NEW_LINE n = len ( arr1 ) NEW_LINE m = len ( arr2 ) NEW_LINE print ( totalPairs ( arr1 , arr2 , K , n , m ) ) NEW_LINE |
Largest sub | Python 3 program to find the length of the largest sub - array of an array every element of whose is a perfect square ; function to return the length of the largest sub - array of an array every element of whose is a perfect square ; if both a and b are equal then arr [ i ] is a perfect square ; Driver code | from math import sqrt NEW_LINE def contiguousPerfectSquare ( arr , n ) : NEW_LINE INDENT current_length = 0 NEW_LINE max_length = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT b = sqrt ( arr [ i ] ) NEW_LINE a = int ( b ) NEW_LINE if ( a == b ) : NEW_LINE INDENT current_length += 1 NEW_LINE DEDENT else : NEW_LINE INDENT current_length = 0 NEW_LINE DEDENT max_length = max ( max_length , current_length ) NEW_LINE DEDENT return max_length NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 75 , 4 , 64 , 121 , 25 ] NEW_LINE n = len ( arr ) NEW_LINE print ( contiguousPerfectSquare ( arr , n ) ) NEW_LINE DEDENT |
Count pairs of numbers from 1 to N with Product divisible by their Sum | Function to count pairs ; variable to store count ; Generate all possible pairs such that 1 <= x < y < n ; Driver code | def countPairs ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for x in range ( 1 , n ) : NEW_LINE INDENT for y in range ( x + 1 , n + 1 ) : NEW_LINE INDENT if ( ( y * x ) % ( y + x ) == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT n = 15 NEW_LINE print ( countPairs ( n ) ) NEW_LINE |
Find the index of the left pointer after possible moves in the array | Function that returns the index of the left pointer ; there 's only one element in the array ; initially both are at end ; Driver code | def getIndex ( a , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ptrL = 0 NEW_LINE ptrR = n - 1 NEW_LINE sumL = a [ 0 ] NEW_LINE sumR = a [ n - 1 ] NEW_LINE while ( ptrR - ptrL > 1 ) : NEW_LINE INDENT if ( sumL < sumR ) : NEW_LINE INDENT ptrL += 1 NEW_LINE sumL += a [ ptrL ] NEW_LINE DEDENT elif ( sumL > sumR ) : NEW_LINE INDENT ptrR -= 1 NEW_LINE sumR += a [ ptrR ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ptrL NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 7 , 9 , 8 , 7 ] NEW_LINE n = len ( a ) NEW_LINE print ( getIndex ( a , n ) ) NEW_LINE DEDENT |
Find the position of the last removed element from the array | Python3 program to find the position of the last removed element from the array ; Function to find the original position of the element which will be removed last ; take ceil of every number ; Since position is index + 1 ; Driver code | import math as mt NEW_LINE def getPosition ( a , n , m ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT a [ i ] = ( a [ i ] // m + ( a [ i ] % m != 0 ) ) NEW_LINE DEDENT ans , maxx = - 1 , - 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( maxx < a [ i ] ) : NEW_LINE INDENT maxx = a [ i ] NEW_LINE ans = i NEW_LINE DEDENT DEDENT return ans + 1 NEW_LINE DEDENT a = [ 2 , 5 , 4 ] NEW_LINE n = len ( a ) NEW_LINE m = 2 NEW_LINE print ( getPosition ( a , n , m ) ) NEW_LINE |
Find the value of f ( n ) / f ( r ) * f ( n | Function to find value of given F ( n ) ; iterate over n ; calculate result ; return the result ; Driver code | def calcFunction ( n , r ) : NEW_LINE INDENT finalDenominator = 1 NEW_LINE mx = max ( r , n - r ) NEW_LINE for i in range ( mx + 1 , n + 1 ) : NEW_LINE INDENT denominator = pow ( i , i ) NEW_LINE numerator = pow ( i - mx , i - mx ) NEW_LINE finalDenominator = ( finalDenominator * denominator ) // numerator NEW_LINE DEDENT return finalDenominator NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 NEW_LINE r = 2 NEW_LINE print ( "1 / " , end = " " ) NEW_LINE print ( calcFunction ( n , r ) ) NEW_LINE DEDENT |
Check if the array has an element which is equal to sum of all the remaining elements | function to check if such element exists or not ; storing frequency in dict ; stores the sum ; traverse the array and count the array element ; Only possible if sum is even ; if half sum is available ; Driver code | def isExists ( a , n ) : NEW_LINE INDENT freq = { i : 0 for i in a } NEW_LINE Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ a [ i ] ] += 1 NEW_LINE Sum += a [ i ] NEW_LINE DEDENT if Sum % 2 == 0 : NEW_LINE INDENT if freq [ Sum // 2 ] : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT a = [ 5 , 1 , 2 , 2 ] NEW_LINE n = len ( a ) NEW_LINE if isExists ( a , n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Print all numbers less than N with at | Python 3 program to print all the numbers less than N which have at most 2 unique digits ; Function to generate all possible numbers ; If the number is less than n ; If the number exceeds ; Check if it is not the same number ; Function to print all numbers ; All combination of digits ; Print all numbers ; Driver code | st = set ( ) NEW_LINE def generateNumbers ( n , num , a , b ) : NEW_LINE INDENT if ( num > 0 and num < n ) : NEW_LINE INDENT st . add ( num ) NEW_LINE DEDENT if ( num >= n ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( num * 10 + a > num ) : NEW_LINE INDENT generateNumbers ( n , num * 10 + a , a , b ) NEW_LINE DEDENT generateNumbers ( n , num * 10 + b , a , b ) NEW_LINE DEDENT def printNumbers ( n ) : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT for j in range ( i + 1 , 10 , 1 ) : NEW_LINE INDENT generateNumbers ( n , 0 , i , j ) NEW_LINE DEDENT DEDENT print ( " The β numbers β are : " , end = " β " ) NEW_LINE l = list ( st ) NEW_LINE for i in l : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 NEW_LINE printNumbers ( n ) NEW_LINE DEDENT |
Smallest prime number missing in an array | This function finds all prime numbers upto 10 ^ 5 ; use sieve to find prime ; If number is prime , then store it in prime list ; Function to find the smallest prime missing ; first of all find all prime ; now store all number as index of freq arr so that we can improve searching ; now check for each prime ; Driver Code ; find smallest prime which is not present | def findPrime ( MAX ) : NEW_LINE INDENT pm = [ True ] * ( MAX + 1 ) NEW_LINE pm [ 0 ] , pm [ 1 ] = False , False NEW_LINE for i in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if pm [ i ] == True : NEW_LINE INDENT for j in range ( 2 * i , MAX + 1 , i ) : NEW_LINE INDENT pm [ j ] = False NEW_LINE DEDENT DEDENT DEDENT prime = [ ] NEW_LINE for i in range ( 0 , MAX + 1 ) : NEW_LINE INDENT if pm [ i ] == True : NEW_LINE INDENT prime . append ( i ) NEW_LINE DEDENT DEDENT return prime NEW_LINE DEDENT def findSmallest ( arr , n ) : NEW_LINE INDENT MAX = max ( arr ) NEW_LINE prime = findPrime ( MAX ) NEW_LINE s = set ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE DEDENT ans = - 1 NEW_LINE for i in range ( 0 , len ( prime ) ) : NEW_LINE INDENT if prime [ i ] not in s : NEW_LINE INDENT ans = prime [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 0 , 1 , 2 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE if ( findSmallest ( arr , n ) == - 1 ) : NEW_LINE INDENT print ( " No β prime β number β missing " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( findSmallest ( arr , n ) ) NEW_LINE DEDENT DEDENT |
Find the number after successive division | Function to find the number ; Driver Code | def findNum ( div , rem , N ) : NEW_LINE INDENT num = rem [ N - 1 ] NEW_LINE i = N - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT num = num * div [ i ] + rem [ i ] NEW_LINE i -= 1 NEW_LINE DEDENT return num NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT div = [ 8 , 3 ] NEW_LINE rem = [ 2 , 2 ] NEW_LINE N = len ( div ) NEW_LINE print ( findNum ( div , rem , N ) ) NEW_LINE DEDENT |
Ways to form n / 2 pairs such that difference of pairs is minimum | Python3 implementation of the above approach ; Using mod because the number of ways might be very large ; ways is serving the same purpose as discussed ; pairing up zero people requires one way . ; map count stores count of s . ; sort according to value ; Iterating backwards . ; Checking if current count is odd . ; if current count = 5 , multiply ans by ways [ 4 ] . ; left out person will be selected in current_count ways ; left out person will pair with previous person in previous_count ways ; if previous count is odd , then multiply answer by ways [ prev_count - 1 ] . since one has already been reserved , remaining will be even . reduce prev_count = 0 , since we don 't need it now. ; if prev count is even , one will be reserved , therefore decrement by 1. In the next iteration , prev_count will become odd and it will be handled in the same way . ; if current count is even , then simply multiply ways [ current_count ] to answer . ; multiply answer by ways [ first__count ] since that is left out , after iterating the array . ; Driver code | from collections import defaultdict NEW_LINE mod = 1000000007 NEW_LINE MAX = 100000 NEW_LINE ways = [ None ] * ( MAX + 1 ) NEW_LINE def preCompute ( ) : NEW_LINE INDENT ways [ 0 ] = 1 NEW_LINE ways [ 2 ] = 1 NEW_LINE for i in range ( 4 , MAX + 1 , 2 ) : NEW_LINE INDENT ways [ i ] = ( ( 1 * ( i - 1 ) * ways [ i - 2 ] ) % mod ) NEW_LINE DEDENT DEDENT def countWays ( arr , n ) : NEW_LINE INDENT count = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT count_vector = [ ] NEW_LINE for key in count : NEW_LINE INDENT count_vector . append ( [ key , count [ key ] ] ) NEW_LINE DEDENT count_vector . sort ( ) NEW_LINE ans = 1 NEW_LINE for i in range ( len ( count_vector ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT current_count = count_vector [ i ] [ 1 ] NEW_LINE prev_count = count_vector [ i - 1 ] [ 1 ] NEW_LINE if current_count & 1 : NEW_LINE INDENT ans = ( ans * ways [ current_count - 1 ] ) % mod NEW_LINE ans = ( ans * current_count ) % mod NEW_LINE ans = ( ans * prev_count ) % mod NEW_LINE if prev_count & 1 : NEW_LINE INDENT ans = ( ans * ways [ prev_count - 1 ] ) % mod NEW_LINE count_vector [ i - 1 ] [ 1 ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT count_vector [ i - 1 ] [ 1 ] -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT ans = ( ans * ways [ current_count ] ) % mod NEW_LINE DEDENT DEDENT ans = ( ans * ways [ count_vector [ 0 ] [ 1 ] ] ) % mod NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT preCompute ( ) NEW_LINE arr = [ 2 , 3 , 3 , 3 , 3 , 4 , 4 , 4 , 4 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE countWays ( arr , n ) NEW_LINE DEDENT |
Subsets and Splits