text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Maximize difference between odd and even indexed array elements by swapping unequal adjacent bits in their binary representations | Python program for the above approach ; Function to count total number of bits present in a number ; Function to count total set bits in a number ; Stores the count of set bits ; Right shift by 1 ; Return the final count ; Function to find maximum number by shifting two unequal bits ; Count set bits in number n ; Iterate the string bits ; Function to find minimum number by shifting two unequal bits ; Iterate the set bit ; Function to find the maximum difference ; Stores the maximum difference ; Stores the sum of elements placed at odd positions ; Stores the sum of elements placed at even positions ; Traverse the array ; Update CaseOne ; Stores the maximum difference ; Assign value O ; Traverse the array ; Update caseTwo ; Return maximum of caseOne and CaseTwo ; Drivers Code ; Function Call
import math NEW_LINE def countBit ( n ) : NEW_LINE INDENT return int ( math . log ( n , 2 ) ) + 1 NEW_LINE DEDENT def countSetBit ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while n : NEW_LINE INDENT ans += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def maximize ( n ) : NEW_LINE INDENT bits = countBit ( n ) NEW_LINE setBits = countSetBit ( n ) NEW_LINE ans = 0 NEW_LINE for i in range ( bits ) : NEW_LINE INDENT if i < setBits : NEW_LINE INDENT ans |= 1 NEW_LINE DEDENT if i != setBits - 1 : NEW_LINE INDENT ans <<= 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def minimize ( n ) : NEW_LINE INDENT setBits = countSetBit ( n ) NEW_LINE ans = 0 NEW_LINE for i in range ( setBits ) : NEW_LINE INDENT ans |= 1 NEW_LINE if i != setBits - 1 : NEW_LINE INDENT ans <<= 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def maxDiff ( arr ) : NEW_LINE INDENT caseOne = 0 NEW_LINE SumOfOdd = 0 NEW_LINE SumOfeven = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if i % 2 : NEW_LINE INDENT SumOfOdd += minimize ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT SumOfeven += maximize ( arr [ i ] ) NEW_LINE DEDENT DEDENT caseOne = abs ( SumOfOdd - SumOfeven ) NEW_LINE caseTwo = 0 NEW_LINE SumOfOdd = 0 NEW_LINE SumOfeven = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if i % 2 : NEW_LINE INDENT SumOfOdd += maximize ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT SumOfeven += minimize ( arr [ i ] ) NEW_LINE DEDENT DEDENT caseTwo = abs ( SumOfOdd - SumOfeven ) NEW_LINE return max ( caseOne , caseTwo ) NEW_LINE DEDENT arr = [ 54 , 32 , 11 , 23 ] NEW_LINE print ( maxDiff ( arr ) ) NEW_LINE
Sum of numbers obtained by the count of set and non | Functino to find the number after processing the diagonal elements ; Store the required number ; Checking for each position ; Store the number of set bits & non - set bits at position i ; Traverse the diagonal elements ; Update count of S if current element is set at position i ; Else update NS ; If number of set bits is > number of non - set bits , add set bits value to the ans ; Return the answer ; Function to find the sum of the numbers generated after processing both the diagonals of the matrix ; Store the primary diagonal elements ; Store the secondary diagonal elements ; Function Call to get the required numbers and return their sum ; Driver Code ; Function Call
def processDiagonal ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE getBit = 1 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT S = 0 NEW_LINE NS = 0 NEW_LINE for j in arr : NEW_LINE if getBit & j : NEW_LINE INDENT S += 1 NEW_LINE DEDENT else : NEW_LINE INDENT NS += 1 NEW_LINE DEDENT if S > NS : NEW_LINE ans += 2 ** i NEW_LINE getBit <<= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def findSum ( mat ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE priDiag = [ ] NEW_LINE while i < len ( mat ) : NEW_LINE INDENT priDiag . append ( mat [ i ] [ j ] ) NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT i = 0 NEW_LINE j = len ( mat ) - 1 NEW_LINE secDiag = [ ] NEW_LINE while i < len ( mat ) : NEW_LINE INDENT secDiag . append ( mat [ i ] [ j ] ) NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return processDiagonal ( priDiag ) + processDiagonal ( secDiag ) NEW_LINE DEDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE print ( findSum ( mat ) ) NEW_LINE
Minimize difference between two sequences obtained by splitting first N powers of 2 | Function to partition first N powers of 2 into two subsequences with minimum difference between their sum ; Largest element in the first part ; Place N / 2 - 1 smallest elements in the first sequence ; Place remaining N / 2 elements in the second sequence ; Print the minimum difference ; Driver Code
def minimumDifference ( N ) : NEW_LINE INDENT sum1 = ( 1 << N ) NEW_LINE sum2 = 0 NEW_LINE for i in range ( 1 , N // 2 ) : NEW_LINE INDENT sum1 += ( 1 << i ) NEW_LINE DEDENT for i in range ( N // 2 , N ) : NEW_LINE INDENT sum2 += ( 1 << i ) NEW_LINE DEDENT print ( sum1 - sum2 ) NEW_LINE DEDENT N = 4 NEW_LINE minimumDifference ( N ) NEW_LINE
Check whether N can be a Perfect Cube after adding or subtracting K | Function to check if a number is a perfect Cube or not ; Driver code
def isPerfectCube ( x ) : NEW_LINE INDENT cr = int ( x ** ( 1 / 3 ) ) ; NEW_LINE return ( cr * cr * cr == x ) ; NEW_LINE DEDENT def canBePerfectCube ( N , K ) : NEW_LINE INDENT if ( isPerfectCube ( N + K ) or isPerfectCube ( N - K ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 ; K = 1 ; NEW_LINE canBePerfectCube ( N , K ) ; NEW_LINE N = 5 ; K = 4 ; NEW_LINE canBePerfectCube ( N , K ) ; NEW_LINE N = 7 ; K = 2 ; NEW_LINE canBePerfectCube ( N , K ) ; NEW_LINE DEDENT
Floor square root without using sqrt ( ) function : Recursive | Function to find the square root of the number N using BS ; If the range is still valid ; Find the mid - value of the range ; Base Case ; Condition to check if the left search space is useless ; Driver Code
def sqrtSearch ( low , high , N ) : NEW_LINE INDENT if ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 ; NEW_LINE if ( ( mid * mid <= N ) and ( ( mid + 1 ) * ( mid + 1 ) > N ) ) : NEW_LINE INDENT return mid ; NEW_LINE DEDENT elif ( mid * mid < N ) : NEW_LINE INDENT return sqrtSearch ( mid + 1 , high , N ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return sqrtSearch ( low , mid - 1 , N ) ; NEW_LINE DEDENT DEDENT return low ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 25 ; NEW_LINE print ( sqrtSearch ( 0 , N , N ) ) NEW_LINE DEDENT
Common divisors of N numbers | Function to calculate gcd of two numbers ; Function to prall the common divisors ; Variable to find the gcd of N numbers ; Set to store all the common divisors ; Finding GCD of the given N numbers ; Finding divisors of the HCF of n numbers ; Prall the divisors ; Driver 's Code ; Function to prall the common divisors
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 printAllDivisors ( arr , N ) : NEW_LINE INDENT g = arr [ 0 ] NEW_LINE divisors = dict ( ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT g = gcd ( arr [ i ] , g ) NEW_LINE DEDENT for i in range ( 1 , g + 1 ) : NEW_LINE INDENT if i * i > g : NEW_LINE INDENT break NEW_LINE DEDENT if ( g % i == 0 ) : NEW_LINE INDENT divisors [ i ] = 1 NEW_LINE if ( g // i != i ) : NEW_LINE INDENT divisors [ g // i ] = 1 NEW_LINE DEDENT DEDENT DEDENT for it in sorted ( divisors ) : NEW_LINE INDENT print ( it , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 6 , 90 , 12 , 18 , 30 , 24 ] NEW_LINE n = len ( arr ) NEW_LINE printAllDivisors ( arr , n ) NEW_LINE DEDENT
Recursive Program to print multiplication table of a number | Function that print the table of a given number using recursion ; Base Case ; Print the table for current iteration ; Recursive call to next iteration ; Input number whose table is to print ; Function call to print the table
def mul_table ( N , i ) : NEW_LINE INDENT if ( i > 10 ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( N , " * " , i , " = " , N * i ) NEW_LINE return mul_table ( N , i + 1 ) NEW_LINE DEDENT N = 8 NEW_LINE mul_table ( N , 1 ) NEW_LINE
Find the largest composite number that divides N but is strictly lesser than N | Python3 program to find the largest composite number that divides N which is less than N ; Function to check whether a number is prime or not ; Corner case ; Check from 2 to n - 1 ; Function that find the largest composite number which divides N and less than N ; Find the prime number ; Driver Code ; Get the smallest prime factor ; Check if ( N / a ) is prime or not . If Yes print " - 1" ; Else print largest composite number ( N / a )
import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def getSmallestPrimefactor ( n ) : NEW_LINE INDENT for i in range ( 2 , ( int ) ( math . sqrt ( n ) + 1 ) ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return i ; NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT N = 100 ; NEW_LINE a = getSmallestPrimefactor ( N ) ; NEW_LINE if ( ( isPrime ( ( int ) ( N / a ) ) ) ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ( int ) ( N / a ) ) ; NEW_LINE DEDENT
Check if N and M can be made equal by increasing N by A and decreasing M by B | Function to whether the numbers can be made equal or not ; Check whether the numbers can reach an equal point or not ; M and N cannot be made equal by increasing M and decreasing N when M is already greater than N ; Driver code
def checkEqualNo ( m , n , a , b ) : NEW_LINE INDENT if ( m <= n ) : NEW_LINE INDENT if ( ( n - m ) % ( a + b ) == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT M = 2 ; N = 8 ; NEW_LINE A = 3 ; B = 3 ; NEW_LINE if ( checkEqualNo ( M , N , A , B ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
XOR and OR of all N | Function to check if a number is palindrome or not ; Convert the num n to string ; Iterate over string to check whether it is palindromic or not ; Function to find XOR of all N - digits palindrome number ; To store the XOR and OR of all palindromic number ; Starting N - digit palindromic number ; Ending N - digit palindromic number ; Iterate over starting and ending number ; To check if i is palindromic or not ; Print the XOR and OR of all palindromic number ; Driver Code
def ispalin ( num ) : NEW_LINE INDENT s = str ( num ) ; NEW_LINE st = 0 ; NEW_LINE ed = len ( s ) - 1 ; NEW_LINE while ( st <= ed ) : NEW_LINE INDENT if ( s [ st ] != s [ ed ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT st += 1 ; NEW_LINE ed -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def CalculateXORandOR ( n ) : NEW_LINE INDENT CalculateXOR = 0 ; NEW_LINE CalculateOR = 0 ; NEW_LINE start = 10 ** ( n - 1 ) ; NEW_LINE end = ( 10 ** n ) - 1 ; NEW_LINE for i in range ( start , end + 1 ) : NEW_LINE INDENT if ( ispalin ( i ) ) : NEW_LINE INDENT CalculateXOR = CalculateXOR ^ i ; NEW_LINE CalculateOR = CalculateOR | i ; NEW_LINE DEDENT DEDENT print ( " XOR ▁ = " , CalculateXOR , end = " ▁ " ) ; NEW_LINE print ( " OR ▁ = ▁ " , CalculateOR ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 ; NEW_LINE CalculateXORandOR ( n ) ; NEW_LINE DEDENT
Sum of all palindromic numbers lying in the range [ L , R ] for Q queries | pref [ ] array to precompute the sum of all palindromic number ; Function that return number num if num is palindromic else return 0 ; Convert num to string ; Function to precompute the sum of all palindrome numbers upto 100000 ; checkPalindrome ( ) return the number i if i is palindromic else return 0 ; Function to print the sum for each query ; Function to prsum of all palindromic numbers between [ L , R ] ; Function that pre computes the sum of all palindromic numbers ; Iterate over all Queries to print the sum ; Queries ; Function that print the the sum of all palindromic number in Range [ L , R ]
pref = [ 0 ] * 100001 NEW_LINE def checkPalindrome ( num ) : NEW_LINE INDENT strr = str ( num ) NEW_LINE l = 0 NEW_LINE r = len ( strr ) - 1 NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( strr [ l ] != strr [ r ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT return num NEW_LINE DEDENT def preCompute ( ) : NEW_LINE INDENT for i in range ( 1 , 100001 ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + checkPalindrome ( i ) NEW_LINE DEDENT DEDENT def printSum ( L , R ) : NEW_LINE INDENT print ( pref [ R ] - pref [ L - 1 ] ) NEW_LINE DEDENT def printSumPalindromic ( arr , Q ) : NEW_LINE INDENT preCompute ( ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) NEW_LINE DEDENT DEDENT Q = 2 NEW_LINE arr = [ [ 10 , 13 ] , [ 12 , 21 ] ] NEW_LINE printSumPalindromic ( arr , Q ) NEW_LINE
Sum of alternating sign Squares of first N natural numbers | Function to calculate the alternating sign sum ; Variable to store the sum ; Loop to iterate each number from 1 to N ; The alternating sign is put by checking if the number is even or odd ; Add the square with the sign ; Add the square with the sign ; Driver code
def summation ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i % 2 == 1 ) : NEW_LINE INDENT sum += ( i * i ) ; NEW_LINE DEDENT else : NEW_LINE INDENT sum -= ( i * i ) ; NEW_LINE DEDENT DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 ; NEW_LINE print ( summation ( N ) ) ; NEW_LINE DEDENT
Sum of alternating sign Squares of first N natural numbers | Function to calculate the alternating sign sum ; Variable to store the absolute sum ; Variable to store the sign ; Variable to store the resultant sum ; Driver code
def summation ( n ) : NEW_LINE INDENT abs_sum = n * ( n + 1 ) // 2 ; NEW_LINE sign = 1 if ( ( n + 1 ) % 2 == 0 ) else - 1 ; NEW_LINE result_sum = sign * abs_sum ; NEW_LINE return result_sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 ; NEW_LINE print ( summation ( N ) ) ; NEW_LINE DEDENT
Count pairs from 1 to N such that their Sum is divisible by their XOR | 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 if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 ; NEW_LINE print ( countPairs ( n ) ) ; NEW_LINE DEDENT
Count pairs in array such that one element is power of another | Python3 program to count pairs in array such that one element is power of another ; Function to check if given number number y is power of x ; log function to calculate value ; compare to the result1 or result2 both are equal ; Function to find pairs from array ; Iterate through all pairs ; Increment count if one is the power of other ; Driver code
from math import log NEW_LINE def isPower ( x , y ) : NEW_LINE INDENT res1 = log ( y ) // log ( x ) ; NEW_LINE res2 = log ( y ) / log ( x ) ; NEW_LINE return ( res1 == res2 ) ; NEW_LINE DEDENT def countPower ( arr , n ) : NEW_LINE INDENT res = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if isPower ( arr [ i ] , arr [ j ] ) or isPower ( arr [ j ] , arr [ i ] ) : NEW_LINE INDENT res += 1 ; NEW_LINE DEDENT DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 16 , 2 , 3 , 9 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( countPower ( a , n ) ) ; NEW_LINE DEDENT
Find the original Array using XOR values of all adjacent elements | XOR of all elements from 1 to N ; Function to find the Array from the XOR Array ; Take a vector to store the permutation ; XOR of N natural numbers ; Loop to find the XOR of adjacent elements of the XOR Array ; Loop to find the other elements of the permutation ; Finding the next and next elements ; Driver Code ; Required Permutation
def xor_all_elements ( n ) : NEW_LINE INDENT if n & 3 == 0 : NEW_LINE INDENT return n NEW_LINE DEDENT elif n & 3 == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif n & 3 == 2 : NEW_LINE INDENT return n + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def findArray ( xorr , n ) : NEW_LINE INDENT arr = [ ] NEW_LINE xor_all = xor_all_elements ( n ) NEW_LINE xor_adjacent = 0 NEW_LINE for i in range ( 0 , n - 1 , 2 ) : NEW_LINE INDENT xor_adjacent = xor_adjacent ^ xorr [ i ] NEW_LINE DEDENT last_element = xor_all ^ xor_adjacent NEW_LINE arr . append ( last_element ) NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT last_element = xorr [ i ] ^ last_element NEW_LINE arr . append ( last_element ) NEW_LINE DEDENT return arr NEW_LINE DEDENT xorr = [ 7 , 5 , 3 , 7 ] NEW_LINE n = 5 NEW_LINE arr = findArray ( xorr , n ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT
Sum of non | Function to return a vector which consists the sum of four portions of the matrix ; Iterating through the matrix ; Condition for selecting all values before the second diagonal of metrics ; Top portion of the matrix ; Left portion of the matrix ; Bottom portion of the matrix ; Right portion of the matrix ; Adding all the four portions into a vecto ; Driver code
def sumOfParts ( arr , N ) : NEW_LINE INDENT sum_part1 , sum_part2 , sum_part3 , sum_part4 = 0 , 0 , 0 , 0 NEW_LINE totalsum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if i + j < N - 1 : NEW_LINE INDENT if ( i < j and i != j and i + j ) : NEW_LINE INDENT sum_part1 += arr [ i ] [ j ] NEW_LINE DEDENT elif i != j : NEW_LINE INDENT sum_part2 += arr [ i ] [ j ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if i > j and i + j != N - 1 : NEW_LINE INDENT sum_part3 += arr [ i ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT if i + j != N - 1 and i != j : NEW_LINE INDENT sum_part4 += arr [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return sum_part1 + sum_part2 + sum_part3 + sum_part4 NEW_LINE DEDENT N = 4 NEW_LINE arr = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] NEW_LINE print ( sumOfParts ( arr , N ) ) NEW_LINE
Check if X and Y can be made zero by using given operation any number of times | Function to check if X and Y can be made equal to zero by using given operation any number of times ; Check for the two conditions ; Driver code
def ifPossible ( X , Y ) : NEW_LINE INDENT if ( X > Y ) : NEW_LINE INDENT X , Y = Y , X NEW_LINE DEDENT if ( ( X + Y ) % 5 == 0 and 3 * X >= 2 * Y ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT X = 33 NEW_LINE Y = 27 NEW_LINE ifPossible ( X , Y ) NEW_LINE
Largest Even and Odd N | Function to print the largest n - digit even and odd numbers in hexadecimal number system ; Append ' F ' ( N - 1 ) times ; Append ' E ' for an even number ; Append ' F ' for an odd number ; Driver code
def findNumbers ( n ) : NEW_LINE INDENT ans = ' F ' * ( n - 1 ) ; NEW_LINE even = ans + ' E ' ; NEW_LINE odd = ans + ' F ' ; NEW_LINE print ( " Even : ▁ " , even ) ; NEW_LINE print ( " Odd : ▁ " , odd ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; NEW_LINE findNumbers ( n ) ; NEW_LINE DEDENT
Program to compute log a to any base b ( logb a ) | Python3 program to find log ( a ) on any base b ; Driver code
from math import log NEW_LINE def log_a_to_base_b ( a , b ) : NEW_LINE INDENT return log ( a ) // log ( b ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 3 ; NEW_LINE b = 2 ; NEW_LINE print ( log_a_to_base_b ( a , b ) ) ; NEW_LINE a = 256 ; NEW_LINE b = 4 ; NEW_LINE print ( log_a_to_base_b ( a , b ) ) ; NEW_LINE DEDENT
Program to compute log a to any base b ( logb a ) | Recursive function to compute log a to the base b ; Driver code
def log_a_to_base_b ( a , b ) : NEW_LINE INDENT rslt = ( 1 + log_a_to_base_b ( a // b , b ) ) if ( a > ( b - 1 ) ) else 0 ; NEW_LINE return rslt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 3 ; NEW_LINE b = 2 ; NEW_LINE print ( log_a_to_base_b ( a , b ) ) ; NEW_LINE a = 256 ; NEW_LINE b = 4 ; NEW_LINE print ( log_a_to_base_b ( a , b ) ) ; NEW_LINE DEDENT
Largest and Smallest N | Function to return the largest N - digit number in Hexa - Decimal Number System ; Append ' F ' N times ; Function to return the smallest N - digit number in Hexa - Decimal Number System ; Append '0' ( N - 1 ) times to 1 ; Function to print the largest and smallest N - digit Hexa - Decimal number ; Driver code
def findLargest ( N ) : NEW_LINE INDENT largest = ' F ' * N NEW_LINE return largest ; NEW_LINE DEDENT def findSmallest ( N ) : NEW_LINE INDENT smallest = '1' + '0' * ( N - 1 ) NEW_LINE return smallest ; NEW_LINE DEDENT def printAns ( largest ) : NEW_LINE INDENT print ( " Largest : ▁ " , findLargest ( largest ) ) ; NEW_LINE print ( " Smallest : ▁ " , findSmallest ( largest ) ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 ; NEW_LINE printAns ( N ) ; NEW_LINE DEDENT
Highest and Smallest power of K less than and greater than equal to N respectively | Python3 implementation of the approach ; Function to return the highest power of k less than or equal to n ; Function to return the smallest power of k greater than or equal to n ; Function to print the result ; Driver code
import math NEW_LINE def prevPowerofK ( n , k ) : NEW_LINE INDENT p = int ( math . log ( n ) / math . log ( k ) ) NEW_LINE return int ( math . pow ( k , p ) ) NEW_LINE DEDENT def nextPowerOfK ( n , k ) : NEW_LINE INDENT return prevPowerofK ( n , k ) * k NEW_LINE DEDENT def printResult ( n , k ) : NEW_LINE INDENT print ( prevPowerofK ( n , k ) , nextPowerOfK ( n , k ) ) NEW_LINE DEDENT n = 6 NEW_LINE k = 3 NEW_LINE printResult ( n , k ) NEW_LINE
Check if all elements of the given array can be made 0 by decrementing value in pairs | Function to check if all the elements can be made 0 in an array ; Variable to store sum and maximum element in an array ; Loop to calculate the sum and max value of the given array ; If n is 1 or sum is odd or sum - max element < max then no solution ; For the remaining case , print Yes ; Driver code
def canMake ( n , ar ) : NEW_LINE INDENT sum = 0 ; maxx = - 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ar [ i ] ; NEW_LINE maxx = max ( maxx , ar [ i ] ) ; NEW_LINE DEDENT if ( n == 1 or sum % 2 == 1 or sum - maxx < maxx ) : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 ; NEW_LINE arr = [ 1 , 1 , 2 , 3 , 6 , 11 ] ; NEW_LINE canMake ( n , arr ) ; NEW_LINE DEDENT
Sum of all Perfect Squares lying in the range [ L , R ] for Q queries | Python3 program to find the sum of all perfect squares in the given range ; Array to precompute the sum of squares from 1 to 100010 so that for every query , the answer can be returned in O ( 1 ) . ; Function to check if a number is a perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; Function to precompute the perfect squares upto 100000. ; Function to print the sum for each query ; Driver code ; To calculate the precompute function ; Calling the printSum function for every query
from math import sqrt , floor NEW_LINE pref = [ 0 ] * 100010 ; NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sr = sqrt ( x ) ; NEW_LINE rslt = x if ( sr - floor ( sr ) == 0 ) else 0 ; NEW_LINE return rslt ; NEW_LINE DEDENT def compute ( ) : NEW_LINE INDENT for i in range ( 1 , 100001 ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + isPerfectSquare ( i ) ; NEW_LINE DEDENT DEDENT def printSum ( L , R ) : NEW_LINE INDENT sum = pref [ R ] - pref [ L - 1 ] ; NEW_LINE print ( sum , end = " ▁ " ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT compute ( ) ; NEW_LINE Q = 4 ; NEW_LINE arr = [ [ 1 , 10 ] , [ 1 , 100 ] , [ 2 , 25 ] , [ 4 , 50 ] ] ; NEW_LINE for i in range ( Q ) : NEW_LINE INDENT printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; NEW_LINE DEDENT DEDENT
Program to find all Factors of a Number using recursion | Recursive function to prfactors of a number ; Checking if the number is less than N ; Calling the function recursively for the next number ; Driver code
def factors ( n , i ) : NEW_LINE INDENT if ( i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE DEDENT factors ( n , i + 1 ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 16 ; NEW_LINE factors ( N , 1 ) ; NEW_LINE DEDENT
Maximize value of ( a + b ) such that ( a * a | Function to maximize the value of ( a + b ) such that ( a * a - b * b = n ) ; Driver code
def maxValue ( n ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 1 ; NEW_LINE print ( maxValue ( n ) ) ; NEW_LINE DEDENT
Maximum number of edges that N | Function to find the maximum number of edges in a N - vertex graph . ; According to the Mantel 's theorem the maximum number of edges will be floor of [(n^2)/4] ; Driver Function
def solve ( n ) : NEW_LINE INDENT ans = ( n * n // 4 ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE print ( solve ( n ) ) NEW_LINE DEDENT
Multiplication table till N rows where every Kth row is table of K upto Kth term | Function to pr the multiplication table upto K - th term ; For loop to iterate from 1 to N where i serves as the value of K ; Inner loop which at every iteration goes till i ; Printing the table value for i ; New line after every row ; Driver code
def prMultiples ( N ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , i + 1 ) : NEW_LINE INDENT print ( ( i * j ) , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE prMultiples ( N ) NEW_LINE DEDENT
Boundary Value Analysis : Nature of Roots of a Quadratic equation | BVA for nature of roots of a quadratic equation ; If a = 0 , D / 2 a will yield exception Hence it is not a valid Quadratic Equation ; If D > 0 , it will be Real Roots ; If D == 0 , it will be Equal Roots ; If D < 0 , it will be Imaginary Roots ; Function to check for all testcases ; Driver Code
def nature_of_roots ( a , b , c ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT print ( " Not ▁ a ▁ Quadratic ▁ Equation " ) ; NEW_LINE return ; NEW_LINE DEDENT D = b * b - 4 * a * c ; NEW_LINE if ( D > 0 ) : NEW_LINE INDENT print ( " Real ▁ Roots " ) ; NEW_LINE DEDENT elif ( D == 0 ) : NEW_LINE INDENT print ( " Equal ▁ Roots " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Imaginary ▁ Roots " ) ; NEW_LINE DEDENT DEDENT def checkForAllTestCase ( ) : NEW_LINE INDENT print ( " Testcase TABSYMBOL a TABSYMBOL b TABSYMBOL c TABSYMBOL Actual ▁ Output " ) ; NEW_LINE print ( ) ; NEW_LINE a = b = c = 0 ; NEW_LINE testcase = 1 ; NEW_LINE while ( testcase <= 13 ) : NEW_LINE INDENT if ( testcase == 1 ) : NEW_LINE INDENT a = 0 ; NEW_LINE b = 50 ; NEW_LINE c = 50 ; NEW_LINE DEDENT elif ( testcase == 2 ) : NEW_LINE INDENT a = 1 ; NEW_LINE b = 50 ; NEW_LINE c = 50 ; NEW_LINE DEDENT elif ( testcase == 3 ) : NEW_LINE INDENT a = 50 ; NEW_LINE b = 50 ; NEW_LINE c = 50 ; NEW_LINE DEDENT elif ( testcase == 4 ) : NEW_LINE INDENT a = 99 ; NEW_LINE b = 50 ; NEW_LINE c = 50 ; NEW_LINE DEDENT elif ( testcase == 5 ) : NEW_LINE INDENT a = 100 ; NEW_LINE b = 50 ; NEW_LINE c = 50 ; NEW_LINE DEDENT elif ( testcase == 6 ) : NEW_LINE INDENT a = 50 ; NEW_LINE b = 0 ; NEW_LINE c = 50 ; NEW_LINE DEDENT elif ( testcase == 7 ) : NEW_LINE INDENT a = 50 ; NEW_LINE b = 1 ; NEW_LINE c = 50 ; NEW_LINE DEDENT elif ( testcase == 8 ) : NEW_LINE INDENT a = 50 ; NEW_LINE b = 99 ; NEW_LINE c = 50 ; NEW_LINE DEDENT elif ( testcase == 9 ) : NEW_LINE INDENT a = 50 ; NEW_LINE b = 100 ; NEW_LINE c = 50 ; NEW_LINE DEDENT elif ( testcase == 10 ) : NEW_LINE INDENT a = 50 ; NEW_LINE b = 50 ; NEW_LINE c = 0 ; NEW_LINE DEDENT elif ( testcase == 11 ) : NEW_LINE INDENT a = 50 ; NEW_LINE b = 50 ; NEW_LINE c = 1 ; NEW_LINE DEDENT elif ( testcase == 12 ) : NEW_LINE INDENT a = 50 ; NEW_LINE b = 50 ; NEW_LINE c = 99 ; NEW_LINE DEDENT elif ( testcase == 13 ) : NEW_LINE INDENT a = 50 ; NEW_LINE b = 50 ; NEW_LINE c = 100 ; NEW_LINE DEDENT print ( " TABSYMBOL " , testcase , " TABSYMBOL " , a , " TABSYMBOL " , b , " TABSYMBOL " , c , " TABSYMBOL " , end = " " ) ; NEW_LINE nature_of_roots ( a , b , c ) ; NEW_LINE print ( ) ; NEW_LINE testcase += 1 ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT checkForAllTestCase ( ) ; NEW_LINE DEDENT
Find if the Vacation can be taken or not | Function to find if the Vacation is possible or not ; Find the required number of hours of study ; find the hours of study that can be done if the vacation is taken ; check if the required hours are less than or equal to the hours of study that can be done if the vacation is taken ; Driver Code
def isPossible ( N , S , C , H , L , T ) : NEW_LINE INDENT total_time_required = S * C * H NEW_LINE available_time_after_vacation = ( N - L ) * T NEW_LINE if ( available_time_after_vacation >= total_time_required ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT N = 12 NEW_LINE S = 5 NEW_LINE C = 8 NEW_LINE H = 3 NEW_LINE L = 2 NEW_LINE T = 20 NEW_LINE if ( isPossible ( N , S , C , H , L , T ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT N = 1 NEW_LINE S = 2 NEW_LINE C = 3 NEW_LINE H = 4 NEW_LINE L = 5 NEW_LINE T = 6 NEW_LINE if ( isPossible ( N , S , C , H , L , T ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Find Maximum and Minimum of two numbers using Absolute function | Function to return maximum among the two numbers ; Function to return minimum among the two numbers ; Driver code ; Displaying the maximum value ; Displaying the minimum value
def maximum ( x , y ) : NEW_LINE INDENT return ( ( x + y + abs ( x - y ) ) // 2 ) NEW_LINE DEDENT def minimum ( x , y ) : NEW_LINE INDENT return ( ( x + y - abs ( x - y ) ) // 2 ) NEW_LINE DEDENT x = 99 NEW_LINE y = 18 NEW_LINE print ( " Maximum : " , maximum ( x , y ) ) NEW_LINE print ( " Minimum : " , minimum ( x , y ) ) NEW_LINE
Find an array of size N having exactly K subarrays with sum S | Function to find array with K subarrays with sum S ; Driver Code ; Function call
def SubarraysWithSumS ( n , k , s ) : NEW_LINE INDENT for i in range ( k ) : NEW_LINE INDENT print ( s , end = " ▁ " ) NEW_LINE DEDENT for i in range ( k , n ) : NEW_LINE INDENT print ( s + 1 , end = " ▁ " ) NEW_LINE DEDENT DEDENT n = 4 NEW_LINE k = 2 NEW_LINE s = 3 NEW_LINE SubarraysWithSumS ( n , k , s ) NEW_LINE
Minimum number of cuts required to pay salary from N length Gold Bar | Python Implementation to find the minimum number of cuts to pay the worker . ; Function to find the minimum number of cuts to pay the worker . ; Nearest Integer to the Log value of the number N ; Driver Code ; Cuts Required in the Length of 15
import math NEW_LINE def pay ( n ) : NEW_LINE INDENT cuts = int ( math . log ( n , 2 ) ) NEW_LINE return cuts NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE cuts = pay ( n ) NEW_LINE print ( cuts ) NEW_LINE n = 15 NEW_LINE cuts = pay ( n ) NEW_LINE print ( cuts ) NEW_LINE DEDENT
Sum of Maximum and Minimum prime factor of every number in the Array | Python3 implementation of the approach ; max_prime [ i ] represent maximum prime number that divides the number i ; min_prime [ i ] represent minimum prime number that divides the number i ; Function to store the minimum prime factor and the maximum prime factor in two arrays ; Check for prime number if min_prime [ i ] > 0 , then it is not a prime number ; if i is a prime number min_prime number that divide prime number and max_prime number that divide prime number is the number itself . ; If this number is being visited for first time then this divisor must be the smallest prime number that divides this number ; The last prime number that divides this number will be maximum . ; Function to find the sum of the minimum and the maximum prime factors of every number from the given array ; Pre - calculation ; For every element of the given array ; The sum of its smallest and largest prime factor ; Driver code
MAX = 100000 NEW_LINE max_prime = [ 0 ] * ( MAX + 1 ) NEW_LINE min_prime = [ 0 ] * ( MAX + 1 ) NEW_LINE def sieve ( n ) : NEW_LINE INDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( min_prime [ i ] > 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT min_prime [ i ] = i NEW_LINE max_prime [ i ] = i NEW_LINE j = i + i NEW_LINE while ( j <= n ) : NEW_LINE INDENT if ( min_prime [ j ] == 0 ) : NEW_LINE INDENT min_prime [ j ] = i NEW_LINE DEDENT max_prime [ j ] = i NEW_LINE j += i NEW_LINE DEDENT DEDENT DEDENT def findSum ( arr , n ) : NEW_LINE INDENT sieve ( MAX ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = min_prime [ arr [ i ] ] + max_prime [ arr [ i ] ] NEW_LINE print ( sum , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 5 , 10 , 15 , 20 , 25 , 30 ] NEW_LINE n = len ( arr ) NEW_LINE findSum ( arr , n ) NEW_LINE
Pair of integers ( a , b ) which satisfy the given equations | Function to count valid pairs ; Driver code
def pairCount ( n , m ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for b in range ( int ( pow ( m , 1 / 2 ) ) ) : NEW_LINE INDENT a = m - b * b ; NEW_LINE if ( a * a + b == n ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 9 ; NEW_LINE m = 3 ; NEW_LINE print ( pairCount ( n , m ) ) ; NEW_LINE DEDENT
Largest Divisor for each element in an array other than 1 and the number itself | Python3 implementation of the approach ; Divisors array to keep track of the maximum divisor ; Function to pre - compute the prime numbers and largest divisors ; Visited array to keep track of prime numbers ; 0 and 1 are not prime numbers ; Initialising divisors [ i ] = i ; For all the numbers divisible by 2 the maximum divisor will be number / 2 ; If divisors [ i ] is not equal to i then this means that divisors [ i ] contains minimum prime divisor for the number ; Update the answer to i / smallest_prime_divisor [ i ] ; Condition if i is a prime number ; If divisors [ j ] is equal to j then this means that i is the first prime divisor for j so we update divi [ j ] = i ; If the current element is prime then it has no divisors other than 1 and itself ; Driver code
maxin = 100001 ; NEW_LINE divisors = [ 0 ] * ( maxin + 1 ) ; NEW_LINE def Calc_Max_Div ( arr , n ) : NEW_LINE INDENT vis = [ 1 ] * ( maxin + 1 ) ; NEW_LINE vis [ 0 ] = vis [ 1 ] = 0 ; NEW_LINE for i in range ( 1 , maxin + 1 ) : NEW_LINE INDENT divisors [ i ] = i ; NEW_LINE DEDENT for i in range ( 4 , maxin + 1 , 2 ) : NEW_LINE INDENT vis [ i ] = 0 ; NEW_LINE divisors [ i ] = i // 2 ; NEW_LINE DEDENT for i in range ( 3 , maxin + 1 , 2 ) : NEW_LINE INDENT if ( divisors [ i ] != i ) : NEW_LINE INDENT divisors [ i ] = i // divisors [ i ] ; NEW_LINE DEDENT if ( vis [ i ] == 1 ) : NEW_LINE INDENT for j in range ( i * i , maxin , i ) : NEW_LINE INDENT vis [ j ] = 0 ; NEW_LINE if ( divisors [ j ] == j ) : NEW_LINE INDENT divisors [ j ] = i ; NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( divisors [ arr [ i ] ] == arr [ i ] ) : NEW_LINE INDENT print ( " - 1 ▁ " , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( divisors [ arr [ i ] ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 6 , 7 , 8 , 9 , 10 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE Calc_Max_Div ( arr , n ) ; NEW_LINE DEDENT
Given a number N in decimal base , find the sum of digits in any base B | Function to compute sum of Digits of Number N in base B ; Initialize sum with 0 ; Compute unit digit of the number ; Add unit digit in sum ; Update value of Number ; Driver code
def sumOfDigit ( n , b ) : NEW_LINE INDENT unitDigit = 0 NEW_LINE sum = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT unitDigit = n % b NEW_LINE sum += unitDigit NEW_LINE n = n // b NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 50 NEW_LINE b = 2 NEW_LINE print ( sumOfDigit ( n , b ) ) NEW_LINE
Find the Nth digit from right in base B of the given number in Decimal base | Function to compute Nth digit from right in base B ; Skip N - 1 Digits in Base B ; Nth Digit from right in Base B ; Driver Code
def nthDigit ( a , n , b ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT a = a // b NEW_LINE DEDENT return a % b NEW_LINE DEDENT a = 100 NEW_LINE n = 3 NEW_LINE b = 4 NEW_LINE print ( nthDigit ( a , n , b ) ) NEW_LINE
Find three prime numbers with given sum | Python3 implementation of the approach ; The vector primes holds the prime numbers ; Function to generate prime numbers ; Initialize the array elements to 0 s ; Set the non - primes to true ; Fill the vector primes with prime numbers which are marked as false in the numbers array ; Function to print three prime numbers which sum up to the number N ; Take the first prime number ; Take the second prime number ; Subtract the two prime numbers from the N to obtain the third number ; If the third number is prime ; Print the three prime numbers if the solution exists ; Driver code ; Function for generating prime numbers using Sieve of Eratosthenes ; Function to print the three prime numbers whose sum is equal to N
from math import sqrt NEW_LINE MAX = 100001 ; NEW_LINE primes = [ ] ; NEW_LINE def initialize ( ) : NEW_LINE INDENT numbers = [ 0 ] * ( MAX + 1 ) ; NEW_LINE n = MAX ; NEW_LINE for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( not numbers [ i ] ) : NEW_LINE INDENT for j in range ( i * i , n + 1 , i ) : NEW_LINE INDENT numbers [ j ] = True ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( numbers [ i ] == False ) : NEW_LINE INDENT primes . append ( i ) ; NEW_LINE DEDENT DEDENT DEDENT def findNums ( num ) : NEW_LINE INDENT ans = False ; NEW_LINE first = - 1 ; NEW_LINE second = - 1 ; NEW_LINE third = - 1 ; NEW_LINE for i in range ( num ) : NEW_LINE INDENT first = primes [ i ] ; NEW_LINE for j in range ( num ) : NEW_LINE INDENT second = primes [ j ] ; NEW_LINE third = num - first - second ; NEW_LINE if ( third in primes ) : NEW_LINE INDENT ans = True ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( ans ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT if ( ans ) : NEW_LINE INDENT print ( first , second , third ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 101 ; NEW_LINE initialize ( ) ; NEW_LINE findNums ( n ) ; NEW_LINE DEDENT
Print all maximal increasing contiguous sub | Function to print each of maximal contiguous increasing subarray ; Loop to iterate through the array and print the maximal contiguous increasing subarray . ; Condition to check whether the element at i , is greater than its next neighbouring element or not . ; Driver function
def printmaxSubseq ( arr , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i + 1 ] ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ i ] ) ; NEW_LINE DEDENT DEDENT print ( arr [ n - 1 ] ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 9 , 8 , 11 , 13 , 10 , 15 , 14 , 16 , 20 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE printmaxSubseq ( arr , n ) ; NEW_LINE DEDENT
Count of non decreasing arrays of length N formed with values in range L to R | Function to return the count of different arrays ; No such combination exists ; Arrays formed with single elements ; Driver code
def countSum ( N , L , R ) : NEW_LINE INDENT if ( L > R ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT return R - L + 1 ; NEW_LINE DEDENT if ( N > 1 ) : NEW_LINE INDENT return ( N - 2 ) * ( R - L ) + 1 ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , L , R = 4 , 4 , 6 ; NEW_LINE print ( countSum ( N , L , R ) ) ; NEW_LINE DEDENT
Minimum decrement operations to make Array elements equal by only decreasing K each time | Python3 implementation of the above approach ; Finding the minimum element ; Loop over all the elements and find the difference ; Solution found and returned ; Driver code
import sys NEW_LINE def solve ( arr , n , k ) : NEW_LINE INDENT minx = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT minx = min ( minx , arr [ i ] ) ; NEW_LINE DEDENT decrements = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( arr [ i ] - minx ) % k != 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT decrements += ( ( arr [ i ] - minx ) // k ) ; NEW_LINE DEDENT DEDENT return decrements ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 ; NEW_LINE k = 3 ; NEW_LINE arr = [ 12 , 9 , 15 ] ; NEW_LINE print ( solve ( arr , n , k ) ) ; NEW_LINE DEDENT
Count non decreasing subarrays of size N from N Natural numbers | Returns value of Binomial Coefficient C ( n , k ) ; Since nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Function to find the count of required subarrays ; The required count is the binomial coefficient as explained in the approach above ; Driver Function
def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ 0 ] * ( k + 1 ) ; NEW_LINE C [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) , 0 , - 1 ) : NEW_LINE INDENT C [ j ] = C [ j ] + C [ j - 1 ] ; NEW_LINE DEDENT DEDENT return C [ k ] ; NEW_LINE DEDENT def count_of_subarrays ( N ) : NEW_LINE INDENT count = binomialCoeff ( 2 * N - 1 , N ) ; NEW_LINE return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 ; NEW_LINE print ( count_of_subarrays ( N ) ) ; NEW_LINE DEDENT
Length of Smallest subarray in range 1 to N with sum greater than a given value | Function to do a binary search on a given range . ; Total sum is the sum of N numbers . ; Sum until mid ; If remaining sum is < the required value , then the required number is in the right half ; Driver code
def usingBinarySearch ( start , end , N , S ) : NEW_LINE INDENT if ( start >= end ) : NEW_LINE INDENT return start ; NEW_LINE DEDENT mid = start + ( end - start ) // 2 ; NEW_LINE totalSum = ( N * ( N + 1 ) ) // 2 ; NEW_LINE midSum = ( mid * ( mid + 1 ) ) // 2 ; NEW_LINE if ( ( totalSum - midSum ) <= S ) : NEW_LINE INDENT return usingBinarySearch ( start , mid , N , S ) ; NEW_LINE DEDENT return usingBinarySearch ( mid + 1 , end , N , S ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 ; NEW_LINE S = 11 ; NEW_LINE print ( N - usingBinarySearch ( 1 , N , N , S ) + 1 ) ; NEW_LINE DEDENT
Distribution of a Number in Array within a Range | Function for the distribution of the number ; Distribute the number among k elements ; If there is some remaining sum to distribute ; If there are elements remaining to distribute i . e . ( n - k ) ; Divide the remaining sum into n - k elements ; Print the distribution ; Driver code
def distribution ( n , k , l , r , S , Sk ) : NEW_LINE INDENT a = [ 0 ] * n ; NEW_LINE len = k ; NEW_LINE temp , rem , s = 0 , 0 , 0 ; NEW_LINE diff = S - Sk ; NEW_LINE for i in range ( len ) : NEW_LINE INDENT temp = Sk / k ; NEW_LINE rem = Sk % k ; NEW_LINE if ( temp + rem >= l and temp + rem <= r ) : NEW_LINE INDENT a [ i ] = temp ; NEW_LINE DEDENT elif ( temp + rem > r ) : NEW_LINE INDENT a [ i ] = r ; NEW_LINE DEDENT elif ( temp + rem < r ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT Sk = Sk - a [ i ] ; NEW_LINE k = k - 1 ; NEW_LINE DEDENT if ( Sk > 0 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT if ( len != 0 ) : NEW_LINE INDENT k = n - len ; NEW_LINE for i in range ( len , n ) : NEW_LINE INDENT temp = diff / k ; NEW_LINE rem = diff % k ; NEW_LINE if ( temp + rem >= l and temp + rem <= r ) : NEW_LINE INDENT a [ i ] = temp ; NEW_LINE DEDENT elif ( temp + rem > r ) : NEW_LINE INDENT a [ i ] = r ; NEW_LINE DEDENT elif ( temp + rem < r ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT diff = diff - a [ i ] ; NEW_LINE k = k - 1 ; NEW_LINE DEDENT if ( diff != 0 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( int ( a [ i ] ) , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n , k , l , r , S , Sk = 5 , 3 , 1 , 5 , 13 , 9 ; NEW_LINE distribution ( n , k , l , r , S , Sk ) ; NEW_LINE DEDENT
Number of valid indices in the permutation of first N natural numbers | Python3 implementation of the approach ; Function to return the number of i 's such that Pi <= Pj for all 1 <= j <= i in the permutation of first N natural numbers ; To store the count of such indices ; Store the mini value ; For all the elements ; Return the required answer ; Driver code
import sys NEW_LINE INT_MAX = sys . maxsize NEW_LINE def min_index ( p , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE mini = INT_MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( p [ i ] <= mini ) : NEW_LINE INDENT mini = p [ i ] ; NEW_LINE DEDENT if ( mini == p [ i ] ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT P = [ 4 , 2 , 5 , 1 , 3 ] ; NEW_LINE n = len ( P ) ; NEW_LINE print ( min_index ( P , n ) ) ; NEW_LINE DEDENT
Check if Sum and XOR of all elements of array is equal | Function to Check if Sum and XOR of all elements of array is equal ; Sum and XOR of all elements ; Checking Sum and XOR to be equal ; Driver Function ; Check Sum and XOR is equal
def equal_xor_sum ( arr , n ) : NEW_LINE INDENT Sum = 0 ; NEW_LINE Xor = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum = Sum + arr [ i ] ; NEW_LINE Xor = Xor ^ arr [ i ] ; NEW_LINE DEDENT if ( Sum == Xor ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 3 , 7 , 10 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE equal_xor_sum ( arr , n ) ; NEW_LINE DEDENT
Count of odd length contiguous Palindromic sequences in a Matrix | Python code to Count the odd length contiguous Palindromic sequences in the matrix ; Function to count the number of contiguous palindromic sequences in the matrix ; Add the total number of elements in the matrix to the count ; Length of possible sequence to be checked for palindrome horizontally and vertically ; Iterate through each element of the matrix and count the number of palindromic sequences in each row and column ; Find the possible length of sequences that can be a palindrome ; From i , check if the sequence formed by elements to its left and right is palindrome or not ; if the sequence [ i , j - k ] to [ i , j + k ] is a palindrome , increment the count by 1 ; From i , check if the sequence formed by elements to its above and below is palindrome or not ; if the sequence [ i - k , j ] to [ i + k , j ] is a palindrome , increment the count by 1 ; Return the total count of the palindromic sequences ; Driver code
MAX = 10 ; NEW_LINE def countPalindromes ( n , m , matrix ) : NEW_LINE INDENT count = n * m ; NEW_LINE length_of_sequence_row = 0 ; NEW_LINE length_of_sequence_column = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT length_of_sequence_row = min ( j , m - 1 - j ) ; NEW_LINE length_of_sequence_column = min ( i , n - i - 1 ) ; NEW_LINE for k in range ( 1 , length_of_sequence_row + 1 ) : NEW_LINE INDENT if ( matrix [ i ] [ j - k ] == matrix [ i ] [ j + k ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT for k in range ( 1 , length_of_sequence_column + 1 ) : NEW_LINE INDENT if ( matrix [ i - k ] [ j ] == matrix [ i + k ] [ j ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 3 ; NEW_LINE n = 3 ; NEW_LINE matrix = [ 2 , 1 , 2 ] , [ 1 , 1 , 1 ] , [ 2 , 1 , 2 ] ; NEW_LINE print ( countPalindromes ( n , m , matrix ) ) ; NEW_LINE DEDENT
Reduce a number to 1 by performing given operations | Set 2 | Function to return the number of set bits in n ; Function to return the minimum steps required to reach 1 ; If n is even then divide it by 2 ; If n is 3 or the number of set bits in ( n - 1 ) is less than the number of set bits in ( n + 1 ) ; Increment the number of steps ; Return the minimum number of steps ; Driver code
def set_bits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += n % 2 NEW_LINE n //= 2 NEW_LINE DEDENT return count NEW_LINE DEDENT def minSteps ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( n != 1 ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT n //= 2 NEW_LINE DEDENT elif ( n == 3 or set_bits ( n - 1 ) < set_bits ( n + 1 ) ) : NEW_LINE INDENT n -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT n += 1 NEW_LINE DEDENT ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 15 NEW_LINE print ( minSteps ( n ) ) NEW_LINE
Minimum integer that can be obtained by swapping adjacent digits of different parity | Function to return the minimum number ; Store the elements which are divisible by two in stack1 ; Store the elements which are not divisible by two in stack2 . ; Concatenate the answer with smaller value of the topmost elements of both the stacks and then pop that element ; Concatenate the answer with remaining values of stack1 . ; Concatenate the answer with remaining values of stack2 . ; Driver code ; Function calling
def minimumNo ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE stack1 = [ ] NEW_LINE stack2 = [ ] NEW_LINE while ( n != 0 ) : NEW_LINE INDENT r = n % 10 NEW_LINE if ( r % 2 == 0 ) : NEW_LINE INDENT stack1 . append ( r ) NEW_LINE DEDENT else : NEW_LINE INDENT stack2 . append ( r ) NEW_LINE DEDENT n = n // 10 NEW_LINE DEDENT while ( len ( stack1 ) > 0 and len ( stack2 ) > 0 ) : NEW_LINE INDENT if ( stack1 [ - 1 ] < stack2 [ - 1 ] ) : NEW_LINE INDENT ans = ans * 10 + stack1 [ - 1 ] NEW_LINE del stack1 [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT ans = ans * 10 + stack2 [ - 1 ] NEW_LINE del stack2 [ - 1 ] NEW_LINE DEDENT DEDENT while ( len ( stack1 ) > 0 ) : NEW_LINE INDENT ans = ans * 10 + stack1 [ - 1 ] NEW_LINE del stack1 [ - 1 ] NEW_LINE DEDENT while ( len ( stack2 ) > 0 ) : NEW_LINE INDENT ans = ans * 10 + stack2 [ - 1 ] NEW_LINE del stack2 [ - 1 ] NEW_LINE DEDENT return ans NEW_LINE DEDENT n1 = 64432 NEW_LINE print ( minimumNo ( n1 ) ) NEW_LINE n2 = 3137 NEW_LINE print ( minimumNo ( n2 ) ) NEW_LINE
Count of possible arrays from prefix | Function to find power of a number . ; Function to find factorial of a number . ; Function to print no of arrays ; c variable counts the no of pairs ; Map to store the frequency of each element ; Sum of all elements of the array ; Variable to check if it is possible to make any array ; First element of suffix array and the last element of prefix array ; Check if the element exists in the map ; If elements of any pair are equal and their frequency is not divisible by 2 update the isArrayPossible variable to false and break through the loop ; If elements of any pair are not equal and their frequency is not same update the isArrayPossible variable to false and break through the loop ; Check if frequency is greater than zero ; update the count of pairs ; Multiply the answer by 2 ^ ( frequency of pairs ) since the elements of the pair are not the same in this condition ; Divide the answer by the factorial of no of similar pairs ; Make frequency of both these elements 0 ; Update the count of pairs ; Divide the answer by the factorial of no . of similar pairs ; Make frequency of this element 0 ; Check if it is possible to make the array and there are n - 1 pairs whose sum will be equal to s1 ; Driver code ; Function calling
def power ( a , b ) : NEW_LINE INDENT result = 1 ; NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( b % 2 == 1 ) : NEW_LINE INDENT result = result * a ; NEW_LINE DEDENT a = a * a ; NEW_LINE b = b // 2 ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT def factorial ( n ) : NEW_LINE INDENT fact = 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fact = fact * i ; NEW_LINE DEDENT return fact ; NEW_LINE DEDENT def findNoOfArrays ( a , n ) : NEW_LINE INDENT sum = 0 ; c = 0 ; NEW_LINE mp = dict . fromkeys ( a , 0 ) ; NEW_LINE for i in range ( 2 * n ) : NEW_LINE INDENT mp [ a [ i ] ] += 1 ; NEW_LINE sum = sum + a [ i ] ; NEW_LINE DEDENT isArrayPossible = True ; NEW_LINE ans = factorial ( n - 1 ) ; NEW_LINE s1 = sum // ( n + 1 ) ; NEW_LINE if ( mp [ s1 ] >= 2 ) : NEW_LINE INDENT mp [ s1 ] = mp [ s1 ] - 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT isArrayPossible = False ; NEW_LINE DEDENT if ( isArrayPossible ) : NEW_LINE INDENT for first , second in mp . items ( ) : NEW_LINE INDENT if ( first == s1 - first ) : NEW_LINE INDENT if ( mp [ first ] % 2 != 0 ) : NEW_LINE INDENT isArrayPossible = False ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( first != s1 - first ) : NEW_LINE INDENT if s1 - first in mp : NEW_LINE INDENT if ( mp [ first ] != mp [ s1 - first ] ) : NEW_LINE INDENT isArrayPossible = False ; NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT if ( second > 0 ) : NEW_LINE INDENT if ( first != s1 - first ) : NEW_LINE INDENT c = c + second ; NEW_LINE ans = ans * power ( 2 , second ) ; NEW_LINE ans = ans / factorial ( second ) ; NEW_LINE mp [ first ] = 0 ; NEW_LINE mp [ s1 - first ] = 0 ; NEW_LINE DEDENT if ( first == s1 - first ) : NEW_LINE INDENT c = c + second // 2 ; NEW_LINE ans = ans // factorial ( second // 2 ) ; NEW_LINE mp [ first ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( c < n - 1 or isArrayPossible == False ) : NEW_LINE INDENT print ( "0" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr1 = [ 5 , 2 , 3 , 5 ] ; NEW_LINE n1 = len ( arr1 ) ; NEW_LINE findNoOfArrays ( arr1 , n1 // 2 ) ; NEW_LINE arr2 = [ - 1 , - 1 , - 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 0 , 0 ] ; NEW_LINE n2 = len ( arr2 ) ; NEW_LINE findNoOfArrays ( arr2 , n2 // 2 ) ; NEW_LINE DEDENT
Find two numbers with the given LCM and minimum possible difference | Python3 implementation of the approach ; Function to return the LCM of a and b ; Function to find and print the two numbers ; To find the factors ; To check if i is a factor of x and the minimum possible number satisfying the given conditions ; Driver code
from math import gcd as __gcd , sqrt , ceil NEW_LINE def lcm ( a , b ) : NEW_LINE INDENT return ( a // __gcd ( a , b ) * b ) NEW_LINE DEDENT def findNums ( x ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , ceil ( sqrt ( x ) ) ) : NEW_LINE INDENT if ( x % i == 0 and lcm ( i , x // i ) == x ) : NEW_LINE INDENT ans = i NEW_LINE DEDENT DEDENT print ( ans , ( x // ans ) ) NEW_LINE DEDENT x = 12 NEW_LINE findNums ( x ) NEW_LINE
Find an integer that is common in the maximum number of given arithmetic progressions | Python implementation of the approach ; Function to return element common in maximum number of APs ; Initialize the count variable ; Increment count for every element of an AP ; Find the index with maximum count ; Return the maximum common element ; Driver code
MAXN = 1000000 NEW_LINE def maxCommonElement ( A , D , N ) : NEW_LINE INDENT cnt = [ 0 ] * MAXN NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( A [ i ] , MAXN , D [ i ] ) : NEW_LINE INDENT cnt [ j ] += 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE com = 0 NEW_LINE for i in range ( MAXN ) : NEW_LINE INDENT if cnt [ i ] > ans : NEW_LINE INDENT ans = cnt [ i ] NEW_LINE com = i NEW_LINE DEDENT DEDENT return com NEW_LINE DEDENT A = [ 13 , 1 , 2 , 5 ] NEW_LINE D = [ 5 , 10 , 1 , 12 ] NEW_LINE N = len ( A ) NEW_LINE print ( maxCommonElement ( A , D , N ) ) NEW_LINE
Number of trailing zeros in N * ( N | Function to return the count of trailing 0 s in the given function ; If n is odd ; If n is even ; Find the trailing zeros in n / 2 factorial ; Return the required answer ; Driver code
def findTrailingZeros ( n ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT ans = 0 NEW_LINE n //= 2 NEW_LINE while ( n ) : NEW_LINE INDENT ans += n // 5 NEW_LINE n //= 5 NEW_LINE DEDENT return ans NEW_LINE DEDENT DEDENT n = 12 NEW_LINE print ( findTrailingZeros ( n ) ) NEW_LINE
Divide N into K unique parts such that gcd of those parts is maximum | Python3 implementation of the approach ; Function to calculate maximum GCD ; Minimum possible sum for K unique positive integers ; It is not possible to divide N into K unique parts ; All the factors greater than sqrt ( N ) are complementary of the factors less than sqrt ( N ) ; If i is a factor of N ; Driver code
from math import sqrt , ceil , floor NEW_LINE def maxGCD ( N , K ) : NEW_LINE INDENT minSum = ( K * ( K + 1 ) ) / 2 NEW_LINE if ( N < minSum ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT i = ceil ( sqrt ( N ) ) NEW_LINE res = 1 NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( i >= minSum ) : NEW_LINE INDENT res = max ( res , N / i ) NEW_LINE DEDENT if ( N / i >= minSum ) : NEW_LINE INDENT res = max ( res , i ) NEW_LINE DEDENT DEDENT i -= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT N = 18 NEW_LINE K = 3 NEW_LINE print ( maxGCD ( N , K ) ) NEW_LINE
Radius of the inscribed circle within three tangent circles | Python3 implementation of the approach ; Radius of the 3 given circles ; Calculation of area of a triangle by Heron 's formula ; Applying binary search to find the radius r4 of the required circle ; Area of main triangle ; Loop runs until l and h becomes approximately equal ; Area of smaller triangles ; If sum of smaller triangles is less than main triangle ; If sum of smaller triangles is greater than or equal to main triangle ; Taking r1 , r2 , r3 as input ; Call to function binary search
import math NEW_LINE r1 = 0 NEW_LINE r2 = 0 NEW_LINE r3 = 0 NEW_LINE def area ( a , b , c ) : NEW_LINE INDENT p = ( a + b + c ) / 2 NEW_LINE return ( ( math . sqrt ( p ) ) * ( math . sqrt ( p - a ) ) * ( math . sqrt ( p - b ) ) * ( math . sqrt ( p - c ) ) ) NEW_LINE DEDENT def binary_search ( ) : NEW_LINE INDENT global r1 , r2 , r3 NEW_LINE s = area ( r1 + r2 , r2 + r3 , r3 + r1 ) NEW_LINE l = 0 NEW_LINE h = s / ( r1 + r2 + r3 ) NEW_LINE while ( h - l > 0.00000001 ) : NEW_LINE INDENT mid = ( l + h ) / 2 NEW_LINE s1 = area ( mid + r1 , mid + r2 , r1 + r2 ) NEW_LINE s2 = area ( mid + r1 , mid + r3 , r1 + r3 ) NEW_LINE s3 = area ( mid + r2 , mid + r3 , r2 + r3 ) NEW_LINE if ( s1 + s2 + s3 < s ) : NEW_LINE INDENT l = mid NEW_LINE DEDENT else : NEW_LINE INDENT h = mid NEW_LINE DEDENT DEDENT return ( ( l + h ) / 2 ) NEW_LINE DEDENT r1 = 1 NEW_LINE r2 = 2 NEW_LINE r3 = 3 NEW_LINE print ( " { 0 : . 6f } " . format ( binary_search ( ) ) ) NEW_LINE
Radius of the inscribed circle within three tangent circles | Python3 implementation of the approach ; Taking r1 , r2 , r3 as input ; Calculation of r4 using formula given above
from math import sqrt NEW_LINE r1 = 1 NEW_LINE r2 = 2 NEW_LINE r3 = 3 NEW_LINE r4 = ( r1 * r2 * r3 ) / ( r1 * r2 + r2 * r3 + r1 * r3 + 2.0 * sqrt ( r1 * r2 * r3 * ( r1 + r2 + r3 ) ) ) NEW_LINE print ( round ( r4 , 6 ) ) NEW_LINE
Make all elements zero by decreasing any two elements by one at a time | Function that returns true if all the array elements can be made 0 with the given operation ; Find the maximum element and the sum ; Check the required condition ; Driver code
def checkZeroArray ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE maximum = - 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + arr [ i ] NEW_LINE maximum = max ( maximum , arr [ i ] ) NEW_LINE DEDENT if ( sum % 2 == 0 and maximum <= sum // 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT arr = [ 1 , 2 , 1 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE if ( checkZeroArray ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Subarray permutation that satisfies the given condition | Function that returns true if the required subarray exists in the given array ; Map to store the positions of each integer in the original permutation ; To store the address of each entry in arr [ n ] but with 1 - based indexing ; To track minimum position sumcur for sum of a positions ti this position ; Summing up addresses ; Tracking minimum address encountered ti now ; The sum of the addresses if it forms the required subarray ; If current sum of address is equal to val ; Driver code
def subArray ( arr , n , m ) : NEW_LINE INDENT i = 0 NEW_LINE mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] = i + 1 NEW_LINE DEDENT sumcur = 0 NEW_LINE p = 10 ** 9 NEW_LINE ans = [ ] NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT sumcur += mp [ i ] NEW_LINE p = min ( p , mp [ i ] ) NEW_LINE val = p * i - i + ( i * ( i + 1 ) ) / 2 NEW_LINE if ( i == m ) : NEW_LINE INDENT if ( val == sumcur ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT DEDENT arr = [ 4 , 5 , 1 , 3 , 2 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE m = 3 NEW_LINE if ( subArray ( arr , n , m ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Sum of all N digit palindrome numbers | Python program for the above approach ; Function to check palindrome ; Function to calculate the sum of n - digit palindrome ; Run a loop to check all possible palindrome ; If palindrome append sum ; Driver code
import math NEW_LINE def isPalindrome ( s ) : NEW_LINE INDENT left = 0 NEW_LINE right = len ( s ) - 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT if ( s [ left ] != s [ right ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT left = left + 1 NEW_LINE right = right - 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def getSum ( n ) : NEW_LINE INDENT start = int ( math . pow ( 10 , n - 1 ) ) NEW_LINE end = int ( math . pow ( 10 , n ) ) - 1 NEW_LINE sum = 0 NEW_LINE for i in range ( start , end + 1 ) : NEW_LINE INDENT s = str ( i ) NEW_LINE if ( isPalindrome ( s ) ) : NEW_LINE INDENT sum = sum + i NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT n = 1 NEW_LINE ans = getSum ( n ) NEW_LINE print ( ans ) NEW_LINE
Sum of all N digit palindrome numbers | Function to calculate sum of n digit number ; Corner case ; Using above approach ; Driver code
def getSum ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE if ( n == 1 ) : NEW_LINE INDENT sum = 45.0 ; NEW_LINE DEDENT else : NEW_LINE INDENT sum = ( 99.0 / 2.0 ) * pow ( 10 , n - 1 ) * pow ( 10 , ( n - 1 ) / 2 ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 ; NEW_LINE ans = int ( getSum ( n ) ) ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT
Count number of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] | Function to return the count of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] ; Increment count if condition satisfy ; Return count of pairs ; Driver code ; Get and print count of pairs
def countPairs ( arr , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] * arr [ j ] == arr [ i ] + arr [ j ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 0 , 3 , 2 , 0 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countPairs ( arr , n ) ) ; NEW_LINE DEDENT
Count number of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] | Function to return the count of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] ; Count number of 0 ' s ▁ and ▁ 2' s in the array ; Total pairs due to occurrence of 0 's ; Total pairs due to occurrence of 2 's ; Return count of all pairs ; Driver code ; Get and print count of pairs
def countPairs ( arr , n ) : NEW_LINE INDENT countZero = 0 ; NEW_LINE countTwo = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT countZero += 1 ; NEW_LINE DEDENT elif ( arr [ i ] == 2 ) : NEW_LINE INDENT countTwo += 1 ; NEW_LINE DEDENT DEDENT pair0 = ( countZero * ( countZero - 1 ) ) // 2 ; NEW_LINE pair2 = ( countTwo * ( countTwo - 1 ) ) // 2 ; NEW_LINE return pair0 + pair2 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 0 , 3 , 2 , 0 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countPairs ( arr , n ) ) ; NEW_LINE DEDENT
Number of subsequences with positive product | Python 3 implementation of the approach ; Function to return the count of all the subsequences with positive product ; To store the count of positive elements in the array ; To store the count of negative elements in the array ; If the current element is positive ; If the current element is negative ; For all the positive elements of the array ; For all the negative elements of the array ; For the empty subsequence ; Driver code
import math NEW_LINE def cntSubSeq ( arr , n ) : NEW_LINE INDENT pos_count = 0 ; NEW_LINE neg_count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT pos_count += 1 NEW_LINE DEDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT neg_count += 1 NEW_LINE DEDENT DEDENT result = int ( math . pow ( 2 , pos_count ) ) NEW_LINE if ( neg_count > 0 ) : NEW_LINE INDENT result *= int ( math . pow ( 2 , neg_count - 1 ) ) NEW_LINE DEDENT result -= 1 NEW_LINE return result NEW_LINE DEDENT arr = [ 2 , - 3 , - 1 , 4 ] NEW_LINE n = len ( arr ) ; NEW_LINE print ( cntSubSeq ( arr , n ) ) NEW_LINE
Smallest number dividing minimum number of elements in the array | Set 2 | Function to return the smallest number that divides minimum number of elements in the given array ; m stores the maximum in the array ; Frequency array ; Sieve ; Incrementing j ; If no multiples of j are in the array ; Driver code
def findMin ( arr , n ) : NEW_LINE INDENT m = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT m = max ( m , arr [ i ] ) NEW_LINE DEDENT freq = [ 0 ] * ( m + 2 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( 1 , m + 2 ) : NEW_LINE INDENT j = i NEW_LINE cnt = 0 NEW_LINE while ( j <= m ) : NEW_LINE INDENT cnt += freq [ j ] NEW_LINE j += i NEW_LINE DEDENT if ( not cnt ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return m + 1 NEW_LINE DEDENT arr = [ 2 , 12 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMin ( arr , n ) ) NEW_LINE
Smallest number dividing minimum number of elements in the Array | Function to return the smallest number that divides minimum number of elements ; m stores the maximum in the array ; Frequency table ; Loop to factorize ; sqrt factorization of the numbers ; Finding the smallest number with zero multiples ; Driver code
def findMin ( arr , n ) : NEW_LINE INDENT m = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT m = max ( m , arr [ i ] ) NEW_LINE DEDENT cnt = [ 0 ] * ( m + 2 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = 1 NEW_LINE while j * j <= arr [ i ] : NEW_LINE INDENT if ( arr [ i ] % j == 0 ) : NEW_LINE INDENT if ( j * j == arr [ i ] ) : NEW_LINE INDENT cnt [ j ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt [ j ] += 1 NEW_LINE cnt [ arr [ i ] // j ] += 1 NEW_LINE DEDENT DEDENT j += 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , m + 2 ) : NEW_LINE INDENT if ( cnt [ i ] == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 12 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMin ( arr , n ) ) NEW_LINE
Remove two consecutive integers from 1 to N to make sum equal to S | Function to find the numbers to be removed ; typecast appropriately so that answer is float ; return the obtained result ; Convert i to integer ; If i is an integer is 0 then answer is Yes ; Driver code
def findNumber ( N , S ) : NEW_LINE INDENT i = ( ( ( N ) * ( N + 1 ) ) / 4 ) - ( ( S + 1 ) / 2 ) ; NEW_LINE return i ; NEW_LINE DEDENT def check ( N , S ) : NEW_LINE INDENT i = findNumber ( N , S ) ; NEW_LINE integerI = int ( i ) ; NEW_LINE if ( i - integerI == 0 ) : NEW_LINE INDENT print ( " Yes : " , integerI , " , " , integerI + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 ; NEW_LINE S = 3 ; NEW_LINE check ( N , S ) ; NEW_LINE N = 5 ; NEW_LINE S = 3 ; NEW_LINE check ( N , S ) ; NEW_LINE DEDENT
Remove all the prime numbers from the given array | Python3 implementation of the approach ; Function for Sieve of Eratosthenes ; Function to pr the elements of the array ; Function to remove all the prime numbers ; Generate primes ; Traverse the array ; If the current element is prime ; Shift all the elements on the right of it to the left ; Decrease the loop counter by 1 to check the shifted element ; Decrease the length ; Pr the updated array ; Driver code
sz = 10 ** 5 NEW_LINE isPrime = [ True for i in range ( sz + 1 ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT isPrime [ 0 ] = isPrime [ 1 ] = False NEW_LINE i = 2 NEW_LINE while i * i < sz : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , sz , i ) : NEW_LINE INDENT isPrime [ j ] = False NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def prArray ( arr , lenn ) : NEW_LINE INDENT for i in range ( lenn ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def removePrimes ( arr , lenn ) : NEW_LINE INDENT sieve ( ) NEW_LINE i = 0 NEW_LINE while i < lenn : NEW_LINE INDENT if ( isPrime [ arr [ i ] ] ) : NEW_LINE INDENT for j in range ( i , lenn - 1 ) : NEW_LINE INDENT arr [ j ] = arr [ j + 1 ] NEW_LINE DEDENT i -= 1 NEW_LINE lenn -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT prArray ( arr , lenn ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 6 , 5 , 3 , 8 , 7 , 10 , 11 , 14 , 15 ] NEW_LINE lenn = len ( arr ) NEW_LINE removePrimes ( arr , lenn ) NEW_LINE DEDENT
Remove one element to get minimum OR value | Function to return the minimized OR after removing an element from the array ; Base case ; Prefix and suffix OR array ; Computing prefix / suffix OR arrays ; To store the final answer ; Finding the final answer ; Returning the final answer ; Driver code
def minOR ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT pre = [ 0 ] * n NEW_LINE suf = [ 0 ] * n NEW_LINE pre [ 0 ] = arr [ 0 ] NEW_LINE suf [ n - 1 ] = arr [ n - 1 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT pre [ i ] = ( pre [ i - 1 ] arr [ i ] ) NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suf [ i ] = ( suf [ i + 1 ] arr [ i ] ) NEW_LINE DEDENT ans = min ( pre [ n - 2 ] , suf [ 1 ] ) NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT ans = min ( ans , ( pre [ i - 1 ] suf [ i + 1 ] ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minOR ( arr , n ) ) NEW_LINE DEDENT
Check if there exists a prime number which gives Y after being repeatedly subtracted from X | Function that returns true if any prime number satisfies the given conditions ; No such prime exists ; Driver code
def isPossible ( x , y ) : NEW_LINE INDENT if ( ( x - y ) == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT x = 100 NEW_LINE y = 98 NEW_LINE if ( isPossible ( x , y ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Find number of square of area Z which can be built in a matrix having blocked regions | Python3 implementation of the approach ; Function to calculate the number of square areas of size K * K ; Row array and column array to store the lengths of differences between consecutive rows / columns ; Fill the conrow vector ; Fill the concol vector ; To store the required answer ; Every pair of row size and column size would result in an unblocked region ; Driver code
from math import sqrt NEW_LINE def subgrids ( N , Z , row , col , r , d ) : NEW_LINE INDENT conrow = [ ] ; NEW_LINE concol = [ ] ; NEW_LINE K = int ( sqrt ( Z ) ) ; NEW_LINE conrow . append ( row [ 0 ] - 0 - 1 ) NEW_LINE conrow . append ( N + 1 - row [ r - 1 ] - 1 ) NEW_LINE for i in range ( 1 , r ) : NEW_LINE INDENT conrow . append ( row [ i ] - row [ i - 1 ] - 1 ) ; NEW_LINE DEDENT concol . append ( col [ 0 ] - 0 - 1 ) NEW_LINE concol . append ( N + 1 - col [ d - 1 ] - 1 ) NEW_LINE for i in range ( 1 , d ) : NEW_LINE INDENT concol . append ( col [ i ] - col [ i - 1 ] - 1 ) ; NEW_LINE DEDENT row_size = len ( conrow ) NEW_LINE col_size = len ( concol ) NEW_LINE answer = 0 NEW_LINE for i in range ( row_size ) : NEW_LINE INDENT for j in range ( col_size ) : NEW_LINE INDENT total = ( concol [ j ] // K ) * ( conrow [ i ] // K ) NEW_LINE answer += ( total ) NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 8 ; Z = 4 NEW_LINE row = [ 4 , 6 ] NEW_LINE col = [ 3 , 8 ] NEW_LINE r = len ( row ) NEW_LINE d = len ( col ) NEW_LINE print ( subgrids ( N , Z , row , col , r , d ) ) NEW_LINE DEDENT
Count of numbers whose sum of increasing powers of digits is equal to the number itself | Function to return the count of digits of n ; Function to return the sum of increasing powers of N ; To store the required answer ; Count of digits in n which will be the power of the last digit ; While there are digits left ; Get the last digit ; Add the last digit after raising it to the required power ; Decrement the power for the previous digit ; Remove the last digit ; Function to return the count of integers which satisfy the given conditions ; If current element satisfies the given condition ; Driver code
def countDigits ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE n //= 10 NEW_LINE DEDENT return cnt NEW_LINE DEDENT def digitPowSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE pw = countDigits ( n ) NEW_LINE while ( n > 0 ) : NEW_LINE INDENT d = n % 10 NEW_LINE sum += pow ( d , pw ) NEW_LINE pw -= 1 NEW_LINE n //= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def countNum ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( i == digitPowSum ( i ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT n = 200 NEW_LINE print ( countNum ( n ) ) NEW_LINE
Print all perfect squares from the given range | Function to print all the perfect squares from the given range ; For every element from the range ; If current element is a perfect square ; Driver code
def perfectSquares ( l , r ) : NEW_LINE INDENT for i in range ( l , r + 1 ) : NEW_LINE INDENT if ( i ** ( .5 ) == int ( i ** ( .5 ) ) ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT l = 2 NEW_LINE r = 24 NEW_LINE perfectSquares ( l , r ) NEW_LINE
Print all perfect squares from the given range | Python3 implementation of the approach ; Function to print all the perfect squares from the given range ; Getting the very first number ; First number 's square ; Next number is at the difference of ; While the perfect squares are from the range ; Print the perfect square ; Get the next perfect square ; Next odd number to be added ; Driver code
from math import ceil , sqrt NEW_LINE def perfectSquares ( l , r ) : NEW_LINE INDENT number = ceil ( sqrt ( l ) ) ; NEW_LINE n2 = number * number ; NEW_LINE number = ( number * 2 ) + 1 ; NEW_LINE while ( ( n2 >= l and n2 <= r ) ) : NEW_LINE INDENT print ( n2 , end = " ▁ " ) ; NEW_LINE n2 = n2 + number ; NEW_LINE number += 2 ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 2 ; r = 24 ; NEW_LINE perfectSquares ( l , r ) ; NEW_LINE DEDENT
Find the value of N XOR 'ed to itself K times | Function to return n ^ n ^ ... k times ; Find the result ; Driver code
def xorK ( n , k ) : NEW_LINE INDENT res = n NEW_LINE for i in range ( 1 , k ) : NEW_LINE INDENT res = ( res ^ n ) NEW_LINE DEDENT return n NEW_LINE DEDENT n = 123 NEW_LINE k = 3 NEW_LINE print ( xorK ( n , k ) ) NEW_LINE
Find all the possible remainders when N is divided by all positive integers from 1 to N + 1 | Python3 implementation of the approach ; Function to find all the distinct remainders when n is divided by all the elements from the range [ 1 , n + 1 ] ; Set will be used to store the remainders in order to eliminate duplicates ; Find the remainders ; Print the contents of the set ; Driver code
from math import ceil , floor , sqrt NEW_LINE def findRemainders ( n ) : NEW_LINE INDENT vc = dict ( ) NEW_LINE for i in range ( 1 , ceil ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT vc [ n // i ] = 1 NEW_LINE DEDENT for i in range ( n // ceil ( sqrt ( n ) ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT vc [ i ] = 1 NEW_LINE DEDENT for it in sorted ( vc ) : NEW_LINE INDENT print ( it , end = " ▁ " ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE findRemainders ( n ) NEW_LINE
Count of primes below N which can be expressed as the sum of two primes | Python3 implementation of the approach ; Function for Sieve of Eratosthenes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to return the count of primes less than or equal to n which can be expressed as the sum of two primes ; To store the required count ; If the integer is prime and it can be expressed as the sum of 2 and a prime number ; Driver code
MAX = 100005 NEW_LINE prime = [ True for i in range ( MAX ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( MAX ) : NEW_LINE INDENT if ( p * p > MAX ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( 2 * p , MAX , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def countPrimes ( n ) : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE cnt = 0 NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( prime [ i ] and prime [ i - 2 ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT n = 11 NEW_LINE print ( countPrimes ( n ) ) NEW_LINE
Print all palindrome dates between the given years | Python 3 implementation of the approach ; Returns true if given year is valid ; Return true if year is a multiple pf 4 and not multiple of 100. OR year is multiple of 400. ; Returns true if given year is valid or not . ; If year , month and day are not in given range ; Handle February month with leap year ; Months of April , June , Sept and Nov must have number of days less than or equal to 30. ; Function to print the palindrome dates between the given years ; For every year ; Current year as a string ; To store the reverse of year ; Get the day and the month ; If the current palindrome date is valid ; Driver code
MAX_VALID_YR = 9999 NEW_LINE MIN_VALID_YR = 1800 NEW_LINE def isLeap ( year ) : NEW_LINE INDENT return ( ( ( year % 4 == 0 ) and ( year % 100 != 0 ) ) or ( year % 400 == 0 ) ) NEW_LINE DEDENT def isValidDate ( d , m , y ) : NEW_LINE INDENT if ( y > MAX_VALID_YR or y < MIN_VALID_YR ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( m < 1 or m > 12 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( d < 1 or d > 31 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( m == 2 ) : NEW_LINE INDENT if ( isLeap ( y ) ) : NEW_LINE INDENT return ( d <= 29 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( d <= 28 ) NEW_LINE DEDENT DEDENT if ( m == 4 or m == 6 or m == 9 or m == 11 ) : NEW_LINE INDENT return ( d <= 30 ) NEW_LINE DEDENT return True NEW_LINE DEDENT def printPalindromeDates ( y1 , y2 ) : NEW_LINE INDENT for year in range ( y1 , y2 + 1 , 1 ) : NEW_LINE INDENT str1 = str ( year ) NEW_LINE rev = str1 NEW_LINE rev = rev [ : : - 1 ] NEW_LINE day = int ( rev [ 0 : 2 ] ) NEW_LINE month = int ( rev [ 2 : 4 ] ) NEW_LINE rev += str1 NEW_LINE if ( isValidDate ( day , month , year ) ) : NEW_LINE INDENT print ( rev ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT y1 = 2001 NEW_LINE y2 = 2005 NEW_LINE printPalindromeDates ( y1 , y2 ) NEW_LINE DEDENT
Find an integer in the given range that satisfies the given conditions | Python3 implementation of the approach ; Function that returns true if x contains all distinct digits ; Last digit of x ; If current digit has appeared before ; Mark the current digit to present ; Remove the last digit ; Function to return the required value of k ; To store the maximum value for the given expression ; If i contains all distinct digits ; If the value of the expression is also maximum then update k and the expression ; Driver code
import sys NEW_LINE MAX = 10 NEW_LINE def distinctDigits ( x ) : NEW_LINE INDENT present = [ False for i in range ( MAX ) ] NEW_LINE while ( x > 0 ) : NEW_LINE INDENT digit = x % 10 NEW_LINE if ( present [ digit ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT present [ digit ] = True NEW_LINE x = x // 10 NEW_LINE DEDENT return True NEW_LINE DEDENT def findK ( l , r ) : NEW_LINE INDENT maxExp = - sys . maxsize - 1 NEW_LINE k = - 1 NEW_LINE for i in range ( l , r + 1 , 1 ) : NEW_LINE INDENT if ( distinctDigits ( i ) ) : NEW_LINE INDENT exp = ( l - i ) * ( i - r ) NEW_LINE if ( exp >= maxExp ) : NEW_LINE INDENT k = i ; NEW_LINE maxExp = exp NEW_LINE DEDENT DEDENT DEDENT return k NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l = 50 NEW_LINE r = 60 NEW_LINE print ( findK ( l , r ) ) NEW_LINE DEDENT
Convert Decimal To Hexa | Function to convert decimal no . to hexadecimal number ; map for decimal to hexa , 0 - 9 are straightforward , alphabets a - f used for 10 to 15. ; string to be returned ; check if num is 0 and directly return "0" ; if num > 0 , use normal technique as discussed in other post ; if num < 0 , we need to use the elaborated trick above , lets see this ; store num in a u_int , size of u_it is greater , it will be positive since msb is 0 ; use the same remainder technique . ; Driver Code
def Hex ( num ) : NEW_LINE INDENT m = dict . fromkeys ( range ( 16 ) , 0 ) ; NEW_LINE digit = ord ( '0' ) ; NEW_LINE c = ord ( ' a ' ) ; NEW_LINE for i in range ( 16 ) : NEW_LINE INDENT if ( i < 10 ) : NEW_LINE INDENT m [ i ] = chr ( digit ) ; NEW_LINE digit += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT m [ i ] = chr ( c ) ; NEW_LINE c += 1 NEW_LINE DEDENT DEDENT res = " " ; NEW_LINE if ( not num ) : NEW_LINE INDENT return "0" ; NEW_LINE DEDENT if ( num > 0 ) : NEW_LINE INDENT while ( num ) : NEW_LINE INDENT res = m [ num % 16 ] + res ; NEW_LINE num //= 16 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT n = num + 2 ** 32 ; NEW_LINE while ( n ) : NEW_LINE INDENT res = m [ n % 16 ] + res ; NEW_LINE n //= 16 ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 134 ; y = - 1 ; z = - 234 ; NEW_LINE print ( " Hexa ▁ representation ▁ for " ) ; NEW_LINE print ( x , " is " , Hex ( x ) ) ; NEW_LINE print ( y , " is " , Hex ( y ) ) ; NEW_LINE print ( z , " is " , Hex ( z ) ) ; NEW_LINE DEDENT
Find the player who will win the Coin game | Function to check the wining player ; As discussed in the above approach ; Driver Code
def findWinner ( n ) : NEW_LINE INDENT if ( ( n - 1 ) % 6 == 0 ) : NEW_LINE INDENT print ( " Second ▁ Player ▁ wins ▁ the ▁ game " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " First ▁ Player ▁ wins ▁ the ▁ game " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 ; NEW_LINE findWinner ( n ) ; NEW_LINE DEDENT
Find ways to arrange K green balls among N balls such that exactly i moves is needed to collect all K green balls | Python3 implementation of the approach ; To store the factorial and the factorial mod inverse of a number ; Function to find ( a ^ m1 ) % mod ; Function to find factorial of all the numbers ; Function to find the factorial mod inverse of all the numbers ; Function to return nCr ; Function to find ways to arrange K green balls among N balls such that we need exactly i moves to collect all K green balls ; Driver code ; Function call
N = 100005 NEW_LINE mod = ( int ) ( 1e9 + 7 ) NEW_LINE factorial = [ 0 ] * N ; NEW_LINE modinverse = [ 0 ] * N ; NEW_LINE def power ( a , m1 ) : NEW_LINE INDENT if ( m1 == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( m1 == 1 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT elif ( m1 == 2 ) : NEW_LINE INDENT return ( a * a ) % mod ; NEW_LINE DEDENT elif ( m1 & 1 ) : NEW_LINE INDENT return ( a * power ( power ( a , m1 // 2 ) , 2 ) ) % mod ; NEW_LINE DEDENT else : NEW_LINE INDENT return power ( power ( a , m1 // 2 ) , 2 ) % mod ; NEW_LINE DEDENT DEDENT def factorialfun ( ) : NEW_LINE INDENT factorial [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT factorial [ i ] = ( factorial [ i - 1 ] * i ) % mod ; NEW_LINE DEDENT DEDENT def modinversefun ( ) : NEW_LINE INDENT modinverse [ N - 1 ] = power ( factorial [ N - 1 ] , mod - 2 ) % mod ; NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT modinverse [ i ] = ( modinverse [ i + 1 ] * ( i + 1 ) ) % mod ; NEW_LINE DEDENT DEDENT def binomial ( n , r ) : NEW_LINE INDENT if ( r > n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT a = ( factorial [ n ] * modinverse [ n - r ] ) % mod ; NEW_LINE a = ( a * modinverse [ r ] ) % mod ; NEW_LINE return a ; NEW_LINE DEDENT def arrange_balls ( n , k ) : NEW_LINE INDENT factorialfun ( ) ; NEW_LINE modinversefun ( ) ; NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT print ( ( binomial ( n - k + 1 , i ) * binomial ( k - 1 , i - 1 ) ) % mod , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; k = 3 ; NEW_LINE arrange_balls ( n , k ) ; NEW_LINE DEDENT
Minimum inversions required so that no two adjacent elements are same | Function to return the minimum inversions required so that no two adjacent elements are same ; To store the inversions required to make the array { 1 , 0 , 1 , 0 , 1 , 0 , 1 , ... } and { 0 , 1 , 0 , 1 , 0 , 1 , 0 , ... } respectively ; Find all the changes required ; Return the required answer ; Driver code
def min_changes ( a , n ) : NEW_LINE INDENT ans_a = 0 ; NEW_LINE ans_b = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT ans_a += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans_b += 1 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT ans_b += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans_a += 1 ; NEW_LINE DEDENT DEDENT DEDENT return min ( ans_a , ans_b ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 0 , 0 , 1 , 0 , 0 , 1 , 0 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( min_changes ( a , n ) ) ; NEW_LINE DEDENT
Sum of all the numbers present at given level in Modified Pascal ’ s triangle | Function to calculate sum ; Driver Code
def ans ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( "1" , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( "0" , end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; NEW_LINE ans ( n ) ; NEW_LINE DEDENT
Find if there exists multiple ways to draw line through ( x , y ) to cut rectangle in equal halfs | Function that returns true if multiple lines are possible passing through ( x , y ) that divide the given rectangle into two equal parts ; If the point ( x , y ) is the centre of the rectangle ; Driver code
def isPossible ( w , h , x , y ) : NEW_LINE INDENT if ( x * 2 == w and y * 2 == h ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT w = 1 NEW_LINE h = 2 NEW_LINE x = 1 NEW_LINE y = 2 NEW_LINE if ( isPossible ( w , h , x , y ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Minimize the number by changing at most K digits | Function to return the minimized number ; Total digits in the number ; If the string is empty or there are no operations to perform ; "0" is a valid number ; If the first digit is not already 1 then update it to 1 and decrement k ; While there are operations left and the number can still be updated ; If the current digit is not already 0 then update it to 0 and decrement k ; Return the minimised number ; Driver code
def minNum ( num , k ) : NEW_LINE INDENT len_ = len ( num ) NEW_LINE if len_ == 0 or k == 0 : NEW_LINE INDENT return num NEW_LINE DEDENT if len_ == 1 : NEW_LINE INDENT return "0" NEW_LINE DEDENT if num [ 0 ] != '1' : NEW_LINE INDENT num = '1' + num [ 1 : ] NEW_LINE k -= 1 NEW_LINE DEDENT i = 1 NEW_LINE while k > 0 and i < len_ : NEW_LINE INDENT if num [ i ] != '0' : NEW_LINE INDENT num = num [ : i ] + '0' + num [ i + 1 : ] NEW_LINE k -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return num NEW_LINE DEDENT num = "91945" NEW_LINE k = 3 NEW_LINE print ( minNum ( num , k ) ) NEW_LINE
Form N by adding 1 or 2 in minimum number of operations X where X is divisible by M | Function to calculate the minimum number of steps required total steps taken is divisible by m and only 1 or 2 steps can be taken at a time ; If m > n ans is - 1 ; else discussed above approach ; Driver code
def minsteps ( n , m ) : NEW_LINE INDENT if ( m > n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( n + 1 ) // 2 + m - 1 ) // m * m ; NEW_LINE DEDENT DEDENT n = 17 NEW_LINE m = 4 NEW_LINE ans = minsteps ( n , m ) NEW_LINE print ( ans ) NEW_LINE
Compare numbers represented by Linked Lists | Structure for a linked list node ; A helper function to remove zeros from the start of the linked list ; A helper function to find the length of linked list ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; Allocate node ; Set the data ; Link the old list after the new node ; Set the head to point to the new node ; Function to compare the numbers represented as linked lists ; Remover leading zeroes from the linked lists ; Since the number represented by a has a greater length , it will be greater ; If the lengths of two numbers are equal we have to check their magnitudes ; If we reach here , then a and b are not None and their data is same , so move to next nodes in both lists ; If linked lists are identical , then we need to return zero ; Driver code ; The constructed linked lists are : a : 5.6 . 7 b : 2.3 . 3
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def removeLeadingZeros ( a ) : NEW_LINE INDENT if ( a != None and a . data == 0 ) : NEW_LINE INDENT return removeLeadingZeros ( a . next ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return a ; NEW_LINE DEDENT DEDENT def getSize ( a ) : NEW_LINE INDENT sz = 0 ; NEW_LINE while ( a != None ) : NEW_LINE INDENT a = a . next ; NEW_LINE sz += 1 NEW_LINE DEDENT return sz ; NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data ; NEW_LINE new_node . next = ( head_ref ) ; NEW_LINE ( head_ref ) = new_node ; NEW_LINE return head_ref NEW_LINE DEDENT def compare ( a , b ) : NEW_LINE INDENT a = removeLeadingZeros ( a ) ; NEW_LINE b = removeLeadingZeros ( b ) ; NEW_LINE lenA = getSize ( a ) ; NEW_LINE lenB = getSize ( b ) ; NEW_LINE if ( lenA > lenB ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( lenB > lenA ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT while ( a != None and b != None ) : NEW_LINE INDENT if ( a . data > b . data ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( a . data < b . data ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT a = a . next ; NEW_LINE b = b . next ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = None ; NEW_LINE a = push ( a , 7 ) ; NEW_LINE a = push ( a , 6 ) ; NEW_LINE a = push ( a , 5 ) ; NEW_LINE b = None ; NEW_LINE b = push ( b , 3 ) ; NEW_LINE b = push ( b , 3 ) ; NEW_LINE b = push ( b , 2 ) ; NEW_LINE print ( compare ( a , b ) ) NEW_LINE DEDENT
Sum of the updated array after performing the given operation | Utility function to return the sum of the array ; Function to return the sum of the modified array ; Find the sum of the subarray arr [ i + 1. . . n - 1 ] ; Subtract the subarray sum ; Return the sum of the modified array ; Driver code
def sumArr ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT def sumModArr ( arr , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT subSum = 0 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT subSum += arr [ j ] NEW_LINE DEDENT arr [ i ] -= subSum NEW_LINE DEDENT return sumArr ( arr , n ) NEW_LINE DEDENT arr = [ 40 , 25 , 12 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( sumModArr ( arr , n ) ) NEW_LINE
Find the minimum possible health of the winning player | Python3 implementation of the approach ; Function to return the minimum possible health of the last player ; Find the GCD of the array elements ; Driver code
from math import gcd NEW_LINE def minHealth ( health , n ) : NEW_LINE INDENT __gcd = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT __gcd = gcd ( __gcd , health [ i ] ) ; NEW_LINE DEDENT return __gcd ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT health = [ 5 , 6 , 1 , 2 , 3 , 4 ] ; NEW_LINE n = len ( health ) ; NEW_LINE print ( minHealth ( health , n ) ) ; NEW_LINE DEDENT
Construct an array from its pair | Python3 implementation of the approach ; Utility function to print the array ; Function to generate the original array from the pair - product array ; First element of the resulting array ; Find all the other elements ; Print the elements of the generated array ; Driver code
from math import sqrt NEW_LINE def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT def constructArr ( pair , n ) : NEW_LINE INDENT size = int ( ( 1 + sqrt ( 1 + 8 * n ) ) // 2 ) ; NEW_LINE arr = [ 0 ] * ( size ) ; NEW_LINE arr [ 0 ] = int ( sqrt ( ( pair [ 0 ] * pair [ 1 ] ) / pair [ size - 1 ] ) ) ; NEW_LINE for i in range ( 1 , size ) : NEW_LINE INDENT arr [ i ] = pair [ i - 1 ] // arr [ 0 ] ; NEW_LINE DEDENT printArr ( arr , size ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT pair = [ 48 , 18 , 24 , 24 , 32 , 12 ] ; NEW_LINE n = len ( pair ) ; NEW_LINE constructArr ( pair , n ) ; NEW_LINE DEDENT
Count of odd and even sum pairs in an array | Function to find the count of pairs with odd sum and the count of pairs with even sum ; To store the count of even and odd number from the array ; If the current element is even ; If it is odd ; To store the count of pairs with even sum ; All the even elements will make pairs with each other and the sum of the pair will be even ; All the odd elements will make pairs with each other and the sum of the pair will be even ; To store the count of pairs with odd sum ; All the even elements will make pairs with all the odd element and the sum of the pair will be odd ; Driver code
def findPairs ( arr , n ) : NEW_LINE INDENT cntEven = 0 ; cntOdd = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT cntEven += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT cntOdd += 1 ; NEW_LINE DEDENT DEDENT evenPairs = 0 ; NEW_LINE evenPairs += ( ( cntEven * ( cntEven - 1 ) ) // 2 ) ; NEW_LINE evenPairs += ( ( cntOdd * ( cntOdd - 1 ) ) // 2 ) ; NEW_LINE oddPairs = 0 ; NEW_LINE oddPairs += ( cntEven * cntOdd ) ; NEW_LINE print ( " Odd ▁ pairs ▁ = ▁ " , oddPairs ) ; NEW_LINE print ( " Even ▁ pairs ▁ = ▁ " , evenPairs ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findPairs ( arr , n ) ; NEW_LINE DEDENT
Number of ways to distribute N Paper Set among M students | Python3 implementation of the approach ; Function to return n ! % 1000000007 ; To store the factorial ; Find the factorial ; Function to return the count of possible ways ; Driver code
MOD = 1000000007 ; NEW_LINE def factMod ( n ) : NEW_LINE INDENT fact = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT fact *= ( i % MOD ) ; NEW_LINE fact %= MOD ; NEW_LINE DEDENT return fact ; NEW_LINE DEDENT def countWays ( n , m ) : NEW_LINE INDENT return factMod ( m ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; m = 2 ; NEW_LINE print ( countWays ( n , m ) ) ; NEW_LINE DEDENT
Program for nth Fuss – Catalan Number | Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth FussCatalan number in O ( n ) time ; Calculate value of 3 nCn ; return 3 nCn / ( 2 n + 1 ) ; Driver code
def binomialCoeff ( n , k ) : NEW_LINE INDENT 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 def Fuss_catalan ( n ) : NEW_LINE INDENT c = binomialCoeff ( 3 * n , n ) ; NEW_LINE return c // ( 2 * n + 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT print ( Fuss_catalan ( i ) , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT
Check if a number is Euler Pseudoprime | Python3 program for nth FussCatalan Number ; Function that returns true if n is composite ; Check if there is any divisor of n . we only need check divisor till sqrt ( n ) because if there is divisor which is greater than sqrt ( n ) then there must be a divisor which is less than sqrt ( n ) ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is greater than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function that returns true if N is Euler Pseudoprime to the base A ; Invalid base ; N is not a composite odd number ; If A and N are not coprime ; All the conditions for Euler Pseudoprime are satisfied ; Driver code
from math import gcd , sqrt NEW_LINE def isComposite ( n ) : NEW_LINE INDENT for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT def Power ( x , y , p ) : NEW_LINE INDENT res = 1 ; NEW_LINE x = x % p ; NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p ; NEW_LINE DEDENT x = ( x * x ) % p ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def isEulerPseudoprime ( N , A ) : NEW_LINE INDENT if ( A <= 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( N % 2 == 0 or not isComposite ( N ) ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( gcd ( A , N ) != 1 ) : NEW_LINE INDENT return false ; NEW_LINE DEDENT mod = Power ( A , ( N - 1 ) // 2 , N ) ; NEW_LINE if ( mod != 1 and mod != N - 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 121 ; A = 3 ; NEW_LINE if ( isEulerPseudoprime ( N , A ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Minimum difference between any two primes from the given range | Python3 implementation of the approach ; Function for Sieve of Eratosthenes ; Function to return the minimum difference between any two prime numbers from the given range [ L , R ] ; Find the first prime from the range ; Find the second prime from the range ; If the number of primes in the given range is < 2 ; To store the minimum difference between two consecutive primes from the range ; Range left to check for primes ; For every integer in the range ; If the current integer is prime ; If the difference between i and snd is minimum so far ; Driver code ; Generate primes
from math import sqrt NEW_LINE sz = int ( 1e5 ) ; NEW_LINE isPrime = [ True ] * ( sz + 1 ) ; NEW_LINE def sieve ( ) : NEW_LINE INDENT isPrime [ 0 ] = isPrime [ 1 ] = False ; NEW_LINE for i in range ( 2 , int ( sqrt ( sz ) ) + 1 ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , sz , i ) : NEW_LINE INDENT isPrime [ j ] = False ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def minDifference ( L , R ) : NEW_LINE INDENT fst = 0 ; NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT fst = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT snd = 0 ; NEW_LINE for i in range ( fst + 1 , R + 1 ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT snd = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( snd == 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT diff = snd - fst ; NEW_LINE left = snd + 1 ; NEW_LINE right = R ; NEW_LINE for i in range ( left , right + 1 ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT if ( i - snd <= diff ) : NEW_LINE INDENT fst = snd ; NEW_LINE snd = i ; NEW_LINE diff = snd - fst ; NEW_LINE DEDENT DEDENT DEDENT return diff ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT sieve ( ) ; NEW_LINE L = 21 ; R = 50 ; NEW_LINE print ( minDifference ( L , R ) ) ; NEW_LINE DEDENT
Number of non | Function to return the required count ; To store the final result ; Two pointer loop ; Initialising j ; Looping till the subarray increases ; Update ret ; Update i ; Return ret ; Driver code
def findCnt ( arr , n , k ) : NEW_LINE INDENT ret = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT j = i + 1 ; NEW_LINE while ( j < n and arr [ j ] >= arr [ j - 1 ] ) : NEW_LINE INDENT j += 1 ; NEW_LINE DEDENT x = max ( 0 , j - i - k ) ; NEW_LINE ret += ( x * ( x + 1 ) ) / 2 ; NEW_LINE i = j ; NEW_LINE DEDENT return ret ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 4 , 3 , 2 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE print ( findCnt ( arr , n , k ) ) ; NEW_LINE DEDENT
Count of elements which are second smallest among three consecutive elements | Function to return the count of elements P [ i ] such that P [ i ] is the second smallest among P [ i 1 ] , P [ i ] and P [ i + 1 ] ; To store the required answer ; Traverse from the second element to the second last element ; Return the required answer ; Driver code
def countElements ( p , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( p [ i - 1 ] > p [ i ] and p [ i ] > p [ i + 1 ] ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT elif ( p [ i - 1 ] < p [ i ] and p [ i ] < p [ i + 1 ] ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p = [ 2 , 5 , 1 , 3 , 4 ] ; NEW_LINE n = len ( p ) ; NEW_LINE print ( countElements ( p , n ) ) ; NEW_LINE DEDENT
Count integers in the range [ A , B ] that are not divisible by C and D | Python3 implementation of the approach ; Function to return the count of integers from the range [ a , b ] that are not divisible by c and d ; Numbers which are divisible by c ; Numbers which are divisible by d ; Find lowest common factor of c and d ; Numbers which are divisible by both c and d ; Return the required answer ; Driver code
from math import gcd NEW_LINE def countNums ( a , b , c , d ) : NEW_LINE INDENT x = b // c - ( a - 1 ) // c ; NEW_LINE y = b // d - ( a - 1 ) // d ; NEW_LINE k = ( c * d ) // gcd ( c , d ) ; NEW_LINE z = b // k - ( a - 1 ) // k ; NEW_LINE return ( b - a + 1 - x - y + z ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 10 ; b = 50 ; c = 4 ; d = 6 ; NEW_LINE print ( countNums ( a , b , c , d ) ) ; NEW_LINE DEDENT