text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Average of Cubes of first N natural numbers | Function to find average of cubes ; Storing sum of cubes of numbers in sum ; Calculate sum of cubes ; Return average ; Driver Code ; Given Number ; Function Call | def findAverageOfCube ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum += i * i * i NEW_LINE DEDENT return round ( sum / n , 6 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE print ( findAverageOfCube ( n ) ) NEW_LINE DEDENT |
Smallest and Largest N | Python3 program for the above approach ; Function to find n digit largest number starting and ending with n ; Corner Case when n = 1 ; Result will store the n - 2 * length ( n ) digit largest number ; Find the number of digits in number n ; Append 9 ; To make it largest n digit number starting and ending with n , we just need to append n at start and end ; Return the largest number ; Function to find n digit smallest number starting and ending with n ; Corner Case when n = 1 ; Result will store the n - 2 * length ( n ) digit smallest number ; Find the number of digits in number n ; To make it smallest n digit number starting and ending with n , we just need to append n at start and end ; Return the smallest number ; Driver Code ; Given Number ; Function Call | import math NEW_LINE def findNumberL ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return "1" NEW_LINE DEDENT result = " " NEW_LINE length = math . floor ( math . log10 ( n ) + 1 ) NEW_LINE for i in range ( 1 , n - ( 2 * length ) + 1 ) : NEW_LINE INDENT result += '9' NEW_LINE DEDENT result = ( str ( n ) + result + str ( n ) ) NEW_LINE return result NEW_LINE DEDENT def findNumberS ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return "1" NEW_LINE DEDENT result = " " NEW_LINE length = math . floor ( math . log10 ( n ) + 1 ) NEW_LINE for i in range ( 1 , n - ( 2 * length ) + 1 ) : NEW_LINE INDENT result += '0' NEW_LINE DEDENT result = ( str ( n ) + result + str ( n ) ) NEW_LINE return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE print ( " Smallest β Number β = β " + findNumberS ( N ) ) NEW_LINE print ( " Largest β Number β = β " + findNumberL ( N ) ) NEW_LINE DEDENT |
Maximum number of 0 s that can be flipped such that Array has no adjacent 1 s | Maximum number of 0 s that can be replaced by 1 ; Check for three consecutive 0 s ; Flip the bit ; Increase the count ; Driver code | def canReplace ( arr , n ) : NEW_LINE INDENT i = 0 NEW_LINE count = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] == 0 and ( i == 0 or arr [ i - 1 ] == 0 ) and ( i == n - 1 or arr [ i + 1 ] == 0 ) ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE count += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 0 , 0 , 1 ] NEW_LINE print ( canReplace ( arr , 5 ) ) NEW_LINE DEDENT |
Sum of first N Star Numbers | Function to find the sum of the first N star number ; Variable to store the sum ; Driver code | def sum_star_num ( n ) : NEW_LINE INDENT summ = 2 * n * ( n + 1 ) * ( n - 1 ) + n NEW_LINE return summ NEW_LINE DEDENT n = 3 NEW_LINE print ( sum_star_num ( n ) ) NEW_LINE |
Count distinct median possible for an Array using given ranges of elements | Function to count the number of distinct medians of an array where each array elements are given by a range ; Loop to store the starting and end range in the array ; Condition to check if the length of the array is odd ; Driver Code ; Function Call | def solve ( n , vec ) : NEW_LINE INDENT a = [ ] NEW_LINE b = [ ] NEW_LINE for pr in vec : NEW_LINE INDENT a . append ( pr [ 0 ] ) NEW_LINE b . append ( pr [ 1 ] ) NEW_LINE DEDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE if ( ( n & 1 ) ) : NEW_LINE INDENT left = a [ n // 2 ] NEW_LINE right = b [ n // 2 ] NEW_LINE ans = right - left + 1 NEW_LINE DEDENT else : NEW_LINE INDENT left = ( a [ n // 2 ] + a [ n // 2 - 1 ] ) NEW_LINE right = ( b [ n // 2 ] + b [ n // 2 - 1 ] ) NEW_LINE ans = right - left + 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE vec = [ ( 100 , 100 ) , ( 10 , 10000 ) , ( 1 , 1000000000 ) ] NEW_LINE solve ( N , vec ) NEW_LINE DEDENT |
Count of pairs from Array with sum equal to twice their bitwise AND | Python3 implementation to find the pairs with equal sum and twice the bitwise AND of the pairs ; Map to store the occurrence of elements of array ; Function to find the pairs with equal sum and twice the bitwise AND of the pairs ; Loop to find the frequency of elements of array ; Function to find the count such pairs in the array ; If an element occurs more than once then the answer will by incremented by nC2 times ; Driver Code ; Function Call | from collections import defaultdict NEW_LINE mp = defaultdict ( int ) NEW_LINE def find_pairs ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in mp . values ( ) : NEW_LINE INDENT count = i NEW_LINE if ( count > 1 ) : NEW_LINE INDENT ans += ( ( count * ( count - 1 ) ) // 2 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 3 , 4 , 5 , 5 , 7 , 8 ] NEW_LINE arr_size = len ( arr ) NEW_LINE print ( find_pairs ( arr , arr_size ) ) NEW_LINE DEDENT |
360 | Function to find the nth 360 - gon Number ; Driver Code | def gonNum360 ( n ) : NEW_LINE INDENT return ( 358 * n * n - 356 * n ) // 2 ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( gonNum360 ( n ) ) ; NEW_LINE |
120 | Function to find the nth 120 - gon Number ; Driver Code | def gonNum120 ( n ) : NEW_LINE INDENT return ( 118 * n * n - 116 * n ) // 2 ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( gonNum120 ( n ) ) ; NEW_LINE |
Tetracontaoctagonal Number | Function to find the nth Tetracontaoctagonal Number ; Driver Code | def TetracontaoctagonalNum ( n ) : NEW_LINE INDENT return ( 46 * n * n - 44 * n ) / 2 ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( TetracontaoctagonalNum ( n ) ) ; NEW_LINE |
257 | Function to find the nth 257 - gon Number ; Driver Code | def gonNum257 ( n ) : NEW_LINE INDENT return ( 255 * n * n - 253 * n ) // 2 ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( gonNum257 ( n ) ) ; NEW_LINE |
Tetracontadigonal Number | Function to find the nth tetracontadigonal number ; Driver Code | def TetracontadigonalNum ( n ) : NEW_LINE INDENT return int ( ( 40 * n * n - 38 * n ) / 2 ) NEW_LINE DEDENT n = 3 NEW_LINE print ( TetracontadigonalNum ( n ) ) NEW_LINE |
Index of smallest triangular number with N digits | Python3 implementation of the above approach ; Function to return index of smallest triangular no n digits ; Driver Code | import math NEW_LINE def findIndex ( n ) : NEW_LINE INDENT x = math . sqrt ( 2 * math . pow ( 10 , ( n - 1 ) ) ) ; NEW_LINE return round ( x ) ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( findIndex ( n ) ) ; NEW_LINE |
Program to find the LCM of two prime numbers | Function to return the LCM of two prime numbers ; If the two numbers are equal then return any one of a and b ; Else return product of the numbers ; Driver code ; Given two numbers ; Function Call | def findLCMPrime ( a , b ) : NEW_LINE INDENT if ( a == b ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT return a * b ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 3 ; b = 5 ; NEW_LINE print ( findLCMPrime ( a , b ) ) ; NEW_LINE DEDENT |
Smallest multiple of N with exactly N digits in its Binary number representation | Python3 program to find smallest multiple of n with exactly N digits in Binary number System . ; Function to find smallest multiple of n with exactly n digits in Binary number representation . ; Driver code | from math import ceil NEW_LINE def smallestNumber ( N ) : NEW_LINE INDENT print ( N * ceil ( pow ( 2 , ( N - 1 ) ) / N ) ) NEW_LINE DEDENT N = 3 NEW_LINE smallestNumber ( N ) NEW_LINE |
Find the largest N digit multiple of N | Python3 program to find largest multiple of N containing N digits ; Function to find the largest N digit multiple of N ; Driver code | from math import floor NEW_LINE def smallestNumber ( N ) : NEW_LINE INDENT print ( N * floor ( ( pow ( 10 , N ) - 1 ) / N ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE smallestNumber ( N ) NEW_LINE DEDENT |
Icosikaiheptagonal Number | Function to find the nth icosikaiheptagonal Number ; Driver code | def icosikaiheptagonalNum ( n ) : NEW_LINE INDENT return ( 25 * n * n - 23 * n ) // 2 ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( "3rd β icosikaiheptagonal β Number β is β " , icosikaiheptagonalNum ( n ) ) ; NEW_LINE |
Program to check if N is a triacontagonal number | Python3 program to check whether a number is an triacontagonal number or not ; Function to check whether a number is an triacontagonal number or not ; Condition to check whether a number is an triacontagonal number or not ; Given number ; Function call | import math ; NEW_LINE def istriacontagonal ( N ) : NEW_LINE INDENT n = ( 26 + math . sqrt ( 224 * N + 676 ) ) // 56 ; NEW_LINE return ( n - int ( n ) ) == 0 ; NEW_LINE DEDENT i = 30 ; NEW_LINE if ( istriacontagonal ( i ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Check whether one root of the Quadratic Equation is twice of other or not | Function to find the required answer ; Driver code | def checkSolution ( a , b , c ) : NEW_LINE INDENT if ( 2 * b * b == 9 * a * c ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT a = 1 ; b = 3 ; c = 2 ; NEW_LINE checkSolution ( a , b , c ) ; NEW_LINE |
Parity of the given mathematical expression using given N numbers | Python3 program to determine the parity of the given mathematical expression ; Iterating through the given integers ; If any odd number is present , then S is even parity ; Else , S is odd parity ; Driver code | def getParity ( n , A ) : NEW_LINE INDENT for x in A : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT print ( " Even " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " Odd " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE A = [ 2 , 3 , 1 ] NEW_LINE getParity ( N , A ) NEW_LINE DEDENT |
Count of digits after concatenation of first N positive integers | Python3 program to find the number of digits after concatenating the first N positive integers ; Function to find the number of digits after concatenating the first N positive integers ; Driver code | from math import log10 , floor NEW_LINE def numberOfDigits ( N ) : NEW_LINE INDENT nod = floor ( log10 ( N ) + 1 ) ; NEW_LINE toDecrease = ( pow ( 10 , nod ) - 1 ) // 9 NEW_LINE print ( ( N + 1 ) * nod - toDecrease ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 13 NEW_LINE numberOfDigits ( N ) NEW_LINE DEDENT |
Length of maximum product subarray | function that returns the maximum length subarray having non zero product ; zeroindex list to store indexex of zero ; if zeroindex list is empty then Maxlength is as size of array ; if zeroindex list is not empty ; first zero is on index 2 that means two numbers positive , before index 2 so as their product is positive to ; checking for other indexex ; if the difference is greater than maxlen then maxlen is updated ; to check the length of remaining array after last zeroindex ; Driver Code | def Maxlength ( arr , N ) : NEW_LINE INDENT zeroindex = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT zeroindex . append ( i ) NEW_LINE DEDENT DEDENT if ( len ( zeroindex ) == 0 ) : NEW_LINE INDENT maxlen = N NEW_LINE DEDENT else : NEW_LINE INDENT maxlen = zeroindex [ 0 ] NEW_LINE for i in range ( 0 , len ( zeroindex ) - 1 ) : NEW_LINE INDENT if ( zeroindex [ i + 1 ] \ - zeroindex [ i ] - 1 \ > maxlen ) : NEW_LINE INDENT maxlen = zeroindex [ i + 1 ] - zeroindex [ i ] - 1 NEW_LINE DEDENT DEDENT if ( N - zeroindex [ len ( zeroindex ) - 1 ] \ - 1 > maxlen ) : NEW_LINE INDENT maxlen = N - zeroindex [ len ( zeroindex ) - 1 ] - 1 NEW_LINE DEDENT DEDENT print ( maxlen ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 9 NEW_LINE arr = [ 7 , 1 , 0 , 1 , 2 , 0 , 9 , 2 , 1 ] NEW_LINE Maxlength ( arr , N ) NEW_LINE DEDENT |
Check if sum of exactly K elements of the Array can be odd or not | Function returns true if it is possible to have odd sum ; Counting number of odd and even elements ; Driver code | def isPossible ( arr , N , K ) : NEW_LINE INDENT oddCount = 0 NEW_LINE evenCount = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT evenCount += 1 NEW_LINE DEDENT else : NEW_LINE INDENT oddCount += 1 NEW_LINE DEDENT DEDENT if ( evenCount == N or ( oddCount == N and K % 2 == 0 ) or ( K == N and oddCount % 2 == 0 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 8 ] NEW_LINE K = 5 NEW_LINE N = len ( arr ) NEW_LINE if ( isPossible ( arr , N , K ) ) : NEW_LINE INDENT print ( " Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT DEDENT |
Find the last two digits of Factorial of a given Number | Function to print the last two digits of N ! ; For N >= 10 , N ! % 100 will always be 0 ; Calculating N ! % 100 ; Driver code | def lastTwoDigits ( N ) : NEW_LINE INDENT if ( N >= 10 ) : NEW_LINE INDENT print ( "00" , end = " " ) NEW_LINE return NEW_LINE DEDENT fac = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT fac = ( fac * i ) % 100 NEW_LINE DEDENT print ( fac ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE lastTwoDigits ( N ) NEW_LINE DEDENT |
Product of N terms of a given Geometric series | Function to calculate product of geometric series ; Return the final product with the above formula ; Given first term and common ratio ; Number of terms ; Function Call | def productOfGP ( a , r , n ) : NEW_LINE INDENT return pow ( a , n ) * pow ( r , n * ( n - 1 ) // 2 ) ; NEW_LINE DEDENT a = 1 ; r = 2 ; NEW_LINE N = 4 ; NEW_LINE print ( productOfGP ( a , r , N ) ) ; NEW_LINE |
Product of N terms of a given Geometric series | Python3 program for the above approach ; Function to calculate product of N terms of geometric series ; Find the product of first and the last term ; Return the sqrt of the above expression to find the product ; Given first term and common ratio ; Number of terms ; Function Call | import math NEW_LINE def productOfGP ( a , r , n ) : NEW_LINE INDENT an = a * pow ( r , n - 1 ) ; NEW_LINE return ( math . sqrt ( pow ( a * an , n ) ) ) NEW_LINE DEDENT a = 1 NEW_LINE r = 2 ; NEW_LINE N = 4 ; NEW_LINE print ( productOfGP ( a , r , N ) ) NEW_LINE |
Find two numbers such that difference of their squares equal to N | Python3 Program to find two numbers with difference of their squares equal to N ; Function to check and print the required two positive integers ; Iterate till sqrt ( n ) to find factors of N ; Check if x is one of the factors of N ; Store the factor ; Compute the other factor ; Check if the two factors are of the same parity ; Compute a and b ; If no pair exists ; Driver Code | from math import sqrt NEW_LINE def solve ( n ) : NEW_LINE INDENT for x in range ( 1 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % x == 0 ) : NEW_LINE INDENT small = x ; NEW_LINE big = n // x ; NEW_LINE if ( small % 2 == big % 2 ) : NEW_LINE INDENT a = ( small + big ) // 2 ; NEW_LINE b = ( big - small ) // 2 ; NEW_LINE print ( a , b ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT DEDENT print ( - 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 7 ; NEW_LINE solve ( n ) ; NEW_LINE DEDENT |
Probability that an arbitrary positive divisor of 10 ^ X is an integral multiple of 10 ^ Y | Python3 program to find the probability of an arbitrary positive divisor of Xth power of 10 to be a multiple of Yth power of 10 ; Function to calculate and print the required probability ; Count of potential divisors of X - th power of 10 which are also multiples of Y - th power of 10 ; Count of divisors of X - th power of 10 ; Calculate GCD ; Print the reduced fraction probability ; Driver Code | from math import * NEW_LINE def prob ( x , y ) : NEW_LINE INDENT num = abs ( x - y + 1 ) * abs ( x - y + 1 ) NEW_LINE den = ( x + 1 ) * ( x + 1 ) NEW_LINE gcd1 = gcd ( num , den ) NEW_LINE print ( num // gcd1 , end = " " ) NEW_LINE print ( " / " , end = " " ) NEW_LINE print ( den // gcd1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 2 NEW_LINE Y = 1 NEW_LINE prob ( X , Y ) NEW_LINE DEDENT |
Program to check if N is a Chiliagon Number | Python3 for the above approach ; Function to check that if N is Chiliagon Number or not ; Condition to check if N is a Chiliagon Number ; Given Number ; Function call | import math ; NEW_LINE def is_Chiliagon ( N ) : NEW_LINE INDENT n = ( 996 + math . sqrt ( 7984 * N + 992016 ) ) // 1996 ; NEW_LINE return ( n - int ( n ) ) == 0 ; NEW_LINE DEDENT N = 1000 ; NEW_LINE if ( is_Chiliagon ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Count of common subarrays in two different permutations of 1 to N | Python3 implementation of above approach ; Initialising Map for Index Mapping ; Mapping elements of A ; Modify elements of B according to Map ; Changing B [ i ] as the index of B [ i ] in A ; Count of common subarrays ; Traversing array B ; While consecutive elements are found , we increment K ; Add number of subarrays with length K to total count ; Driver code | def commonSubarrays ( A , B , N ) : NEW_LINE INDENT Map = [ 0 for i in range ( N + 1 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT Map [ A [ i ] ] = i NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT B [ i ] = Map [ B [ i ] ] NEW_LINE DEDENT count = 0 NEW_LINE i = 0 NEW_LINE while i < N : NEW_LINE INDENT K = 1 NEW_LINE i += 1 NEW_LINE while i < N and B [ i ] == B [ i - 1 ] + 1 : NEW_LINE INDENT i += 1 NEW_LINE K += 1 NEW_LINE DEDENT count = count + ( ( K ) * ( K + 1 ) ) // 2 NEW_LINE DEDENT return count NEW_LINE DEDENT N = 3 NEW_LINE A = [ 1 , 2 , 3 ] NEW_LINE B = [ 2 , 3 , 1 ] NEW_LINE print ( commonSubarrays ( A , B , N ) ) NEW_LINE N = 5 NEW_LINE A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE B = [ 2 , 3 , 1 , 4 , 5 ] NEW_LINE print ( commonSubarrays ( A , B , N ) ) NEW_LINE |
Represent N as sum of K even or K odd numbers with repetitions allowed | Function to find the array with all the even / odd elements ; First let 's check kth is odd or even ; if last element is also an odd number then we can choose odd elements for our answer ; Add 1 in the array ( k - 1 ) times ; Add last odd element ; If array of even elements would be the answer then k - 1 elements would be 2 ; if last element is also an even number then we can choose even elements for our answer ; Add 2 in the array ( k - 1 ) times ; Add last even element ; Printing the array ; Driver Code | def getArrayOfSizeK ( n , k ) : NEW_LINE INDENT ans = [ ] NEW_LINE odd = n - ( ( k - 1 ) * 1 ) NEW_LINE if ( odd > 0 and odd % 2 != 0 ) : NEW_LINE INDENT for i in range ( k - 1 ) : NEW_LINE INDENT ans . append ( 1 ) NEW_LINE DEDENT ans . append ( odd ) NEW_LINE DEDENT even = n - ( ( k - 1 ) * 2 ) NEW_LINE if ( even > 0 and even % 2 == 0 and len ( ans ) == 0 ) : NEW_LINE INDENT for i in range ( k - 1 ) : NEW_LINE INDENT ans . append ( 2 ) NEW_LINE DEDENT ans . append ( even ) NEW_LINE DEDENT if ( len ( ans ) > 0 ) : NEW_LINE INDENT for i in range ( k ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 10 , 3 NEW_LINE getArrayOfSizeK ( n , k ) NEW_LINE DEDENT |
Check whether a given number N is a Nude Number or not | Check if all digits of num divide num ; Array to store all digits of the given number ; If any of the condition is true for any digit then N is not a nude number ; Driver code | def checkDivisbility ( num ) : NEW_LINE INDENT digit = 0 NEW_LINE N = num NEW_LINE while ( num != 0 ) : NEW_LINE INDENT digit = num % 10 NEW_LINE num = num // 10 NEW_LINE if ( digit == 0 or N % digit != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 128 NEW_LINE result = checkDivisbility ( N ) NEW_LINE if ( result ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Hensel 's Lemma | Function to find the modular inverse of a modulo m ; Apply the Euclidean algorithm , to find the modular inverse ; Function to find the derivative of f ( x ) and f '(x) = 3 * (x ^ 2) ; Function to find the image of x in f ( x ) = x ^ 3 - k . ; Function to find the next power of the number ; Next power of prime for which solution is to be found ; Using Hensel 's recursion to find the solution(next_a) for next power of prime ; If next_a < 0 return equivalent positive remainder modulo p ; Return the next power of a ; Function to find the solution of the required exponent of prime ; The lemma does not work for derivative of f ( x ) at a1 ; Looping from 1 to power of prime whose solution is to be found ; Final answer after evaluating all the exponents up till the required exponent ; Driver Code ; Function Call | def inv ( a , m ) : NEW_LINE INDENT m0 = m NEW_LINE x0 = 0 NEW_LINE x1 = 1 NEW_LINE if ( m == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( a > 1 ) : NEW_LINE INDENT q = a // m NEW_LINE t = m NEW_LINE m = a % m NEW_LINE a = t NEW_LINE t = x0 NEW_LINE x0 = x1 - q * x0 NEW_LINE x1 = t NEW_LINE DEDENT if ( x1 < 0 ) : NEW_LINE INDENT x1 += m0 NEW_LINE DEDENT return x1 NEW_LINE DEDENT def derivative ( x ) : NEW_LINE INDENT return 3 * x * x NEW_LINE DEDENT def Image ( x , k ) : NEW_LINE INDENT return x * x * x - k NEW_LINE DEDENT def next_power ( a_t , t , a1 , prime , k ) : NEW_LINE INDENT power_p = int ( pow ( prime , t + 1 ) ) NEW_LINE next_a = ( a_t - Image ( a_t , k ) * inv ( derivative ( a1 ) , prime ) ) % power_p NEW_LINE if ( next_a < 0 ) : NEW_LINE INDENT next_a += power_p NEW_LINE return next_a NEW_LINE DEDENT return next_a NEW_LINE DEDENT def powerOfPrime ( prime , power , k , a1 ) : NEW_LINE INDENT if ( derivative ( a1 ) != 0 ) : NEW_LINE INDENT a_t = a1 NEW_LINE for p in range ( 1 , power ) : NEW_LINE INDENT a_t = next_power ( a_t , p , a1 , prime , k ) NEW_LINE DEDENT return a_t NEW_LINE DEDENT return - 1 NEW_LINE DEDENT prime = 7 NEW_LINE a1 = 3 NEW_LINE power = 2 NEW_LINE k = 3 NEW_LINE print ( powerOfPrime ( prime , power , k , a1 ) ) NEW_LINE |
Count of numbers with all digits same in a given range | Python3 program to count the total numbers in the range L and R which have all the digit same ; Function that count the total numbersProgram between L and R which have all the digit same ; length of R ; tmp has all digits as 1 ; For each multiple of tmp in range 1 to 9 , check if it present in range [ L , R ] ; Increment the required count ; Driver Code | import math NEW_LINE def count_same_digit ( L , R ) : NEW_LINE INDENT tmp = 0 ; ans = 0 ; NEW_LINE n = int ( math . log10 ( R ) + 1 ) ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT tmp = tmp * 10 + 1 ; NEW_LINE for j in range ( 1 , 9 ) : NEW_LINE INDENT if ( L <= ( tmp * j ) and ( tmp * j ) <= R ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT L = 12 ; R = 68 ; NEW_LINE print ( count_same_digit ( L , R ) ) NEW_LINE |
Minimum LCM of all pairs in a given array | Python3 program to find the pair having minimum LCM ; function that return pair having minimum LCM ; find max element in the array as the gcd of two elements from the array can 't greater than max element. ; created a 2D array to store minimum two multiple of any particular i . ; we already found two smallest multiple ; iterating over all gcd ; iterating over its multiple ; if we already found the two smallest multiple of i ; choosing smallest two multiple ; calculating lcm ; return final answer ; Driver code | import sys NEW_LINE def minLCM ( arr , n ) : NEW_LINE INDENT mx = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mx = max ( mx , arr [ i ] ) NEW_LINE DEDENT mul = [ [ ] for i in range ( mx + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( len ( mul [ arr [ i ] ] ) > 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT mul [ arr [ i ] ] . append ( arr [ i ] ) NEW_LINE DEDENT for i in range ( 1 , mx + 1 ) : NEW_LINE INDENT for j in range ( i + i , mx + 1 , i ) : NEW_LINE INDENT if ( len ( mul [ i ] ) > 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT for k in mul [ j ] : NEW_LINE INDENT if ( len ( mul [ i ] ) > 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT mul [ i ] . append ( k ) NEW_LINE DEDENT DEDENT DEDENT ans = sys . maxsize NEW_LINE for i in range ( 1 , mx + 1 ) : NEW_LINE INDENT if ( len ( mul [ i ] ) <= 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT a , b = mul [ i ] [ 0 ] , mul [ i ] [ 1 ] NEW_LINE lcm = ( a * b ) // i NEW_LINE ans = min ( ans , lcm ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 4 , 3 , 6 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minLCM ( arr , n ) ) NEW_LINE |
Count of triplets of numbers 1 to N such that middle element is always largest | Function to find Number of triplets for given Number N such that middle element is always greater than left and right side element . ; Check if arrangement is possible or Not ; Else return total ways ; Driver code . | def findArrangement ( N ) : NEW_LINE INDENT if ( N < 3 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT return ( ( N ) * ( N - 1 ) * ( N - 2 ) ) // 3 ; NEW_LINE DEDENT N = 10 ; NEW_LINE print ( findArrangement ( N ) ) ; NEW_LINE |
Lexicographically smallest array formed by at most one swap for every pair of adjacent indices | Function to find the lexicographically smallest array ; Maximum swaps possible ; Hash to store swaps performed ; Let current element be the minimum possible ; Find actual position of the minimum element ; Update minimum element and its position ; Perform swaps if possible ; Insert current swap in hash ; Print the required array ; Driver code | def findSmallestArray ( A , n ) : NEW_LINE INDENT count = n - 1 NEW_LINE mp = { ' ' } NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( count <= 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT mn = A [ i ] NEW_LINE pos = i NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( A [ j ] < mn ) : NEW_LINE INDENT mn = A [ j ] NEW_LINE pos = j NEW_LINE DEDENT DEDENT while ( pos > i and count > 0 and ( ( pos - 1 , pos ) not in mp ) ) : NEW_LINE INDENT mp . add ( ( pos - 1 , pos ) ) NEW_LINE A [ pos ] , A [ pos - 1 ] = A [ pos - 1 ] , A [ pos ] NEW_LINE pos -= 1 NEW_LINE count -= 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( A [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT A = [ 2 , 1 , 4 , 3 , 6 , 5 ] NEW_LINE n = len ( A ) NEW_LINE findSmallestArray ( A , n ) NEW_LINE |
Sum of all perfect square divisors of numbers from 1 to N | Python3 program to find the sum of all perfect square divisors of numbers from 1 to N ; Function for finding inverse of a number iteratively Here we will find the inverse of 6 , since it appears as denominator in the formula of sum of squares from 1 to N ; Store the value of the inverse of 6 once as we don 't need to call the function again and again ; Formula for finding the sum of first n squares ; No perfect square exists which is less than 4 ; Starting from 2 , present value of start is denoted here as curStart ; Finding end of the segment for which the contribution will be same ; Using the above mentioned formula to find ans % MOD ; Now for mthe next iteration start will become end + 1 ; Finally return the answer ; Driver Code ; Here we are adding x because we have not counted 1 as perfect squares so if u want to add it you can just add that number to the ans | from math import * NEW_LINE MOD = 1000000007 NEW_LINE def inv ( a ) : NEW_LINE INDENT o = 1 NEW_LINE p = MOD - 2 NEW_LINE while ( p > 0 ) : NEW_LINE INDENT if ( p % 2 == 1 ) : NEW_LINE INDENT o = ( o * a ) % MOD NEW_LINE DEDENT a = ( a * a ) % MOD NEW_LINE p >>= 1 NEW_LINE DEDENT return o NEW_LINE DEDENT inv6 = inv ( 6 ) NEW_LINE def sumOfSquares ( n ) : NEW_LINE INDENT n %= MOD NEW_LINE return ( ( ( n * ( n + 1 ) ) % MOD * ( 2 * n + 1 ) ) % MOD * inv6 ) % MOD NEW_LINE DEDENT def sums ( n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT curStart = 2 NEW_LINE ans = 0 NEW_LINE sqrtN = int ( sqrt ( n ) ) NEW_LINE while ( curStart <= n // curStart ) : NEW_LINE INDENT V = n // ( curStart * curStart ) NEW_LINE end = int ( sqrt ( n // V ) ) NEW_LINE ans += ( ( n // ( curStart * curStart ) % MOD * ( sumOfSquares ( end ) + MOD - sumOfSquares ( curStart - 1 ) ) ) % MOD ) NEW_LINE if ( ans >= MOD ) : NEW_LINE INDENT ans -= MOD NEW_LINE DEDENT curStart = end + 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Input = [ 5 ] NEW_LINE for x in Input : NEW_LINE INDENT print ( " sum β of β all β perfect β " \ " square β " , end = ' ' ) NEW_LINE print ( " divisors β from β 1 β to " , x , " is : β " , end = ' ' ) NEW_LINE print ( x + sums ( x ) ) NEW_LINE DEDENT DEDENT |
Check whether the binary equivalent of a number ends with "001" or not | Function returns true if s1 is suffix of s2 ; Function to check if binary equivalent of a number ends in "001" or not ; To store the binary number ; Count used to store exponent value ; Driver code | def isSuffix ( s1 , s2 ) : NEW_LINE INDENT n1 = len ( s1 ) ; NEW_LINE n2 = len ( s2 ) ; NEW_LINE if ( n1 > n2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( n1 ) : NEW_LINE INDENT if ( s1 [ n1 - i - 1 ] != s2 [ n2 - i - 1 ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def CheckBinaryEquivalent ( N ) : NEW_LINE INDENT B_Number = 0 ; NEW_LINE cnt = 0 ; NEW_LINE while ( N != 0 ) : NEW_LINE INDENT rem = N % 2 ; NEW_LINE c = 10 ** cnt ; NEW_LINE B_Number += rem * c ; NEW_LINE N //= 2 ; NEW_LINE cnt += 1 ; NEW_LINE DEDENT bin = str ( B_Number ) ; NEW_LINE return isSuffix ( "001" , bin ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 9 ; NEW_LINE if ( CheckBinaryEquivalent ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Check whether the binary equivalent of a number ends with "001" or not | Function to check if binary equivalent of a number ends in "001" or not ; To check if binary equivalent of a number ends in "001" or not ; Driver code | def CheckBinaryEquivalent ( N ) : NEW_LINE INDENT return ( N - 1 ) % 8 == 0 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 9 ; NEW_LINE if ( CheckBinaryEquivalent ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Panarithmic numbers within a given range | Python3 program to print Practical Numbers in given range ; Function to compute divisors of a number ; Vector to store divisors ; 1 will always be a divisor ; Check if i is squareroot of A then only one time insert it in ans ; Function to check that a number can be represented as summ of distinct divisor or not ; The value of subsett [ i ] [ j ] will be True if there is a subsett of sett [ 0. . j - 1 ] with summ equal to i ; If summ is 0 , then answer is True ; If summ is not 0 and sett is empty , then answer is False ; Fill the subsett table in bottom up manner ; Return the possibility of given summ ; Function to check a number is Practical or not ; Vector to store divisors ; If all numbers can be represented as summ of unique divisors ; Function to prPractical Numbers in a range ; Driver code | import math NEW_LINE def get_divisors ( A ) : NEW_LINE INDENT ans = [ ] NEW_LINE ans . append ( 1 ) NEW_LINE for i in range ( 2 , math . floor ( math . sqrt ( A ) ) + 1 ) : NEW_LINE INDENT if ( A % i == 0 ) : NEW_LINE INDENT ans . append ( i ) NEW_LINE if ( ( i * i ) != A ) : NEW_LINE INDENT ans . append ( A // i ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT def summ_Possible ( sett , summ ) : NEW_LINE INDENT n = len ( sett ) NEW_LINE subsett = [ [ 0 for i in range ( summ + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT subsett [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , summ + 1 ) : NEW_LINE INDENT subsett [ 0 ] [ i ] = False NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( summ + 1 ) : NEW_LINE INDENT if ( j < sett [ i - 1 ] ) : NEW_LINE INDENT subsett [ i ] [ j ] = subsett [ i - 1 ] [ j ] NEW_LINE DEDENT if ( j >= sett [ i - 1 ] ) : NEW_LINE INDENT subsett [ i ] [ j ] = ( subsett [ i - 1 ] [ j ] or subsett [ i - 1 ] [ j - sett [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT return subsett [ n ] [ summ ] NEW_LINE DEDENT def Is_Practical ( A ) : NEW_LINE INDENT divisors = [ ] NEW_LINE divisors = get_divisors ( A ) NEW_LINE for i in range ( 2 , A ) : NEW_LINE INDENT if ( summ_Possible ( divisors , i ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def print_practica_No ( A , B ) : NEW_LINE INDENT for i in range ( A , B + 1 ) : NEW_LINE INDENT if ( Is_Practical ( i ) == True ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT A = 1 NEW_LINE B = 100 NEW_LINE print_practica_No ( A , B ) NEW_LINE |
Maximize the division result of Array using given operations | Function to find the max result ; Sort the array in descending order ; Loop to divide in this order arr [ 0 ] / ( arr [ 1 ] / arr [ 2 ] / ... . arr [ n - 2 ] / arr [ n - 1 ] ) ; Return the final result ; Driver code | def maxDivision ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE mxdiv = arr [ 1 ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT mxdiv = mxdiv / arr [ i ] NEW_LINE DEDENT return arr [ 0 ] / mxdiv NEW_LINE DEDENT arr = [ 100 , 1000 , 10 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxDivision ( arr , n ) ) NEW_LINE |
Print all distinct Coprime sets possible from 1 to N | Function to prall co - prime sets ; Check if n is less than 4 then simply prall values till n ; For all the values of n > 3 ; Check if n is even then every set will contain 2 adjacent elements up - to n ; If n is odd then every set will contain 2 adjacent element except the last set which will have last three elements ; Last element for odd case ; Driver code | def coPrimeSet ( n ) : NEW_LINE INDENT firstadj = 0 ; NEW_LINE secadj = 0 ; NEW_LINE if ( n < 4 ) : NEW_LINE INDENT print ( " ( β " ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( i + " , β " ) ; NEW_LINE DEDENT print ( " ) " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT for i in range ( 0 , n / 2 ) : NEW_LINE INDENT firstadj = 2 * i + 1 ; NEW_LINE secadj = 2 * i + 2 ; NEW_LINE print ( " ( " , firstadj , " , β " , secadj , " ) " ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 0 , int ( n / 2 ) - 1 ) : NEW_LINE INDENT firstadj = 2 * i + 1 ; NEW_LINE secadj = 2 * i + 2 ; NEW_LINE print ( " ( " , firstadj , " , β " , secadj , " ) " ) ; NEW_LINE DEDENT print ( " ( " , ( n - 2 ) , " , β " , ( n - 1 ) , " , β " , n , " ) " ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; NEW_LINE coPrimeSet ( n ) ; NEW_LINE DEDENT |
Find the sequence number of a triangular number | Python3 code to print sequence number of a triangular number ; if N is not tringular number | import math NEW_LINE N = 21 NEW_LINE A = math . sqrt ( 2 * N + 0.25 ) - 0.5 NEW_LINE B = int ( A ) NEW_LINE if B != A : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( B ) NEW_LINE DEDENT |
Count subarrays with sum equal to its XOR value | Function to count the number of subarrays such that Xor of all the elements of that subarray is equal to sum of the elements ; Maintain two pointers left and right ; Iterating through the array ; Calculate the window where the above condition is satisfied ; Count will be ( right - left ) ; Remove the previous element as it is already included ; Driver code | def operation ( arr , N ) : NEW_LINE INDENT right = 0 ; ans = 0 ; NEW_LINE num = 0 ; NEW_LINE for left in range ( 0 , N ) : NEW_LINE INDENT while ( right < N and num + arr [ right ] == ( num ^ arr [ right ] ) ) : NEW_LINE INDENT num += arr [ right ] ; NEW_LINE right += 1 ; NEW_LINE DEDENT ans += right - left ; NEW_LINE if ( left == right ) : NEW_LINE INDENT right += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT num -= arr [ left ] ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE N = len ( arr ) NEW_LINE print ( operation ( arr , N ) ) ; NEW_LINE |
Count of pairs in an Array whose sum is Prime | Function for Sieve Of Eratosthenes ; Function to count total number of pairs of elements whose sum is prime ; Driver code | def sieveOfEratosthenes ( N ) : NEW_LINE INDENT isPrime = [ True for i in range ( N + 1 ) ] NEW_LINE isPrime [ 0 ] = False NEW_LINE isPrime [ 1 ] = False NEW_LINE i = 2 NEW_LINE while ( ( i * i ) <= N ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT j = 2 NEW_LINE while ( i * j <= N ) : NEW_LINE INDENT isPrime [ i * j ] = False NEW_LINE j += 1 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return isPrime NEW_LINE DEDENT def numPairsWithPrimeSum ( arr , n ) : NEW_LINE INDENT N = 2 * 1000000 NEW_LINE isPrime = sieveOfEratosthenes ( N ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT sum = arr [ i ] + arr [ j ] NEW_LINE if ( isPrime [ sum ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( numPairsWithPrimeSum ( arr , n ) ) NEW_LINE DEDENT |
Count of numbers in Array ending with digits of number N | Array to keep the track of digits occurred Initially all are 0 ( false ) ; Function to initialize true if the digit is present ; Variable to store the last digit ; Loop to iterate through every digit of the number N ; Updating the array according to the presence of the digit in n at the array index ; Function to check if the numbers in the array end with the digits of the number N ; Variable to store the count ; Variable to store the last digit ; Checking the presence of the last digit in N ; Function to find the required count ; Driver code ; Preprocessing | digit = [ 0 ] * 10 NEW_LINE def digitsPresent ( n ) : NEW_LINE INDENT lastDigit = 0 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT lastDigit = n % 10 ; NEW_LINE digit [ int ( lastDigit ) ] = 1 ; NEW_LINE n /= 10 ; NEW_LINE DEDENT DEDENT def checkLastDigit ( num ) : NEW_LINE INDENT count = 0 ; NEW_LINE lastDigit = 0 ; NEW_LINE lastDigit = num % 10 ; NEW_LINE if ( digit [ int ( lastDigit ) ] == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count ; NEW_LINE DEDENT def findCount ( N , K , arr ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( K ) : NEW_LINE INDENT if checkLastDigit ( arr [ i ] ) == 1 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT N = 1731 ; NEW_LINE digitsPresent ( N ) ; NEW_LINE K = 5 ; NEW_LINE arr = [ 57 , 6786 , 1111 , 3 , 9812 ] ; NEW_LINE findCount ( N , K , arr ) ; NEW_LINE |
Check if count of even divisors of N is equal to count of odd divisors | Function to check if count of even and odd divisors are equal ; If ( n - 2 ) % 4 is an integer , then return true else return false ; Given Number ; Function Call | def divisorsSame ( n ) : NEW_LINE INDENT return ( n - 2 ) % 4 == 0 ; NEW_LINE DEDENT N = 6 ; NEW_LINE if ( divisorsSame ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Nth term of a sequence formed by sum of current term with product of its largest and smallest digit | Function to find integer ; Because 1 st integer is K itself ; Initialize min_d and max_d ; Updating min_d and max_d ; Break if min digit is 0 ; Driver code | def find ( K , N ) : NEW_LINE INDENT N = N - 1 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT curr_term = K NEW_LINE min_d = 9 NEW_LINE max_d = 0 NEW_LINE while curr_term > 0 : NEW_LINE INDENT r = int ( curr_term % 10 ) NEW_LINE min_d = min ( min_d , r ) NEW_LINE max_d = max ( max_d , r ) NEW_LINE curr_term = int ( curr_term / 10 ) NEW_LINE DEDENT if min_d == 0 : NEW_LINE break NEW_LINE K = K + min_d * max_d NEW_LINE return K NEW_LINE DEDENT DEDENT K = 487 NEW_LINE N = 2 NEW_LINE print ( find ( K , N ) ) NEW_LINE |
Count of subarrays whose sum is a perfect square | Python3 code for the above approach . ; Function to find count of subarrays whose sum is a perfect square . ; To search for index with ( current prefix sum - j * j ) ; Storing the prefix sum ; Used to track the minimum value in prefixSum ; Calculating the prefixSum and tracking the prefixMin ; Below statement is used if array contains negative numbers ; Counts the no of subarrays with perfect square sum ; As 0 is a perfect square , so we initialize 0 th index - key with value 1 ; Here we count the perfect square subarray sum by searching if there is a prefix with sum = ( current prefixSum - ( sq * sq ) ) ; Increasing our subarray count ; Increasing the current prefixSum index value in map by 1 to count the other perfect squares while traversing further ; Driver code ; Printing the result | from collections import defaultdict NEW_LINE def countSubarrays ( arr , n ) : NEW_LINE INDENT mp = defaultdict ( lambda : 0 ) NEW_LINE prefixSum = [ 0 ] * n NEW_LINE prefixMin = 0 NEW_LINE prefixSum [ 0 ] = arr [ 0 ] NEW_LINE prefixMin = min ( prefixMin , prefixSum [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefixSum [ i ] = prefixSum [ i - 1 ] + arr [ i ] NEW_LINE prefixMin = min ( prefixMin , prefixSum [ i ] ) NEW_LINE DEDENT countSubs = 0 NEW_LINE mp [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = 0 NEW_LINE while prefixSum [ i ] - j * j >= prefixMin : NEW_LINE INDENT if prefixSum [ i ] - j * j in mp : NEW_LINE INDENT countSubs += mp [ prefixSum [ i ] - j * j ] NEW_LINE DEDENT j += 1 NEW_LINE DEDENT mp [ prefixSum [ i ] ] += 1 NEW_LINE DEDENT return countSubs NEW_LINE DEDENT arr = [ 2 , 3 , - 5 , 6 , - 7 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE ans = countSubarrays ( arr , n ) NEW_LINE print ( ans ) NEW_LINE |
Find if two given Quadratic equations have common roots or not | Function to check if 2 quadratic equations have common roots or not . ; Driver code | def checkSolution ( a1 , b1 , c1 , a2 , b2 , c2 ) : NEW_LINE INDENT return ( ( a1 / a2 ) == ( b1 / b2 ) and ( b1 / b2 ) == ( c1 / c2 ) ) NEW_LINE DEDENT a1 , b1 , c1 = 1 , - 5 , 6 NEW_LINE a2 , b2 , c2 = 2 , - 10 , 12 NEW_LINE if ( checkSolution ( a1 , b1 , c1 , a2 , b2 , c2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Check if roots of a Quadratic Equation are numerically equal but opposite in sign or not | Function to find the required answer ; Driver code | def checkSolution ( a , b , c ) : NEW_LINE INDENT if b == 0 : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT a = 2 NEW_LINE b = 0 NEW_LINE c = 2 NEW_LINE checkSolution ( a , b , c ) NEW_LINE |
Count of index pairs in array whose range product is a positive integer | Python3 program to find the count of index pairs in the array positive range product ; Condition if number of negative elements is even then increase even_count ; Otherwise increase odd_count ; Condition if current element is negative ; Condition if number of negative elements is even then add even_count in answer ; Otherwise add odd_count in answer ; Driver Code | def positiveProduct ( arr , n ) : NEW_LINE INDENT even_count = 0 NEW_LINE odd_count = 0 NEW_LINE total_count = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( total_count % 2 == 0 ) : NEW_LINE INDENT even_count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd_count += 1 NEW_LINE DEDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT total_count += 1 NEW_LINE DEDENT if ( total_count % 2 == 0 ) : NEW_LINE INDENT ans += even_count NEW_LINE DEDENT else : NEW_LINE INDENT ans += odd_count NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 5 , - 3 , 3 , - 1 , 1 ] NEW_LINE size = len ( A ) NEW_LINE positiveProduct ( A , size ) NEW_LINE DEDENT |
Pair of integers having difference of their fifth power as X | Python3 implementation to find a pair of integers A & B such that difference of fifth power is equal to the given number X ; Function to find a pair of integers A & B such that difference of fifth power is equal to the given number X ; Loop to choose every possible pair with in the range ; Check if equation holds ; Driver Code ; Function Call | import math NEW_LINE def findPair ( x ) : NEW_LINE INDENT lim = 120 NEW_LINE for i in range ( - lim , lim + 1 ) : NEW_LINE INDENT for j in range ( - lim , lim + 1 ) : NEW_LINE INDENT if ( math . pow ( i , 5 ) - math . pow ( j , 5 ) == x ) : NEW_LINE INDENT print ( i , end = ' β ' ) NEW_LINE print ( j , end = ' ' ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( " - 1" ) NEW_LINE DEDENT X = 33 NEW_LINE findPair ( X ) NEW_LINE |
Sum of GCD of all numbers upto N with N itself | Function to Find Sum of GCD of each numbers ; Consider all prime factors of no . and subtract their multiples from result ; Check if p is a prime factor ; If yes , then update no and result ; If no has a prime factor greater than Math . sqrt ( n ) then at - most one such prime factor exists ; Return the result ; Finding GCD of pairs ; Calculate the divisors ; Return count of numbers from 1 to N with GCD d with N ; Check if d1 and d2 are equal then skip this ; Driver code | def getCount ( d , n ) : NEW_LINE INDENT no = n // d ; NEW_LINE result = no ; NEW_LINE for p in range ( 2 , int ( pow ( no , 1 / 2 ) ) + 1 ) : NEW_LINE INDENT if ( no % p == 0 ) : NEW_LINE INDENT while ( no % p == 0 ) : NEW_LINE INDENT no //= p ; NEW_LINE DEDENT result -= result // p ; NEW_LINE DEDENT DEDENT if ( no > 1 ) : NEW_LINE INDENT result -= result // no ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT def sumOfGCDofPairs ( n ) : NEW_LINE INDENT res = 0 ; NEW_LINE for i in range ( 1 , int ( pow ( n , 1 / 2 ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT d1 = i ; NEW_LINE d2 = n // i ; NEW_LINE res += d1 * getCount ( d1 , n ) ; NEW_LINE if ( d1 != d2 ) : NEW_LINE INDENT res += d2 * getCount ( d2 , n ) ; NEW_LINE DEDENT DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 ; NEW_LINE print ( sumOfGCDofPairs ( n ) ) ; NEW_LINE DEDENT |
Check whether Array represents a Fibonacci Series or not | Returns true if a permutation of arr [ 0. . n - 1 ] can form a Fibonacci Series ; Sort array ; After sorting , check if every element is equal to the sum of previous 2 elements ; Driver Code | def checkIsFibonacci ( arr , n ) : NEW_LINE INDENT if ( n == 1 or n == 2 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT arr . sort ( ) NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( ( arr [ i - 1 ] + arr [ i - 2 ] ) != arr [ i ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 8 , 3 , 5 , 13 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE if ( checkIsFibonacci ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Last digit in a power of 2 | Python3 program to find last digit in a power of 2. ; Corner case ; Find the shift in current cycle and return value accordingly ; Driver code | def lastDigit2PowerN ( n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif n % 4 == 1 : NEW_LINE INDENT return 2 NEW_LINE DEDENT elif n % 4 == 2 : NEW_LINE INDENT return 4 NEW_LINE DEDENT elif n % 4 == 3 : NEW_LINE INDENT return 8 NEW_LINE DEDENT else : NEW_LINE DEDENT for n in range ( 20 ) : NEW_LINE INDENT print ( lastDigit2PowerN ( n ) , end = " β " ) NEW_LINE DEDENT |
Sum of all subsequences of length K | Function to find nCr ; Function that returns factorial of n ; Function for finding sum of all K length subsequences ; Calculate the sum of array ; Calculate nCk ; Return the final result ; Driver Code | def nCr ( n , r ) : NEW_LINE INDENT return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) NEW_LINE DEDENT def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def sumSubsequences ( arr , n , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum = sum + arr [ i ] NEW_LINE DEDENT kLengthSubSequence = nCr ( n , k ) NEW_LINE ans = sum * ( ( k * kLengthSubSequence ) / n ) ; NEW_LINE return ans NEW_LINE DEDENT arr = [ 7 , 8 , 9 , 2 ] NEW_LINE k = 2 NEW_LINE n = len ( arr ) NEW_LINE print ( sumSubsequences ( arr , n , k ) ) NEW_LINE |
Sum of first K numbers which are not divisible by N | Function to find the sum ; Find the last multiple of N ; Find the K - th non - multiple of N ; Calculate the sum of all elements from 1 to val ; Calculate the sum of all multiples of N between 1 to val ; Driver code | def findSum ( n , k ) : NEW_LINE INDENT val = ( k // ( n - 1 ) ) * n ; NEW_LINE rem = k % ( n - 1 ) ; NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT val = val - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT val = val + rem ; NEW_LINE DEDENT sum = ( val * ( val + 1 ) ) // 2 ; NEW_LINE x = k // ( n - 1 ) ; NEW_LINE sum_of_multiples = ( x * ( x + 1 ) * n ) // 2 ; NEW_LINE sum -= sum_of_multiples ; NEW_LINE return sum ; NEW_LINE DEDENT n = 7 ; k = 13 ; NEW_LINE print ( findSum ( n , k ) ) NEW_LINE |
Count of the non | Python3 program to find count of non - prime divisors of given number ; Function to factors of the given number ; Loop to find the divisors of the number 2 ; Loop to find the divisors of the given number upto SQRT ( N ) ; Condition to check if the rest number is also a prime number ; Function to find the non - prime divisors of the given number ; Loop to count the number of the total divisors of given number ; Driver Code ; Function Call | from math import sqrt NEW_LINE def getFactorization ( x ) : NEW_LINE INDENT count = 0 NEW_LINE v = [ ] NEW_LINE while ( x % 2 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE x = x // 2 NEW_LINE DEDENT if ( count != 0 ) : NEW_LINE INDENT v . append ( count ) NEW_LINE DEDENT for i in range ( 3 , int ( sqrt ( x ) ) + 12 ) : NEW_LINE INDENT count = 0 NEW_LINE while ( x % i == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE x //= i NEW_LINE DEDENT if ( count != 0 ) : NEW_LINE INDENT v . append ( count ) NEW_LINE DEDENT DEDENT if ( x > 1 ) : NEW_LINE INDENT v . append ( 1 ) NEW_LINE DEDENT return v NEW_LINE DEDENT def nonPrimeDivisors ( N ) : NEW_LINE INDENT v = getFactorization ( N ) NEW_LINE ret = 1 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT ret = ret * ( v [ i ] + 1 ) NEW_LINE DEDENT ret = ret - len ( v ) NEW_LINE return ret NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE print ( nonPrimeDivisors ( N ) ) NEW_LINE DEDENT |
Check if a number is Full Fibonacci or not | Python3 program to check if a given number is a Full Fibonacci Number or not ; A utility function that returns true if x is perfect square ; Returns true if N is a Fibonacci Number and false otherwise ; N is Fibonacci if one of 5 * N ^ 2 + 4 or 5 * N ^ 2 - 4 or both is a perferct square ; Function to check digits ; Check if all digits are fibonacci or not ; Extract digit ; Check if the current digit is not fibonacci ; Function to check and return if N is a Full Fibonacci number or not ; Driver Code | from math import * NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT s = sqrt ( x ) NEW_LINE return ( s * s == x ) NEW_LINE DEDENT def isFibonacci ( n ) : NEW_LINE INDENT return ( isPerfectSquare ( 5 * n * n + 4 ) or isPerfectSquare ( 5 * n * n - 4 ) ) NEW_LINE DEDENT def checkDigits ( n ) : NEW_LINE INDENT while ( n ) : NEW_LINE INDENT dig = n % 10 NEW_LINE if ( dig == 4 and dig == 6 and dig == 7 and dig == 9 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n /= 10 NEW_LINE DEDENT return True NEW_LINE DEDENT def isFullfibonacci ( n ) : NEW_LINE INDENT return ( checkDigits ( n ) and isFibonacci ( n ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 13 NEW_LINE if ( isFullfibonacci ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Check whether a large number is divisible by 53 or not | Function to check if the number is divisible by 53 or not ; Driver Code | def isDivisible ( s ) : NEW_LINE INDENT flag = 0 NEW_LINE while ( len ( s ) > 4 ) : NEW_LINE INDENT l = len ( s ) - 1 NEW_LINE x = ( ord ( s [ l ] ) - ord ( '0' ) ) * 37 NEW_LINE s = s [ : : - 1 ] NEW_LINE s = s . replace ( '0' , ' ' , 1 ) NEW_LINE i = 0 NEW_LINE carry = 0 NEW_LINE while ( x ) : NEW_LINE INDENT d = ( ( ord ( s [ i ] ) - ord ( '0' ) ) - ( x % 10 ) - carry ) NEW_LINE if ( d < 0 ) : NEW_LINE INDENT d += 10 NEW_LINE carry = 1 NEW_LINE DEDENT else : NEW_LINE INDENT carry = 0 NEW_LINE DEDENT s = s . replace ( s [ i ] , chr ( d + ord ( '0' ) ) , 1 ) NEW_LINE x //= 10 NEW_LINE i += 1 NEW_LINE DEDENT while ( carry and i < l ) : NEW_LINE INDENT d = ( ord ( s [ i ] ) - ord ( '0' ) ) - carry NEW_LINE if ( d < 0 ) : NEW_LINE INDENT d += 10 NEW_LINE carry = 1 NEW_LINE DEDENT else : NEW_LINE INDENT carry = 0 NEW_LINE DEDENT s = s . replace ( s [ i ] , chr ( d + ord ( '0' ) ) , 1 ) NEW_LINE i += 1 NEW_LINE DEDENT s = s [ : : - 1 ] NEW_LINE DEDENT num = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT num = num * 10 + ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT if ( num % 53 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = "1843246219106" NEW_LINE if ( isDivisible ( N ) ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT DEDENT |
Check whether two numbers are in silver ratio | Function to check that two numbers are in silver ratio ; Swapping the numbers such that A contains the maximum number between these numbers ; First Ratio ; Second Ratio ; Condition to check that two numbers are in silver ratio ; Driver Code ; Function Call | def checksilverRatio ( a , b ) : NEW_LINE INDENT a , b = max ( a , b ) , min ( a , b ) NEW_LINE ratio1 = round ( a / b , 3 ) NEW_LINE ratio2 = round ( ( 2 * a + b ) / a , 3 ) NEW_LINE if ratio1 == ratio2 and ratio1 == 2.414 : NEW_LINE INDENT print ( " Yes " ) NEW_LINE return True NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 2.414 NEW_LINE b = 1 NEW_LINE checksilverRatio ( a , b ) NEW_LINE DEDENT |
Nth term where K + 1 th term is product of Kth term with difference of max and min digit of Kth term | Function to find minimum digit in the decimal representation of N ; Loop to find the minimum digit in the number ; Function to find maximum digit in the decimal representation of N ; Loop to find the maximum digit in the number ; Function to find the value of the given function ; Loop to compute the values of the given number ; Driver Code ; Function Call | def MIN ( n ) : NEW_LINE INDENT ans = 11 NEW_LINE while n : NEW_LINE INDENT ans = min ( ans , n % 10 ) NEW_LINE n //= 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT def MAX ( n ) : NEW_LINE INDENT ans = - 1 NEW_LINE while n : NEW_LINE INDENT ans = max ( ans , n % 10 ) NEW_LINE n //= 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT def Find_value ( n , k ) : NEW_LINE INDENT k -= 1 NEW_LINE ( x , y ) = ( 0 , 0 ) NEW_LINE while k : NEW_LINE INDENT k -= 1 NEW_LINE x = MIN ( n ) NEW_LINE y = MAX ( n ) NEW_LINE if ( ( y - x ) == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT n *= ( y - x ) NEW_LINE DEDENT print ( n , end = ' β ' ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ( N , D ) = ( 487 , 5 ) NEW_LINE Find_value ( N , D ) NEW_LINE DEDENT |
Program to check if N is a Decagonal Number | Python3 program for the above approach ; Function to check if N is a decagonal number ; Condition to check if the number is a decagonal number ; Driver Code ; Given number ; Function Call | import math NEW_LINE def isdecagonal ( N ) : NEW_LINE INDENT n = ( 3 + math . sqrt ( 16 * N + 9 ) ) / 8 NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE if isdecagonal ( N ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT DEDENT |
Program to check if N is a Octadecagon number | Python3 program for the above approach ; Function to check if N is a octadecagon number ; Condition to check if the number is a octadecagon number ; Driver code ; Given number ; Function Call | import math NEW_LINE def isOctadecagon ( N ) : NEW_LINE INDENT n = ( 14 + math . sqrt ( 128 * N + 196 ) ) // 32 NEW_LINE return ( ( n - int ( n ) ) == 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 18 NEW_LINE if isOctadecagon ( N ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT DEDENT |
Count of subsequences which consists exactly K prime numbers | Returns factorial of n ; Function to return total number of combinations ; Function check whether a number is prime or not ; Corner case ; Check from 2 to n - 1 ; Function for finding number of subsequences which consists exactly K primes ; If number of primes are less than k ; Driver code | def fact ( n ) : NEW_LINE INDENT res = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def nCr ( n , r ) : NEW_LINE INDENT return ( fact ( n ) // ( fact ( r ) * fact ( n - r ) ) ) NEW_LINE DEDENT 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 countSubsequences ( arr , n , k ) : NEW_LINE INDENT countPrime = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( isPrime ( arr [ i ] ) ) : NEW_LINE INDENT countPrime += 1 NEW_LINE DEDENT DEDENT if ( countPrime < k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( nCr ( countPrime , k ) * pow ( 2 , ( n - countPrime ) ) ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] NEW_LINE K = 3 NEW_LINE n = len ( arr ) NEW_LINE print ( countSubsequences ( arr , n , K ) ) NEW_LINE |
Length of the longest alternating even odd subarray | Function to find the longest subarray ; Length of longest alternating subarray ; Iterate in the array ; Increment count if consecutive elements has an odd sum ; Store maximum count in longest ; Reinitialize cnt as 1 consecutive elements does not have an odd sum ; Length of ' longest ' can never be 1 since even odd has to occur in pair or more so return 0 if longest = 1 ; Driver Code | def longestEvenOddSubarray ( arr , n ) : NEW_LINE INDENT longest = 1 NEW_LINE cnt = 1 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( ( arr [ i ] + arr [ i + 1 ] ) % 2 == 1 ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE DEDENT else : NEW_LINE INDENT longest = max ( longest , cnt ) NEW_LINE cnt = 1 NEW_LINE DEDENT DEDENT if ( longest == 1 ) : NEW_LINE return 0 NEW_LINE return max ( cnt , longest ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 7 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestEvenOddSubarray ( arr , n ) ) NEW_LINE |
Check whether given number N is a Moran Number or not | Function to calculate digit sum ; Function to check if number is prime ; Function to check if number is moran number ; Calculate digit sum ; Check if n is completely divisible by digit sum ; Calculate the quotient ; Check if the number is prime ; Driver code | def digSum ( a ) : NEW_LINE INDENT _sum = 0 NEW_LINE while ( a ) : NEW_LINE INDENT _sum += a % 10 NEW_LINE a = a // 10 NEW_LINE DEDENT return _sum NEW_LINE DEDENT def isPrime ( r ) : NEW_LINE INDENT s = True NEW_LINE i = 2 NEW_LINE while i * i <= r : NEW_LINE INDENT if ( r % i == 0 ) : NEW_LINE INDENT s = False NEW_LINE break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return s NEW_LINE DEDENT def moranNo ( n ) : NEW_LINE INDENT dup = n NEW_LINE _sum = digSum ( dup ) NEW_LINE if ( n % _sum == 0 ) : NEW_LINE INDENT c = n // _sum NEW_LINE if ( isPrime ( c ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " No " ) NEW_LINE DEDENT n = 21 NEW_LINE moranNo ( n ) NEW_LINE |
Program to check if N is a Hendecagonal Number | Python3 program for the above approach ; Function to check if N is a Hendecagonal Number ; Condition to check if the number is a hendecagonal number ; Given Number ; Function call | import math NEW_LINE def ishendecagonal ( N ) : NEW_LINE INDENT n = ( 7 + math . sqrt ( 72 * N + 49 ) ) // 18 ; NEW_LINE return ( n - int ( n ) ) == 0 ; NEW_LINE DEDENT N = 11 ; NEW_LINE if ( ishendecagonal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Program to check if N is a Hexadecagonal Number | Python3 program for the above approach ; Function to check if N is a hexadecagonal number ; Condition to check if the number is a hexadecagonal number ; Driver code ; Given number ; Function call | from math import sqrt NEW_LINE def ishexadecagonal ( N ) : NEW_LINE INDENT n = ( 12 + sqrt ( 112 * N + 144 ) ) / 28 ; NEW_LINE return ( n - int ( n ) ) == 0 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 16 ; NEW_LINE if ( ishexadecagonal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Program to check if N is a Nonagonal Number | Function to check if N is a nonagonal number ; Condition to check if the number is a nonagonal number ; Driver code ; Given number ; Function call | def isnonagonal ( N ) : NEW_LINE INDENT n = ( 5 + pow ( ( 56 * N + 25 ) , 1 / 2 ) ) / 14 ; NEW_LINE return ( n - int ( n ) ) == 0 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 9 ; NEW_LINE if ( isnonagonal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Count of decreasing pairs formed from numbers 1 to N | Function to count the possible number of pairs ; if the number is even then the answer in ( N / 2 ) - 1 ; if the number is odd then the answer in N / 2 ; Driver code | def divParts ( N ) : NEW_LINE INDENT if ( N % 2 == 0 ) : NEW_LINE INDENT print ( ( N / 2 ) - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( N / 2 ) ; NEW_LINE DEDENT DEDENT N = 8 ; NEW_LINE divParts ( N ) ; NEW_LINE |
Count the minimum steps to reach 0 from the given integer N | Function returns min step to reach 0 from N ; Direct possible reduction of value N ; Remaining steps needs to be reduced by 1 ; Summation of both the values ; Return the final answer ; Driver code | def getMinSteps ( n , jump ) : NEW_LINE INDENT quotient = int ( n / jump ) NEW_LINE remainder = n % jump NEW_LINE steps = quotient + remainder NEW_LINE return steps NEW_LINE DEDENT N = 6 NEW_LINE K = 3 NEW_LINE print ( getMinSteps ( N , K ) ) NEW_LINE |
Construct an Array of size N whose sum of cube of all elements is a perfect square | Function to construct an array of size N ; Prints the first N natural numbers ; Driver code | def constructArray ( N ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( i , end = ' β ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE constructArray ( N ) NEW_LINE DEDENT |
Program to check if N is a Centered Decagonal Number | Python3 program for the above approach ; Function to check if the number N is a centered decagonal number ; Condition to check if N is centered decagonal number ; Driver Code ; Function call | import numpy as np NEW_LINE def isCentereddecagonal ( N ) : NEW_LINE INDENT n = ( 5 + np . sqrt ( 20 * N + 5 ) ) / 10 NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT N = 11 NEW_LINE if ( isCentereddecagonal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Count Sexy Prime Pairs in the given array | Python 3 program to count Sexy Prime pairs in array ; A utility function to check if the number n is prime or not ; Base Cases ; Check to skip middle five numbers in below loop ; If n is divisible by i and i + 2 then it is not prime ; A utility function that check if n1 and n2 are SPP ( Sexy Prime Pair ) or not ; Function to find SPP ( Sexy Prime Pair ) pairs from the given array ; Iterate through all pairs ; Increment count if SPP ( Sexy Prime Pair ) pair ; Driver code ; Function call to find SPP ( Sexy Prime Pair ) pair | from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 5 , int ( sqrt ( n ) ) + 1 , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 6 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def SexyPrime ( n1 , n2 ) : NEW_LINE INDENT return ( isPrime ( n1 ) and isPrime ( n2 ) and abs ( n1 - n2 ) == 6 ) NEW_LINE DEDENT def countSexyPairs ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( SexyPrime ( 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 = [ 6 , 7 , 5 , 11 , 13 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countSexyPairs ( arr , n ) ) NEW_LINE DEDENT |
Find the K | Function to find the index of number at first position of kth sequence of set of size n ; n_actual_fact = n ! ; First position of the kth sequence will be occupied by the number present at index = k / ( n - 1 ) ! ; Function to find the kth permutation of n numbers ; Store final answer ; Insert all natural number upto n in set ; Subtract 1 to get 0 based indexing ; Mark the first position ; itr now points to the number at index in set s ; remove current number from the set ; Driver code | def findFirstNumIndex ( k , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 , k NEW_LINE DEDENT n -= 1 NEW_LINE first_num_index = 0 NEW_LINE n_partial_fact = n NEW_LINE while ( k >= n_partial_fact and n > 1 ) : NEW_LINE INDENT n_partial_fact = n_partial_fact * ( n - 1 ) NEW_LINE n -= 1 NEW_LINE DEDENT first_num_index = k // n_partial_fact NEW_LINE k = k % n_partial_fact NEW_LINE return first_num_index , k NEW_LINE DEDENT def findKthPermutation ( n , k ) : NEW_LINE INDENT ans = " " NEW_LINE s = set ( ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT s . add ( i ) NEW_LINE DEDENT k = k - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT itr = list ( s ) NEW_LINE index , k = findFirstNumIndex ( k , n - i ) NEW_LINE ans += str ( itr [ index ] ) NEW_LINE itr . pop ( index ) NEW_LINE s = set ( itr ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE k = 4 NEW_LINE kth_perm_seq = findKthPermutation ( n , k ) NEW_LINE print ( kth_perm_seq ) NEW_LINE DEDENT |
Find the Largest N digit perfect square number in Base B | Python3 implementation to find the largest N digit perfect square number in base B ; Function to find the largest N digit number ; Largest n - digit perfect square ; Print the result ; Driver Code | import math NEW_LINE def nDigitPerfectSquares ( n , b ) : NEW_LINE INDENT largest = pow ( math . ceil ( math . sqrt ( pow ( b , n ) ) ) - 1 , 2 ) NEW_LINE print ( largest ) NEW_LINE DEDENT N = 1 NEW_LINE B = 8 NEW_LINE nDigitPerfectSquares ( N , B ) NEW_LINE |
Find Cube root of a number using Log function | Python3 program to find cube root of a number using logarithm ; Function to find the cube root ; Calculate the cube root ; Return the final answer ; Driver code | import numpy as np NEW_LINE def cubeRoot ( n ) : NEW_LINE INDENT ans = pow ( 3 , ( 1.0 / 3 ) * ( np . log ( n ) / np . log ( 3 ) ) ) NEW_LINE return ans NEW_LINE DEDENT N = 8 NEW_LINE print ( " % .2f " % cubeRoot ( N ) ) NEW_LINE |
Find the maximum possible value for the given periodic function | Function to return the maximum value of f ( x ) ; Driver code | def floorMax ( A , B , N ) : NEW_LINE INDENT x = min ( B - 1 , N ) NEW_LINE return ( A * x ) // B NEW_LINE DEDENT A = 11 NEW_LINE B = 10 NEW_LINE N = 9 NEW_LINE print ( floorMax ( A , B , N ) ) NEW_LINE |
Minimum moves taken to move coin of each cell to any one cell of Matrix | Function to find the minimum number of moves taken to move the element of each cell to any one cell of the square matrix of odd length ; Initializing count to 0 ; Number of layers that are around the centre element ; Iterating over ranger of layers ; Increase the value of count by 8 * k * k ; Driver code | def calculateMoves ( n ) : NEW_LINE INDENT count = 0 NEW_LINE layers = n // 2 NEW_LINE for k in range ( 1 , layers + 1 ) : NEW_LINE INDENT count += 8 * k * k NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE print ( calculateMoves ( N ) ) NEW_LINE DEDENT |
Check if N can be represented as sum of squares of two consecutive integers | Python3 implementation to check that a number is sum of squares of 2 consecutive numbers or not ; Function to check that the a number is sum of squares of 2 consecutive numbers or not ; Condition to check if the a number is sum of squares of 2 consecutive numbers or not ; Driver code ; Function call | import math NEW_LINE def isSumSquare ( N ) : NEW_LINE INDENT n = ( 2 + math . sqrt ( 8 * N - 4 ) ) / 2 NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT i = 13 NEW_LINE if isSumSquare ( i ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT DEDENT |
Program to check if N is a Centered heptagonal number | Python3 implementation to check that a number is a centered heptagonal number or not ; Function to check that the number is a centered heptagonal number ; Condition to check if the number is a centered heptagonal number ; Driver Code ; Function call | import math NEW_LINE def isCenteredheptagonal ( N ) : NEW_LINE INDENT n = ( 7 + math . sqrt ( 56 * N - 7 ) ) / 14 NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT n = 8 NEW_LINE if ( isCenteredheptagonal ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Program to check if N is a Centered nonadecagonal number | Python3 implementation to check that a number is a Centered nonadecagonal number or not ; Function to check that the number is a Centered nonadecagonal number ; Condition to check if the number is a Centered nonadecagonal number ; Driver Code ; Function call | import math NEW_LINE def isCenterednonadecagonal ( N ) : NEW_LINE INDENT n = ( 19 + math . sqrt ( 152 * N + 209 ) ) / 38 ; NEW_LINE return ( n - int ( n ) ) == 0 ; NEW_LINE DEDENT n = 20 ; NEW_LINE if ( isCenterednonadecagonal ( n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Program to check if N is a Centered Octadecagonal number | Python3 implementation to check that a number is a centered octadecagonal number or not ; Function to check that the number is a centered octadecagonal number ; Implement the formula generated ; Condition to check if the number is a centered octadecagonal number ; Driver code ; Function call | import math NEW_LINE def isCenteredOctadecagonal ( N ) : NEW_LINE INDENT n = ( 9 + math . sqrt ( 36 * N + 45 ) ) / 18 ; NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 19 NEW_LINE if isCenteredOctadecagonal ( n ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT DEDENT |
Logarithm tricks for Competitive Programming | Python3 implementation to find Kth root of the number ; Function to find the Kth root of the number ; Driver code | import math NEW_LINE def kth_root ( n , k ) : NEW_LINE INDENT return ( pow ( k , ( ( 1.0 / k ) * ( math . log ( n ) / math . log ( k ) ) ) ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 8.0 NEW_LINE k = 3 NEW_LINE print ( round ( kth_root ( n , k ) ) ) NEW_LINE DEDENT |
Logarithm tricks for Competitive Programming | Python3 implementation to check if a number is a power of the other number ; Function to check if the number is power of K ; Logarithm function to calculate value ; Compare to the result1 or result2 both are equal ; Driver code | from math import log NEW_LINE def isPower ( n , k ) : NEW_LINE INDENT res1 = int ( log ( n ) / log ( k ) ) NEW_LINE res2 = log ( n ) / log ( k ) NEW_LINE return ( res1 == res2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 8 NEW_LINE k = 2 NEW_LINE if ( isPower ( n , k ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Count of subarrays which start and end with the same element | Function to find total sub - array which start and end with same element ; Initialize result with 0 ; Array to count frequency of 1 to N ; Update frequency of A [ i ] ; Update result with sub - array contributed by number i ; Print the result ; Driver code | def cntArray ( A , N ) : NEW_LINE INDENT result = 0 NEW_LINE frequency = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT frequency [ A [ i ] ] = frequency [ A [ i ] ] + 1 NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT frequency_of_i = frequency [ i ] NEW_LINE result = result + ( ( frequency_of_i ) * ( frequency_of_i + 1 ) ) / 2 NEW_LINE DEDENT print ( int ( result ) ) NEW_LINE print ( " " ) NEW_LINE DEDENT A = [ 1 , 5 , 6 , 1 , 9 , 5 , 8 , 10 , 8 , 9 ] NEW_LINE N = len ( A ) NEW_LINE cntArray ( A , N ) NEW_LINE |
Length of array pair formed where one contains all distinct elements and other all same elements | Function to find the max size possible ; Counting the maximum frequency ; Counting total distinct elements ; Find max of both the answer ; Driver code | def findMaxSize ( a , n ) : NEW_LINE INDENT frq = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT frq [ a [ i ] ] += 1 NEW_LINE DEDENT maxfrq = max ( frq ) NEW_LINE dist = n + 1 - frq . count ( 0 ) NEW_LINE ans1 = min ( maxfrq - 1 , dist ) NEW_LINE ans2 = min ( maxfrq , dist - 1 ) NEW_LINE ans = max ( ans1 , ans2 ) NEW_LINE return ans NEW_LINE DEDENT arr = [ 4 , 2 , 4 , 1 , 4 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMaxSize ( arr , n ) ) NEW_LINE |
Longest subarray with all elements same | Function to find largest sub array with all equal elements . ; Traverse the array ; If element is same as previous increment temp value ; Return the required answer ; Driver code ; Function call | def subarray ( arr , n ) : NEW_LINE INDENT ans , temp = 1 , 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] == arr [ i - 1 ] : NEW_LINE INDENT temp = temp + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans = max ( ans , temp ) NEW_LINE temp = 1 NEW_LINE DEDENT DEDENT ans = max ( ans , temp ) NEW_LINE return ans NEW_LINE DEDENT arr = [ 2 , 2 , 1 , 1 , 2 , 2 , 2 , 3 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( subarray ( arr , n ) ) NEW_LINE |
Min and max length subarray having adjacent element difference atmost K | Function to find the maximum and minimum length subarray ; Initialise minimum and maximum size of subarray in worst case ; Left will scan the size of possible subarray in left of selected element ; Right will scan the size of possible subarray in right of selected element ; Temp will store size of group associateed with every element ; Loop to find size of subarray for every element of array ; Left will move in left direction and compare difference between itself and element left to it ; Right will move in right direction and compare difference between itself and element right to it ; If subarray of much lesser or much greater is found than yet known then update ; Print minimum and maximum possible size of subarray ; Driver Code ; Function call to find maximum and minimum possible sub array | def findMaxMinSubArray ( arr , K , n ) : NEW_LINE INDENT min = n NEW_LINE max = 0 NEW_LINE left = 0 NEW_LINE right = n NEW_LINE tmp = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT tmp = 1 NEW_LINE left = i NEW_LINE while ( left - 1 >= 0 and abs ( arr [ left ] - arr [ left - 1 ] ) <= K ) : NEW_LINE INDENT left = left - 1 NEW_LINE tmp = tmp + 1 NEW_LINE DEDENT right = i NEW_LINE while ( right + 1 <= n - 1 and abs ( arr [ right ] - arr [ right + 1 ] ) <= K ) : NEW_LINE INDENT right = right + 1 NEW_LINE tmp = tmp + 1 NEW_LINE DEDENT if ( min > tmp ) : NEW_LINE INDENT min = tmp NEW_LINE DEDENT if ( max < tmp ) : NEW_LINE INDENT max = tmp NEW_LINE DEDENT DEDENT print ( min , end = ' , β ' ) NEW_LINE print ( max , end = ' ' ) NEW_LINE DEDENT arr = [ 1 , 2 , 5 , 6 , 7 ] NEW_LINE K = 2 NEW_LINE n = len ( arr ) NEW_LINE findMaxMinSubArray ( arr , K , n ) NEW_LINE |
Count of elements which is the sum of a subarray of the given Array | Function to count element such that their exist a subarray whose sum is equal to this element ; Loop to compute frequency of the given elements ; Loop to iterate over every possible subarray of array ; Driver Code | def countElement ( arr , n ) : NEW_LINE INDENT freq = { } NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] = freq . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT tmpsum = arr [ i ] NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT tmpsum += arr [ j ] NEW_LINE if tmpsum in freq : NEW_LINE INDENT ans += freq [ tmpsum ] NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countElement ( arr , n ) ) NEW_LINE DEDENT |
Nth root of a number using log | Python3 implementation to find the Kth root of a number using log ; Function to find the Kth root of the number using log function ; Driver Code | import numpy as np NEW_LINE def kthRoot ( n , k ) : NEW_LINE INDENT return pow ( k , ( ( 1.0 / k ) * ( np . log ( n ) / np . log ( k ) ) ) ) NEW_LINE DEDENT n = 81 NEW_LINE k = 4 NEW_LINE print ( " % .6f " % kthRoot ( n , k ) ) NEW_LINE |
Make A , B and C equal by adding total value N to them | Python3 Program to Distribute integer N among A , B , C such that they become equal ; find maximum among the three elements ; summation of three elements ; check if difference is divisible by 3 ; Driver code | def distributeN ( A , B , C , n ) : NEW_LINE INDENT maximum = max ( A , B , C ) NEW_LINE sum = A + B + C NEW_LINE p = ( 3 * maximum ) - sum NEW_LINE diff = n - p NEW_LINE if diff < 0 or diff % 3 : NEW_LINE INDENT print " No " NEW_LINE DEDENT else : NEW_LINE INDENT print " Yes " NEW_LINE DEDENT DEDENT A = 10 NEW_LINE B = 20 NEW_LINE C = 15 NEW_LINE n = 14 NEW_LINE distributeN ( A , B , C , n ) NEW_LINE |
Represent N as sum of K odd numbers with repetitions allowed | Function to print the representation ; N must be greater than equal to 2 * K and must be odd ; Driver Code | def sumOddNumbers ( N , K ) : NEW_LINE INDENT check = N - ( K - 1 ) NEW_LINE if ( check > 0 and check % 2 == 1 ) : NEW_LINE INDENT for i in range ( 0 , K - 1 ) : NEW_LINE INDENT print ( "1" , end = " β " ) NEW_LINE DEDENT print ( check , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE K = 3 ; NEW_LINE sumOddNumbers ( N , K ) NEW_LINE |
Number of continuous reductions of A from B or B from A to make them ( 1 , 1 ) | Function to find the minimum number of steps required ; Condition to check if it is not possible to reach ; Condition to check if the pair is reached to 1 , 1 ; Condition to change the A as the maximum element ; Driver Code | def minimumSteps ( a , b , c ) : NEW_LINE INDENT if a < 1 or b < 1 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if a == 1 and b == 1 : NEW_LINE INDENT return c NEW_LINE DEDENT if a < b : NEW_LINE INDENT a , b = b , a NEW_LINE DEDENT return minimumSteps ( a - b , b , c + 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 75 ; b = 17 NEW_LINE print ( minimumSteps ( a , b , 0 ) ) NEW_LINE DEDENT |
Longest Mountain Subarray | Function to find the longest mountain subarray ; If the size of the array is less than 3 , the array won 't show mountain like behaviour ; When a new mountain sub - array is found , there is a need to set the variables k , j to - 1 in order to help calculate the length of new mountain sub - array ; j marks the starting index of a new mountain sub - array . So set the value of j to current index i . ; Checks if next element is less than current element ; Checks if starting element exists or not , if the starting element of the mountain sub - array exists then the index of ending element is stored in k ; This condition checks if both starting index and ending index exists or not , if yes , the length is calculated . ; d holds the length of the longest mountain sub - array . If the current length is greater than the calculated length , then value of d is updated . ; Ignore if there is no increase or decrease in the value of the next element ; Checks and calculates the length if last element of the array is the last element of a mountain sub - array ; Driver code | def LongestMountain ( a ) : NEW_LINE INDENT i = 0 NEW_LINE j = - 1 NEW_LINE k = - 1 NEW_LINE p = 0 NEW_LINE d = 0 NEW_LINE n = 0 NEW_LINE if ( len ( a ) < 3 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( len ( a ) - 1 ) : NEW_LINE INDENT if ( a [ i + 1 ] > a [ i ] ) : NEW_LINE INDENT if ( k != - 1 ) : NEW_LINE INDENT k = - 1 NEW_LINE j = - 1 NEW_LINE DEDENT if ( j == - 1 ) : NEW_LINE INDENT j = i NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( a [ i + 1 ] < a [ i ] ) : NEW_LINE INDENT if ( j != - 1 ) : NEW_LINE INDENT k = i + 1 NEW_LINE DEDENT if ( k != - 1 and j != - 1 ) : NEW_LINE INDENT if ( d < k - j + 1 ) : NEW_LINE INDENT d = k - j + 1 NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT k = - 1 NEW_LINE j = - 1 NEW_LINE DEDENT DEDENT DEDENT if ( k != - 1 and j != - 1 ) : NEW_LINE INDENT if ( d < k - j + 1 ) : NEW_LINE INDENT d = k - j + 1 NEW_LINE DEDENT DEDENT return d NEW_LINE DEDENT d = [ 1 , 3 , 1 , 4 , 5 , 6 , 7 , 8 , 9 , 8 , 7 , 6 , 5 ] NEW_LINE print ( LongestMountain ( d ) ) NEW_LINE |
Check whether an Array can be made 0 by splitting and merging repeatedly | Function that finds if it is possible to make the array contain only 1 element i . e . 0 ; Check if element is odd ; According to the logic in above approach ; Driver code | def solve ( A ) : NEW_LINE INDENT ctr = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if A [ i ] % 2 == 1 : NEW_LINE INDENT ctr += 1 NEW_LINE DEDENT DEDENT if ctr % 2 == 1 : NEW_LINE INDENT return ' No ' NEW_LINE DEDENT else : NEW_LINE INDENT return ' Yes ' NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 17 ] NEW_LINE print ( solve ( arr ) ) NEW_LINE DEDENT |
Count of perfect squares of given length | Python3 Program to count perfect squares of given length ; Function to check if a number is perfect square ; Find floating point value of square root of x . ; If square root is an integer ; Function to return the count of n digit perfect squares ; Initialize result ; Traverse through all numbers of n digits ; Check if current number ' i ' is perfect square ; Driver code | import math ; NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sr = math . sqrt ( x ) ; NEW_LINE return ( ( sr - math . floor ( sr ) ) == 0 ) ; NEW_LINE DEDENT def countSquares ( n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( int ( math . pow ( 10 , ( n - 1 ) ) ) , int ( math . pow ( 10 , n ) ) ) : NEW_LINE INDENT if ( i != 0 and isPerfectSquare ( i ) ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT return cnt ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( countSquares ( n ) ) ; NEW_LINE |
Count of perfect squares of given length | Python3 program to count perfect squares of given length ; Function to return the count of n digit perfect squares ; Driver code | import math NEW_LINE def countSquares ( n ) : NEW_LINE INDENT r = math . ceil ( math . sqrt ( math . pow ( 10 , n ) ) ) ; NEW_LINE l = math . ceil ( math . sqrt ( math . pow ( 10 , n - 1 ) ) ) ; NEW_LINE return r - l ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( countSquares ( n ) ) ; NEW_LINE |
Subsets and Splits