text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Sum of alternating sign cubes of first N Natural numbers | Function to compute sum of the cubes with alternating sign ; Driver Code | def summation ( N ) : NEW_LINE INDENT co = ( N + 1 ) / 2 NEW_LINE co = int ( co ) NEW_LINE ce = N / 2 NEW_LINE ce = int ( ce ) NEW_LINE se = 2 * ( ( ce * ( ce + 1 ) ) * ( ce * ( ce + 1 ) ) ) NEW_LINE so = ( co * co ) * ( 2 * ( co * co ) - 1 ) NEW_LINE return so - se NEW_LINE DEDENT n = 3 NEW_LINE print ( summation ( n ) ) NEW_LINE |
Program to check if N is a Star Number | Python3 implementation to check that a number is a star number or not ; Function to check that the number is a star number ; Condition to check if the number is a star number ; Driver Code ; Function call | import math NEW_LINE def isStar ( N ) : NEW_LINE INDENT n = ( math . sqrt ( 24 * N + 12 ) + 6 ) / 6 NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT i = 13 NEW_LINE if isStar ( i ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Smallest number to make Array sum at most K by dividing each element | Python3 program to find the smallest number such that the sum of the array becomes less than or equal to K when every element of the array is divided by that number ; Function to find the smallest number such that the sum of the array becomes less than or equal to K when every element of the array is divided by that number ; Binary search between 1 and 10 ^ 9 ; Calculating the new sum after dividing every element by mid ; If after dividing by mid , if the new sum is less than or equal to limit move low to mid + 1 ; Else , move mid + 1 to high ; Returning the minimum number ; Driver code | from math import ceil NEW_LINE def findMinDivisor ( arr , n , limit ) : NEW_LINE INDENT low = 0 NEW_LINE high = 10 ** 9 NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ceil ( arr [ i ] / mid ) NEW_LINE DEDENT if ( sum <= limit ) : NEW_LINE INDENT high = mid NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE K = 6 NEW_LINE print ( findMinDivisor ( arr , N , K ) ) NEW_LINE DEDENT |
Count of triplets ( a , b , c ) in the Array such that a divides b and b divides c | Function to count triplets ; Iterate for middle element ; Iterate left array for a [ i ] ; Iterate right array for a [ k ] ; Return the final result ; Driver code | def getCount ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( 1 , n - 1 ) : NEW_LINE INDENT p , q = 0 , 0 NEW_LINE for i in range ( j ) : NEW_LINE INDENT if ( arr [ j ] % arr [ i ] == 0 ) : NEW_LINE INDENT p += 1 NEW_LINE DEDENT DEDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( arr [ k ] % arr [ j ] == 0 ) : NEW_LINE INDENT q += 1 NEW_LINE DEDENT DEDENT count += p * q NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( getCount ( arr , N ) ) NEW_LINE DEDENT |
Find pair with maximum ratio in an Array | Function to find the maximum pair possible for the array ; Loop to iterate over every possible pair in the array ; Check pair ( x , y ) as well as ( y , x ) for maximum value ; Update the answer ; Driver Code | def computeMaxValue ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT val = max ( arr [ i ] / arr [ j ] , arr [ j ] / arr [ i ] ) NEW_LINE ans = max ( ans , val ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 15 , 10 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( computeMaxValue ( arr , n ) ) NEW_LINE DEDENT |
Find the Kth number which is not divisible by N | Python3 implementation to find the K 'th non-divisible number of N ; Function to find the Kth not divisible by N ; Driver Code ; Function Call | import math NEW_LINE def kthNonDivisible ( N , K ) : NEW_LINE INDENT return K + math . floor ( ( K - 1 ) / ( N - 1 ) ) NEW_LINE DEDENT N = 3 NEW_LINE K = 6 NEW_LINE print ( kthNonDivisible ( N , K ) ) NEW_LINE |
Find the maximum sum pair in an Array with even parity | Python3 implementation to find a pair with even parity and maximum sum ; Function that returns true if count of set bits in given number is even ; Parity will store the count of set bits ; Function to print the elements of the array ; Function to remove all the even parity elements from the given array ; Traverse the array ; If the current element has even parity ; Driver Code ; Function call | import sys NEW_LINE sz = 1e3 NEW_LINE def isEvenParity ( x ) : NEW_LINE INDENT parity = 0 NEW_LINE while x != 0 : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT parity = parity + 1 ; NEW_LINE DEDENT x = x >> 1 NEW_LINE DEDENT if ( parity % 2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = ' β ' ) NEW_LINE DEDENT DEDENT def findPairEvenParity ( arr , n ) : NEW_LINE INDENT firstMaximum = - 1 NEW_LINE secondMaximum = - 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if isEvenParity ( arr [ i ] ) == True : NEW_LINE INDENT if ( arr [ i ] >= firstMaximum ) : NEW_LINE INDENT secondMaximum = firstMaximum NEW_LINE firstMaximum = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] >= secondMaximum ) : NEW_LINE INDENT secondMaximum = arr [ i ] NEW_LINE DEDENT DEDENT DEDENT print ( firstMaximum , secondMaximum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 18 , 15 , 8 , 9 , 14 ] NEW_LINE n = len ( arr ) NEW_LINE findPairEvenParity ( arr , n ) NEW_LINE DEDENT |
Program to check if N is a Hexagonal Number or not | Python3 program to check if N is a hexagonal number ; Function to check if number is hexagonal ; Calculate the value for n ; Check if n - floor ( n ) is equal to 0 ; Driver code | from math import sqrt NEW_LINE def isHexagonal ( N ) : NEW_LINE INDENT val = 8 * N + 1 NEW_LINE x = 1 + sqrt ( val ) NEW_LINE n = x / 4 NEW_LINE if ( ( n - int ( n ) ) == 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 = 14 NEW_LINE if ( isHexagonal ( N ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Program to convert Number in characters | Python3 program to convert number in characters ; To calculate the reverse of the number ; The remainder will give the last digit of the number ; Extract the first digit of the reversed number ; Match it with switch case ; Divide the number by 10 to get the next number ; Driver code | def NumbertoCharacter ( n ) : NEW_LINE INDENT rev = 0 ; r = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT r = n % 10 ; NEW_LINE rev = rev * 10 + r ; NEW_LINE n = n // 10 ; NEW_LINE DEDENT while ( rev > 0 ) : NEW_LINE INDENT r = rev % 10 ; NEW_LINE switcher = { 0 : " zero β " , 1 : " one β " , 2 : " two β " , 3 : " three β " , 4 : " four β " , 5 : " five β " , 6 : " six β " , 7 : " seven β " , 8 : " eight β " , 9 : " nine β " } NEW_LINE print ( switcher . get ( r , " UnValid " ) , end = " β " ) ; NEW_LINE rev = rev // 10 ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12345 ; NEW_LINE NumbertoCharacter ( n ) ; NEW_LINE DEDENT |
Count all subarrays whose sum can be split as difference of squares of two Integers | Function to count all the non - contiguous subarrays whose sum can be split as the difference of the squares ; Loop to iterate over all the possible subsequences of the array ; Finding the sum of all the possible subsequences ; Condition to check whether the number can be split as difference of squares ; Driver code | def Solve ( arr , n ) : NEW_LINE INDENT temp = 0 ; count = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT temp = 0 ; NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT temp = temp + arr [ j ] ; NEW_LINE if ( ( temp + 2 ) % 4 != 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( Solve ( arr , N ) ) ; NEW_LINE |
Find product of all elements at indexes which are factors of M for all possible sorted subsequences of length M | Python3 program to find the product of all the combinations of M elements from an array whose index in the sorted order divides M completely ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; If y is odd , multiply x with result ; y must be even now ; Iterative Function to calculate ( nCr ) % p and save in f [ n ] [ r ] C ( n , r ) % p = [ C ( n - 1 , r - 1 ) % p + C ( n - 1 , r ) % p ] % p and C ( n , 0 ) = C ( n , n ) = 1 ; If j > i then C ( i , j ) = 0 ; If i is equal to j then C ( i , j ) = 1 ; C ( i , j ) = ( C ( i - 1 , j ) + C ( i - 1 , j - 1 ) ) % p ; Initialize the answer ; For every element arr [ i ] , x is count of occurrence of arr [ i ] in different set such that index of arr [ i ] in those sets divides m completely . ; Finding the count of arr [ i ] by placing it at the index which divides m completely ; Using fermat 's little theorem ; Multiplying with the count ; Driver code | m = 4 NEW_LINE 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 y = y >> 1 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def nCr ( n , p , f ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m + 1 ) : NEW_LINE INDENT if ( j > i ) : NEW_LINE INDENT f [ i ] [ j ] = 0 NEW_LINE DEDENT elif ( j == 0 or j == i ) : NEW_LINE INDENT f [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT f [ i ] [ j ] = ( ( f [ i - 1 ] [ j ] + f [ i - 1 ] [ j - 1 ] ) % p ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def operations ( arr , n , f ) : NEW_LINE INDENT p = 1000000007 NEW_LINE nCr ( n , p - 1 , f ) NEW_LINE arr . sort ( ) NEW_LINE ans = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = 0 NEW_LINE for j in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( m % j == 0 ) : NEW_LINE INDENT x = ( ( x + ( f [ n - i - 1 ] [ m - j ] * f [ i ] [ j - 1 ] ) % ( p - 1 ) ) % ( p - 1 ) ) NEW_LINE DEDENT DEDENT ans = ( ( ans * power ( arr [ i ] , x , p ) ) % p ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 5 , 7 , 9 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE f = [ [ 0 for x in range ( m + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE operations ( arr , n , f ) NEW_LINE DEDENT |
Check whether a number can be represented by the product of two squares | Function to check if there exist two numbers product of whose squares is n . ; Check whether the product of the square of both numbers is equal to N ; Driver code | def prodSquare ( n ) : NEW_LINE INDENT for i in range ( 2 , ( n ) + 1 ) : NEW_LINE INDENT if ( i * i < ( n + 1 ) ) : NEW_LINE INDENT for j in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( ( i * i * j * j ) == n ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return False ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 25 ; NEW_LINE if ( prodSquare ( n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Check whether a number can be represented by the product of two squares | Function to check if there exist two numbers product of whose squares is n ; Initialize dict / map ; Store square value in hashmap ; Driver Code | def prodSquare ( n ) : NEW_LINE INDENT s = dict ( ) NEW_LINE i = 2 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT s [ i * i ] = 1 NEW_LINE if ( ( n // ( i * i ) ) in s ) : NEW_LINE INDENT return True NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 25 NEW_LINE if ( prodSquare ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Print N distinct numbers following the given operations | Function to print the required array ; Check if number is a multiple of 4 ; Printing Left Half of the array ; Printing Right Half of the array ; Driver code | def printArr ( n ) : NEW_LINE INDENT if ( n % 4 == 0 ) : NEW_LINE INDENT for i in range ( 1 , ( n / 2 ) + 1 ) : NEW_LINE INDENT print ( i * 2 , end = " β " ) NEW_LINE DEDENT for i in range ( 1 , n / 2 ) : NEW_LINE INDENT print ( i * 2 - 1 , end = " β " ) NEW_LINE DEDENT print ( n + n / 2 - 1 , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT n = 22 NEW_LINE printArr ( n ) NEW_LINE |
Sum of product of all subsets formed by only divisors of N | Function to find the sum of product of all the subsets formed by only divisors of N ; Vector to store all the divisors of n ; Loop to find out the divisors of N ; Both ' i ' and ' n / i ' are the divisors of n ; Check if ' i ' and ' n / i ' are equal or not ; Calculating the answer ; Excluding the value of the empty set ; Driver Code | def GetSum ( n ) : NEW_LINE INDENT divisors = [ ] NEW_LINE i = 1 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT divisors . append ( i ) NEW_LINE if ( i != n // i ) : NEW_LINE INDENT divisors . append ( n // i ) NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT ans = 1 NEW_LINE for i in divisors : NEW_LINE INDENT ans *= ( i + 1 ) NEW_LINE DEDENT ans = ans - 1 NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE print ( GetSum ( N ) ) NEW_LINE DEDENT |
Length of longest Powerful number subsequence in an Array | Python3 program to find the length of Longest Powerful Subsequence in an Array ; Function to check if the number is powerful ; First divide the number repeatedly by 2 ; Check if only 2 ^ 1 divides n , then return false ; Check if n is not a power of 2 then this loop will execute repeat above process ; Find highest power of " factor " that divides n ; If only factor ^ 1 divides n , then return false ; n must be 1 now if it is not a prime number . Since prime numbers are not powerful , we return false if n is not 1. ; Function to find the longest subsequence which contain all powerful numbers ; Driver code | import math NEW_LINE def isPowerful ( n ) : NEW_LINE INDENT while ( n % 2 == 0 ) : NEW_LINE INDENT power = 0 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n //= 2 NEW_LINE power += 1 NEW_LINE DEDENT if ( power == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for factor in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT power = 0 NEW_LINE while ( n % factor == 0 ) : NEW_LINE INDENT n = n // factor NEW_LINE power += 1 NEW_LINE DEDENT if ( power == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return ( n == 1 ) NEW_LINE DEDENT def longestPowerfulSubsequence ( arr , n ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( isPowerful ( arr [ i ] ) ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT arr = [ 6 , 4 , 10 , 13 , 9 , 25 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestPowerfulSubsequence ( arr , n ) ) NEW_LINE |
Maximum OR value of a pair in an Array without using OR operator | Python3 implementation of the approach ; Function to return the maximum bitwise OR for any pair of the given array without using bitwise OR operation ; Find maximum element in the array ; Finding complement will set all unset bits in a number ; Iterate through all other array elements to find maximum AND value ; c will give the maximum value that could be added to max_value to produce maximum OR value ; Driver code | from math import log2 , floor NEW_LINE def maxOR ( arr , n ) : NEW_LINE INDENT max_value = max ( arr ) NEW_LINE number_of_bits = floor ( log2 ( max_value ) ) + 1 NEW_LINE complement = ( ( ( 1 << number_of_bits ) - 1 ) ^ max_value ) NEW_LINE c = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != max_value ) : NEW_LINE INDENT c = max ( c , ( complement & arr [ i ] ) ) NEW_LINE DEDENT DEDENT return ( max_value + c ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 8 , 16 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxOR ( arr , n ) ) NEW_LINE DEDENT |
Find the XOR of the elements in the given range [ L , R ] with the value K for a given set of queries | Function to perform the update operation on the given array ; Converting the indices to 0 indexing . ; Saving the XOR of K from the starting index in the range [ L , R ] . ; Saving the XOR of K at the ending index in the given [ L , R ] . ; Function to display the resulting array ; Finding the resultant value in the result array ; Combining the effects of the updates with the original array without changing the initial array . ; Driver code ; Query 1 ; Query 2 ; Query 3 | def update ( res , L , R , K ) : NEW_LINE INDENT L = L - 1 NEW_LINE R = R - 1 NEW_LINE res [ L ] = res [ L ] ^ K NEW_LINE res [ R + 1 ] = res [ R + 1 ] ^ K NEW_LINE DEDENT def display ( arr , res , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT res [ i ] = res [ i ] ^ res [ i - 1 ] NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] ^ res [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 2 , 4 , 6 , 8 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE res = [ 0 ] * N NEW_LINE L = 1 NEW_LINE R = 3 NEW_LINE K = 2 NEW_LINE update ( res , L , R , K ) NEW_LINE L = 2 NEW_LINE R = 4 NEW_LINE K = 3 NEW_LINE update ( res , L , R , K ) NEW_LINE display ( arr , res , N ) NEW_LINE |
Shortest subarray to be removed to make all Array elements unique | Python3 program to make array elements pairwise distinct by removing at most one subarray of minimum length ; Function to check if elements of Prefix and suffix of each sub array of size K are pairwise distinct or not ; Hash map to store frequencies of elements of prefix and suffix ; Variable to store number of occurrences of an element other than one ; Adding frequency of elements of suffix to hash for subarray starting from first index There is no prefix for this sub array ; Counting extra elements in current Hash map ; If there are no extra elements return true ; Check for remaining sub arrays ; First element of suffix is now part of subarray which is being removed so , check for extra elements ; Decrement frequency of first element of the suffix ; Increment frequency of last element of the prefix ; Check for extra elements ; If there are no extra elements return true ; Function for calculating minimum length of the subarray , which on removing make all elements pairwise distinct ; Possible range of length of subarray ; Binary search to find minimum ans ; Driver code | from collections import defaultdict NEW_LINE def check ( a , n , k ) : NEW_LINE INDENT m = defaultdict ( int ) NEW_LINE extra = 0 NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT m [ a [ i ] ] += 1 NEW_LINE DEDENT for x in m : NEW_LINE INDENT extra += m [ x ] - 1 NEW_LINE DEDENT if ( extra == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 1 , i + k - 1 < n ) : NEW_LINE INDENT if ( m [ a [ i + k - 1 ] ] > 1 ) : NEW_LINE INDENT extra -= 1 NEW_LINE DEDENT m [ a [ i + k - 1 ] ] -= 1 NEW_LINE m [ a [ i - 1 ] ] += 1 NEW_LINE if ( m [ a [ i - 1 ] ] > 1 ) : NEW_LINE INDENT extra += 1 NEW_LINE DEDENT if ( extra == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def minlength ( a , n ) : NEW_LINE INDENT lo = 0 NEW_LINE hi = n + 1 NEW_LINE ans = 0 NEW_LINE while ( lo < hi ) : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE if ( check ( a , n , mid ) ) : NEW_LINE INDENT ans = mid NEW_LINE hi = mid NEW_LINE DEDENT else : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 1 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( minlength ( a , n ) ) NEW_LINE DEDENT |
Find N distinct integers with zero sum | Function to print distinct n numbers such that their sum is 0 ; Print 2 symmetric numbers ; Print a extra 0 if N is odd ; Driver code | def findNumbers ( N ) : NEW_LINE INDENT for i in range ( 1 , N // 2 + 1 ) : NEW_LINE INDENT print ( i , end = ' , β ' ) NEW_LINE print ( - i , end = ' , β ' ) NEW_LINE DEDENT if N % 2 == 1 : NEW_LINE INDENT print ( 0 , end = ' ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE findNumbers ( N ) NEW_LINE DEDENT |
Program to calculate Electricity Bill | Function to calculate the electricity bill ; Condition to find the charges bar in which the units consumed is fall ; Driver Code | def calculateBill ( units ) : NEW_LINE INDENT if ( units <= 100 ) : NEW_LINE INDENT return units * 10 ; NEW_LINE DEDENT elif ( units <= 200 ) : NEW_LINE INDENT return ( ( 100 * 10 ) + ( units - 100 ) * 15 ) ; NEW_LINE DEDENT elif ( units <= 300 ) : NEW_LINE INDENT return ( ( 100 * 10 ) + ( 100 * 15 ) + ( units - 200 ) * 20 ) ; NEW_LINE DEDENT elif ( units > 300 ) : NEW_LINE INDENT return ( ( 100 * 10 ) + ( 100 * 15 ) + ( 100 * 20 ) + ( units - 300 ) * 25 ) ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT units = 250 ; NEW_LINE print ( calculateBill ( units ) ) ; NEW_LINE |
Find all divisors of first N natural numbers | Function to find the factors of the numbers from 1 to N ; Loop to find the factors of the first N natural numbers of the integer ; Driver Code | def factors ( n ) : NEW_LINE INDENT print ( "1 β - - > 1" ) ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT print ( i , " β - - > " , end = " " ) ; NEW_LINE for j in range ( 1 , int ( pow ( i , 1 ) ) ) : NEW_LINE INDENT if ( i % j == 0 ) : NEW_LINE INDENT print ( j , " , β " , end = " " ) ; NEW_LINE if ( i // j != j ) : NEW_LINE INDENT print ( i // j , " , β " , end = " " ) ; NEW_LINE DEDENT DEDENT DEDENT print ( end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; NEW_LINE factors ( n ) ; NEW_LINE DEDENT |
Find all divisors of first N natural numbers | Python3 program to find the factors of first N natural numbers ; Initialize divisor list ( array ) of sequence container ; Calculate all divisors of a number ; Function to find the factors of first n natural numbers ; Driver code ; Function call | MAX = 100001 NEW_LINE divisor = [ [ ] for x in range ( MAX ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT for i in range ( 1 , MAX ) : NEW_LINE INDENT for j in range ( i , MAX , i ) : NEW_LINE INDENT divisor [ j ] . append ( i ) NEW_LINE DEDENT DEDENT DEDENT def findNFactors ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( i , " β - - > β " , end = ' ' ) NEW_LINE for divi in divisor [ i ] : NEW_LINE INDENT print ( divi , " , β " , end = ' ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE sieve ( ) NEW_LINE findNFactors ( n ) NEW_LINE DEDENT |
Maximum number of prime factors a number can have with exactly x factors | Python3 implementation to find the maximum count of the prime factors by the count of factors of number ; Function to count number of prime factors of x ; Count variable is incremented form every prime factor of x ; Loop to count the number of the prime factors of the given number ; Driver Code | import math NEW_LINE def countPrimeFactors ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT cnt = 0 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE n = n // 2 NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE n = n // i NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT return cnt NEW_LINE DEDENT x = 8 NEW_LINE prime_factor_cnt = countPrimeFactors ( x ) NEW_LINE print ( prime_factor_cnt ) NEW_LINE |
Count of N digit palindromic numbers divisible by 9 | Function to find the count of N digits palindromic numbers which are divisible by 9 ; If N is odd ; If N is even ; Driver Code | def countPalindromic ( n ) : NEW_LINE INDENT count = 0 NEW_LINE if ( n % 2 == 1 ) : NEW_LINE INDENT count = pow ( 9 , ( n - 1 ) // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT count = pow ( 9 , ( n - 2 ) // 2 ) NEW_LINE DEDENT return count NEW_LINE DEDENT n = 3 NEW_LINE print ( countPalindromic ( n ) ) NEW_LINE |
Count of sub | Function that returns the count of sub - arrays with odd product ; Initialize the count variable ; Initialize variable to store the last index with even number ; Initialize variable to store count of continuous odd numbers ; Loop through the array ; Check if the number is even or not ; Calculate count of continuous odd numbers ; Increase the count of sub - arrays with odd product ; Store the index of last even number ; N considered as index of even number ; Driver Code ; Function call | def countSubArrayWithOddProduct ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE last = - 1 NEW_LINE K = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] % 2 == 0 ) : NEW_LINE INDENT K = ( i - last - 1 ) NEW_LINE count += ( K * ( K + 1 ) / 2 ) NEW_LINE last = i NEW_LINE DEDENT DEDENT K = ( N - last - 1 ) NEW_LINE count += ( K * ( K + 1 ) / 2 ) NEW_LINE return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 15 , 7 , 3 , 25 , 6 , 2 , 1 , 1 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( int ( countSubArrayWithOddProduct ( arr , n ) ) ) NEW_LINE DEDENT |
Calculate the CGPA and CGPA % of marks obtained by a Student in N subjects | Python3 program to calculate the CGPA and CGPA percentage of a student ; Variable to store the grades in every subject ; Variables to store CGPA and the sum of all the grades ; Computing the grades ; Computing the sum of grades ; Computing the CGPA ; Driver code | def CgpaCalc ( marks , n ) : NEW_LINE INDENT grade = [ 0 ] * n NEW_LINE Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE grade [ i ] = ( marks [ i ] / 10 ) NEW_LINE for i in range ( n ) : NEW_LINE Sum += grade [ i ] NEW_LINE cgpa = Sum / n NEW_LINE return cgpa NEW_LINE DEDENT n = 5 NEW_LINE marks = [ 90 , 80 , 70 , 80 , 90 ] NEW_LINE cgpa = CgpaCalc ( marks , n ) NEW_LINE print ( " CGPA β = β " , ' % .1f ' % cgpa ) NEW_LINE print ( " CGPA β Percentage β = β " , ' % .2f ' % ( cgpa * 9.5 ) ) NEW_LINE |
Find the subarray of size K with minimum XOR | Function to find the minimum XOR of the subarray of size K ; K must be smaller than or equal to n ; Initialize beginning index of result ; Compute XOR sum of first subarray of size K ; Initialize minimum XOR sum as current xor ; Traverse from ( k + 1 ) ' th β β element β to β n ' th element ; XOR with current item and first item of previous subarray ; Update result if needed ; Driver Code ; Subarray size ; Function Call | def findMinXORSubarray ( arr , n , k ) : NEW_LINE INDENT if ( n < k ) : NEW_LINE INDENT return NEW_LINE DEDENT res_index = 0 NEW_LINE curr_xor = 0 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT curr_xor = curr_xor ^ arr [ i ] NEW_LINE DEDENT min_xor = curr_xor NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT curr_xor ^= ( arr [ i ] ^ arr [ i - k ] ) NEW_LINE if ( curr_xor < min_xor ) : NEW_LINE INDENT min_xor = curr_xor NEW_LINE res_index = ( i - k + 1 ) NEW_LINE DEDENT DEDENT print ( min_xor , end = ' ' ) NEW_LINE DEDENT arr = [ 3 , 7 , 90 , 20 , 10 , 50 , 40 ] NEW_LINE k = 3 NEW_LINE n = len ( arr ) NEW_LINE findMinXORSubarray ( arr , n , k ) NEW_LINE |
Greatest number that can be formed from a pair in a given Array | Python3 implementation to find the greatest number from the given pairs of the array ; Function to find the greatest number formed from the pairs ; first append Y at the end of X ; then append X at the end of Y ; Now see which of the two formed numbers is greater than other ; Function to find pairs from array ; Iterate through all pairs ; Driver code | import sys ; NEW_LINE def getNumber ( a , b ) : NEW_LINE INDENT X = str ( a ) ; NEW_LINE Y = str ( b ) ; NEW_LINE XY = X + Y ; NEW_LINE YX = Y + X ; NEW_LINE if ( XY > YX ) : NEW_LINE INDENT return XY ; NEW_LINE DEDENT else : NEW_LINE INDENT return YX ; NEW_LINE DEDENT DEDENT def printMaxPair ( arr , n ) : NEW_LINE INDENT largest = - sys . maxsize - 1 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT number = int ( getNumber ( arr [ i ] , arr [ j ] ) ) ; NEW_LINE largest = max ( largest , number ) ; NEW_LINE DEDENT DEDENT print ( largest ) ; NEW_LINE DEDENT a = [ 23 , 14 , 16 , 25 , 3 , 9 ] ; NEW_LINE n = len ( a ) ; NEW_LINE printMaxPair ( a , n ) ; NEW_LINE |
Check whether two numbers are in golden ratio | Function to check that two numbers are in golden 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 golden ratio ; Driver Code ; Function Call | def checkGoldenRatio ( a , b ) : NEW_LINE INDENT a , b = max ( a , b ) , min ( a , b ) NEW_LINE ratio1 = round ( a / b , 3 ) NEW_LINE ratio2 = round ( ( a + b ) / a , 3 ) NEW_LINE if ratio1 == ratio2 and ratio1 == 1.618 : 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 = 0.618 NEW_LINE b = 1 NEW_LINE checkGoldenRatio ( a , b ) NEW_LINE DEDENT |
Find the minimum number to be added to N to make it a power of K | Python3 program to find the minimum number to be added to N to make it a power of K ; Function to return the minimum number to be added to N to make it a power of K . ; Computing the difference between then next greater power of K and N ; Driver code | import math NEW_LINE def minNum ( n , k ) : NEW_LINE INDENT x = int ( ( math . log ( n ) // math . log ( k ) ) ) + 1 NEW_LINE mn = pow ( k , x ) - n NEW_LINE return mn NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 20 NEW_LINE k = 5 NEW_LINE print ( minNum ( n , k ) ) NEW_LINE DEDENT |
Previous perfect square and cube number smaller than number N | Python3 implementation to find the previous perfect square and cube smaller than the given number ; Function to find the previous perfect square of the number N ; If N is already a perfect square decrease prevN by 1. ; Function to find the previous perfect cube ; If N is already a perfect cube decrease prevN by 1. ; Driver Code | import math NEW_LINE import numpy as np NEW_LINE def previousPerfectSquare ( N ) : NEW_LINE INDENT prevN = math . floor ( math . sqrt ( N ) ) ; NEW_LINE if ( prevN * prevN == N ) : NEW_LINE INDENT prevN -= 1 ; NEW_LINE DEDENT return prevN * prevN ; NEW_LINE DEDENT def previousPerfectCube ( N ) : NEW_LINE INDENT prevN = math . floor ( np . cbrt ( N ) ) ; NEW_LINE if ( prevN * prevN * prevN == N ) : NEW_LINE INDENT prevN -= 1 ; NEW_LINE DEDENT return prevN * prevN * prevN ; NEW_LINE DEDENT n = 30 ; NEW_LINE print ( previousPerfectSquare ( n ) ) ; NEW_LINE print ( previousPerfectCube ( n ) ) ; NEW_LINE |
Find the count of even odd pairs in a given Array | Function to count the pairs in array of the form ( even , odd ) ; Variable to store count of such pairs ; Iterate through all pairs ; Increment count if condition is satisfied ; Driver code | def findCount ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( ( arr [ i ] % 2 == 0 ) and ( arr [ j ] % 2 == 1 ) ) : NEW_LINE INDENT res = res + 1 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT a = [ 5 , 4 , 1 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( findCount ( a , n ) ) NEW_LINE |
Find the count of even odd pairs in a given Array | Function to count the pairs in array of the form ( even , odd ) ; Check if number is even or not ; Driver code | def findCount ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans = ans + count NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT a = [ 5 , 4 , 1 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( findCount ( a , n ) ) NEW_LINE |
Product of all non repeating Subarrays of an Array | Function to find the product of all non - repeating Subarrays of an Array ; Finding the occurrence of every element ; Iterating through the array and finding the product ; We are taking the power of each element in array with the occurrence and then taking product of those . ; Driver code | def product ( arr ) : NEW_LINE INDENT occurrence = pow ( 2 , len ( arr ) - 1 ) ; NEW_LINE product = 1 ; NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT product *= pow ( arr [ i ] , occurrence ) ; NEW_LINE DEDENT return product ; NEW_LINE DEDENT arr = [ 10 , 3 , 7 ] ; NEW_LINE print ( product ( arr ) ) ; NEW_LINE |
Sum of all N | Python 3 program for the above approach ; Function to find a ^ b efficiently ; Base Case ; To store the value of a ^ b ; Multiply temp by a until b is not 0 ; Return the final ans a ^ b ; Function to find sum of all N - digit palindromic number divisible by 9 ; Base Case ; If N is even , decrease ways by 1 ; Find the total number of ways ; Iterate over [ 1 , N ] and find the sum at each index ; Print the final Sum ; Driver Code | MOD = 1000000007 NEW_LINE def power ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT temp = power ( a , b // 2 ) NEW_LINE temp = ( temp * temp ) % MOD NEW_LINE if ( b % 2 != 0 ) : NEW_LINE INDENT temp = ( temp * a ) % MOD NEW_LINE DEDENT return temp NEW_LINE DEDENT def palindromicSum ( N ) : NEW_LINE INDENT sum = 0 NEW_LINE if ( N == 1 ) : NEW_LINE INDENT print ( "9" ) NEW_LINE return NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT print ( "99" ) NEW_LINE return NEW_LINE DEDENT ways = N // 2 NEW_LINE if ( N % 2 == 0 ) : NEW_LINE INDENT ways -= 1 NEW_LINE DEDENT res = power ( 9 , ways - 1 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum = sum * 10 + 45 * res NEW_LINE sum %= MOD NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE palindromicSum ( N ) NEW_LINE DEDENT |
Maximize array sum by concatenating corresponding elements of given two arrays | Function to join the two numbers ; Loop to reverse the digits of the one number ; Loop to join two numbers ; Function to find the maximum array sum ; Loop to iterate over the two elements of the array ; Find the array sum ; Return the array sum ; Driver Code | def joinNumbers ( numA , numB ) : NEW_LINE INDENT revB = 0 NEW_LINE while ( numB > 0 ) : NEW_LINE INDENT revB = revB * 10 + ( numB % 10 ) NEW_LINE numB = numB // 10 NEW_LINE DEDENT while ( revB > 0 ) : NEW_LINE INDENT numA = numA * 10 + ( revB % 10 ) NEW_LINE revB = revB // 10 NEW_LINE DEDENT return numA NEW_LINE DEDENT def findMaxSum ( A , B , n ) : NEW_LINE INDENT maxArr = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT X = joinNumbers ( A [ i ] , B [ i ] ) NEW_LINE Y = joinNumbers ( B [ i ] , A [ i ] ) NEW_LINE mx = max ( X , Y ) NEW_LINE maxArr [ i ] = mx NEW_LINE DEDENT maxAns = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxAns += maxArr [ i ] NEW_LINE DEDENT return maxAns NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE A = [ 11 , 23 , 38 , 43 , 59 ] NEW_LINE B = [ 36 , 24 , 17 , 40 , 56 ] NEW_LINE print ( findMaxSum ( A , B , N ) ) NEW_LINE DEDENT |
Split N natural numbers into two sets having GCD of their sums greater than 1 | Function to create and print the two sets ; For n <= 2 such sets can never be formed ; Check if N is even or odd and store the element which divides the sum of N natural numbers accordingly ; First set ; Print elements of second set ; Driver code | def createSets ( n ) : NEW_LINE INDENT if ( n <= 2 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT else : NEW_LINE INDENT x = ( n // 2 ) if ( n % 2 == 0 ) else ( ( n + 1 ) // 2 ) ; NEW_LINE print ( x , " β " ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i == x ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT print ( i , end = " β " ) ; NEW_LINE DEDENT DEDENT return ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 ; NEW_LINE createSets ( N ) ; NEW_LINE DEDENT |
Count the factors of K present in the given Array | Function to find the count of factors of K present in array ; Loop to consider every element of array ; Driver Code ; Function Call | def calcCount ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( k % arr [ i ] == 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 2 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE k = 6 NEW_LINE print ( calcCount ( arr , n , k ) ) NEW_LINE |
Multiply N complex numbers given as strings | Function which returns the in digit format ; a : real b : imaginary ; sa : sign of a sb : sign of b ; Extract the real number ; Extract the imaginary part ; If size == 1 means we reached at result ; Extract the first two elements ; Remove them ; Calculate and store the real part ; Calculate and store the imaginary part ; Append the real part ; Append the imaginary part ; Insert into vector ; Driver code | def findnum ( s1 ) : NEW_LINE INDENT v = [ ] NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE sa = 0 NEW_LINE sb = 0 NEW_LINE i = 0 NEW_LINE if ( s1 [ 0 ] == ' - ' ) : NEW_LINE INDENT sa = 1 NEW_LINE i = 1 NEW_LINE DEDENT while ( s1 [ i ] . isdigit ( ) ) : NEW_LINE INDENT a = a * 10 + ( int ( s1 [ i ] ) ) NEW_LINE i += 1 NEW_LINE DEDENT if ( s1 [ i ] == ' + ' ) : NEW_LINE INDENT sb = 0 NEW_LINE i += 1 NEW_LINE DEDENT if ( s1 [ i ] == ' - ' ) : NEW_LINE INDENT sb = 1 NEW_LINE i += 1 NEW_LINE DEDENT while ( i < len ( s1 ) and s1 [ i ] . isdigit ( ) ) : NEW_LINE INDENT b = b * 10 + ( int ( s1 [ i ] ) ) NEW_LINE i += 1 NEW_LINE DEDENT if ( sa ) : NEW_LINE INDENT a *= - 1 NEW_LINE DEDENT if ( sb ) : NEW_LINE INDENT b *= - 1 NEW_LINE DEDENT v . append ( a ) NEW_LINE v . append ( b ) NEW_LINE return v NEW_LINE DEDENT def complexNumberMultiply ( v ) : NEW_LINE INDENT while ( len ( v ) != 1 ) : NEW_LINE INDENT v1 = findnum ( v [ 0 ] ) NEW_LINE v2 = findnum ( v [ 1 ] ) NEW_LINE del v [ 0 ] NEW_LINE del v [ 0 ] NEW_LINE r = ( v1 [ 0 ] * v2 [ 0 ] - v1 [ 1 ] * v2 [ 1 ] ) NEW_LINE img = v1 [ 0 ] * v2 [ 1 ] + v1 [ 1 ] * v2 [ 0 ] NEW_LINE res = " " NEW_LINE res += str ( r ) NEW_LINE res += ' + ' NEW_LINE res += str ( img ) + ' i ' NEW_LINE v . insert ( 0 , res ) NEW_LINE DEDENT return v [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE v = [ "3 + 1i " , "2 + 1i " , " - 5 + - 7i " ] NEW_LINE print ( complexNumberMultiply ( v ) ) NEW_LINE DEDENT |
Length of largest subarray whose all elements are Perfect Number | Function that returns true if n is perfect ; To store sum of divisors ; Find all divisors and add them ; check if the sum of divisors is equal to n , then n is a perfect number ; Function to return the length of the largest sub - array of an array every element of whose is a perfect number ; check if arr [ i ] is a perfect number ; Driver code | def isPerfect ( n ) : NEW_LINE INDENT sum = 1 NEW_LINE i = 2 NEW_LINE while i * i <= n : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT sum = sum + i + n / i NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return ( True if sum == n and n != 1 else False ) NEW_LINE DEDENT def contiguousPerfectNumber ( arr , n ) : NEW_LINE INDENT current_length = 0 NEW_LINE max_length = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( isPerfect ( arr [ i ] ) ) : NEW_LINE INDENT current_length += 1 NEW_LINE DEDENT else : NEW_LINE INDENT current_length = 0 NEW_LINE DEDENT max_length = max ( max_length , current_length ) NEW_LINE DEDENT return max_length NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 7 , 36 , 4 , 6 , 28 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( contiguousPerfectNumber ( arr , n ) ) NEW_LINE DEDENT |
Length of largest subarray whose all elements Powerful number | Python 3 program to find the length of the largest sub - array of an array every element of whose is a powerful number ; function to check if the number is powerful ; First divide the number repeatedly by 2 ; If only 2 ^ 1 divides n ( not higher powers ) , then return false ; If n is not a power of 2 then this loop will execute repeat above process ; Find highest power of " factor " that divides n ; If only factor ^ 1 divides n ( not higher powers ) , then return false ; n must be 1 now if it is not a prime numenr . Since prime numbers are not powerful , we return false if n is not 1. ; Function to return the length of the largest sub - array of an array every element of whose is a powerful number ; If arr [ i ] is a Powerful number ; Driver code | import math NEW_LINE def isPowerful ( n ) : NEW_LINE INDENT while ( n % 2 == 0 ) : NEW_LINE INDENT power = 0 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = n // 2 NEW_LINE power = power + 1 NEW_LINE DEDENT if ( power == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for factor in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT power = 0 NEW_LINE while ( n % factor == 0 ) : NEW_LINE INDENT n = n // factor NEW_LINE power = power + 1 NEW_LINE DEDENT if ( power == 1 ) : NEW_LINE INDENT return false NEW_LINE DEDENT DEDENT return ( n == 1 ) NEW_LINE DEDENT def contiguousPowerfulNumber ( arr , n ) : NEW_LINE INDENT current_length = 0 NEW_LINE max_length = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( isPowerful ( arr [ i ] ) ) : NEW_LINE INDENT current_length += 1 NEW_LINE DEDENT else : NEW_LINE INDENT current_length = 0 NEW_LINE DEDENT max_length = max ( max_length , current_length ) NEW_LINE DEDENT return max_length NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 7 , 36 , 4 , 6 , 28 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( contiguousPowerfulNumber ( arr , n ) ) NEW_LINE DEDENT |
Maximize sum of K corner elements in Array | Function to return maximum sum ; Base case ; Pick the start index ; Pick the end index ; Recursive function call ; Return the final answer ; Function to find the maximized sum ; Driver code | def maxSum ( arr , K , start , end , max_sum ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return max_sum NEW_LINE DEDENT max_sum_start = max_sum + arr [ start ] NEW_LINE max_sum_end = max_sum + arr [ end ] NEW_LINE ans = max ( maxSum ( arr , K - 1 , start + 1 , end , max_sum_start ) , maxSum ( arr , K - 1 , start , end - 1 , max_sum_end ) ) NEW_LINE return ans NEW_LINE DEDENT def maximizeSum ( arr , K , n ) : NEW_LINE INDENT max_sum = 0 NEW_LINE start = 0 NEW_LINE end = n - 1 NEW_LINE print ( maxSum ( arr , K , start , end , max_sum ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 4 , 4 , 8 , 12 , 3 , 2 , 9 ] NEW_LINE K = 3 NEW_LINE n = len ( arr ) NEW_LINE maximizeSum ( arr , K , n ) NEW_LINE DEDENT |
Maximize sum of K corner elements in Array | Function to return maximum sum ; Initialize variables ; Iterate over first K elements of array and update the value for curr_points ; Update value for max_points ; j points to the end of the array ; Return the final result ; Driver code | def maxPointCount ( arr , K , size ) : NEW_LINE INDENT curr_points = 0 NEW_LINE max_points = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT curr_points += arr [ i ] NEW_LINE DEDENT max_points = curr_points NEW_LINE j = size - 1 NEW_LINE for i in range ( K - 1 , - 1 , - 1 ) : NEW_LINE INDENT curr_points = ( curr_points + arr [ j ] - arr [ i ] ) NEW_LINE max_points = max ( curr_points , max_points ) NEW_LINE j -= 1 NEW_LINE DEDENT return max_points NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 8 , 4 , 4 , 8 , 12 , 3 , 2 , 9 ] NEW_LINE K = 3 NEW_LINE n = len ( arr ) NEW_LINE print ( maxPointCount ( arr , K , n ) ) NEW_LINE DEDENT |
Sum of all N digit palindromic numbers divisible by 9 formed using digits 1 to 9 | Function for finding count of N digits palindrome which are divisible by 9 ; If N is odd ; If N is even ; Function for finding sum of N digits palindrome which are divisible by 9 ; Count the possible number of palindrome ; Driver Code | def countPalindrome ( n ) : NEW_LINE INDENT count = 0 NEW_LINE if ( n % 2 == 1 ) : NEW_LINE INDENT count = pow ( 9 , ( n - 1 ) // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT count = pow ( 9 , ( n - 2 ) // 2 ) NEW_LINE DEDENT return count NEW_LINE DEDENT def sumPalindrome ( n ) : NEW_LINE INDENT count = countPalindrome ( n ) NEW_LINE res = 0 NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 9 NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return 99 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT res = res * 10 + count * 5 NEW_LINE DEDENT return res NEW_LINE DEDENT n = 3 NEW_LINE print ( sumPalindrome ( n ) ) NEW_LINE |
Find the total count of numbers up to N digits in a given base B | Python3 implementation to find the count of natural numbers up to N digits ; Function to return the count of natural numbers upto N digits ; Loop to iterate from 1 to N and calculating number of natural numbers for every ' i ' th digit . ; Driver Code | from math import pow NEW_LINE def count ( N , B ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT sum += ( B - 1 ) * pow ( B , i - 1 ) NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE B = 10 NEW_LINE print ( int ( count ( N , B ) ) ) NEW_LINE DEDENT |
Find smallest perfect square number A such that N + A is also a perfect square number | Python3 code to find out the smallest perfect square X which when added to N yields another perfect square number . ; X is the smallest perfect square number ; Loop from 1 to square root of N ; Condition to check whether i is factor of N or not ; Condition to check whether factors satisfies the equation or not ; Stores minimum value ; Return if X * X if X is not equal to 1e9 else return - 1 ; Driver code | import math NEW_LINE def SmallestPerfectSquare ( N ) : NEW_LINE INDENT X = 1e9 NEW_LINE for i in range ( 1 , int ( math . sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if N % i == 0 : NEW_LINE INDENT a = i NEW_LINE b = N // i NEW_LINE if b - a != 0 and ( b - a ) % 2 == 0 : NEW_LINE INDENT X = min ( X , ( b - a ) // 2 ) NEW_LINE DEDENT DEDENT DEDENT return ( X * X if X != 1e9 else - 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE print ( SmallestPerfectSquare ( N ) ) NEW_LINE DEDENT |
Minimum Cost Path to visit all nodes situated at the Circumference of Circular Road | Function to find the minimum cost ; Sort the given array ; Initialise a new array of double size ; Fill the array elements ; Find the minimum path cost ; Return the final result ; Driver code | def minCost ( arr , n , circumference ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE arr2 = [ 0 ] * ( 2 * n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr2 [ i ] = arr [ i ] NEW_LINE arr2 [ i + n ] = arr [ i ] + circumference NEW_LINE DEDENT res = 9999999999999999999 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT res = min ( res , arr2 [ i + ( n - 1 ) ] - arr2 [ i ] ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT arr = [ 19 , 3 , 6 ] ; NEW_LINE n = len ( arr ) NEW_LINE circumference = 20 ; NEW_LINE print ( minCost ( arr , n , circumference ) ) NEW_LINE |
Unique element in an array where all elements occur K times except one | Set 2 | Function to find single occurrence element ; By shifting 1 to left ith time and taking and with 1 will give us that ith bit of a [ j ] is 1 or 0 ; Taking modulo of p with k ; Generate result ; Loop for negative numbers ; Check if the calculated value res is present in array , then mark c = 1 and if c = 1 return res else res must be - ve ; Driver code ; Function call | def findunique ( a , k ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT p = 0 NEW_LINE for j in range ( len ( a ) ) : NEW_LINE INDENT if ( abs ( a [ j ] ) & ( 1 << i ) ) != 0 : NEW_LINE INDENT p += 1 NEW_LINE DEDENT DEDENT p %= k NEW_LINE res += pow ( 2 , i ) * p NEW_LINE DEDENT c = 0 NEW_LINE for x in a : NEW_LINE INDENT if ( x == res ) : NEW_LINE INDENT c = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if c == 1 : NEW_LINE INDENT return res NEW_LINE DEDENT else : NEW_LINE INDENT return - res NEW_LINE DEDENT DEDENT a = [ 12 , 12 , 2 , 2 , 3 ] NEW_LINE k = 2 NEW_LINE print ( findunique ( a , k ) ) NEW_LINE |
Find minimum GCD of all pairs in an array | Python3 program to find the minimum GCD of any pair in the array ; Function returns the Minimum GCD of any pair ; Finding GCD of all the elements in the array . ; Driver code | from math import gcd NEW_LINE def MinimumGCD ( arr , n ) : NEW_LINE INDENT g = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT g = gcd ( g , arr [ i ] ) NEW_LINE DEDENT return g NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 6 , 8 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( MinimumGCD ( arr , N ) ) NEW_LINE DEDENT |
Minimum steps to reach the Nth stair in jumps of perfect power of 2 | Function to count the number of jumps required to reach Nth stairs . ; Till N becomes 0 ; Removes the set bits from the right to left ; Driver Code ; Number of stairs ; Function Call | def stepRequired ( N ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE while ( N > 0 ) : NEW_LINE INDENT N = N & ( N - 1 ) ; NEW_LINE cnt += 1 ; NEW_LINE DEDENT return cnt ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 23 ; NEW_LINE print ( stepRequired ( N ) ) ; NEW_LINE DEDENT |
Count of total subarrays whose sum is a Fibonacci Numbers | Python3 program for the above approach ; Function to check whether a number is perfect square or not ; Function to check whether a number is fibonacci number or not ; If 5 * n * n + 4 or 5 * n * n - 5 is a perfect square , then the number is Fibonacci ; Function to count the subarray with sum fibonacci number ; Traverse the array arr [ ] to find the sum of each subarray ; To store the sum ; Check whether sum of subarray between [ i , j ] is fibonacci or not ; Driver Code ; Function Call | import math NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT s = int ( math . sqrt ( x ) ) NEW_LINE if s * s == x : NEW_LINE INDENT return True NEW_LINE DEDENT return False 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 fibonacciSubarrays ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT sum += arr [ j ] NEW_LINE if ( isFibonacci ( sum ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT arr = [ 6 , 7 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE fibonacciSubarrays ( arr , n ) NEW_LINE |
Count the number of ways to fill K boxes with N distinct items | Python3 program to calculate the above formula ; To store the factorials of all numbers ; Function to calculate factorial of all numbers ; Calculate x to the power y in O ( log n ) time ; Function to find inverse mod of a number x ; Calculate ( n C r ) ; Loop to compute the formula evaluated ; Add even power terms ; Subtract odd power terms ; Choose the k boxes which were used ; Driver code | mod = 1000000007 NEW_LINE factorial = [ 0 for i in range ( 100005 ) ] NEW_LINE def StoreFactorials ( n ) : NEW_LINE INDENT factorial [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT factorial [ i ] = ( i * factorial [ i - 1 ] ) % mod NEW_LINE DEDENT DEDENT def Power ( x , y ) : NEW_LINE INDENT ans = 1 NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y % 2 == 1 ) : NEW_LINE INDENT ans = ( ans * x ) % mod NEW_LINE DEDENT x = ( x * x ) % mod NEW_LINE y //= 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT def invmod ( x ) : NEW_LINE INDENT return Power ( x , mod - 2 ) NEW_LINE DEDENT def nCr ( n , r ) : NEW_LINE INDENT return ( ( factorial [ n ] * invmod ( ( factorial [ r ] * factorial [ n - r ] ) % mod ) ) % mod ) NEW_LINE DEDENT def CountWays ( n , k ) : NEW_LINE INDENT StoreFactorials ( n ) NEW_LINE ans = 0 NEW_LINE i = k NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( i % 2 == k % 2 ) : NEW_LINE INDENT ans = ( ( ans + ( Power ( i , n ) * nCr ( k , i ) ) % mod ) % mod ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = ( ( ans + mod - ( Power ( i , n ) * nCr ( k , i ) ) % mod ) % mod ) NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT ans = ( ans * nCr ( n , k ) ) % mod NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 5 NEW_LINE print ( CountWays ( N , K ) ) NEW_LINE DEDENT |
Program to print numbers from N to 1 in reverse order | Recursive function to print from N to 1 ; if N is less than 1 then return void function ; recursive call of the function ; Driver Code | def PrintReverseOrder ( N ) : NEW_LINE INDENT if ( N <= 0 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( N , end = " β " ) ; NEW_LINE PrintReverseOrder ( N - 1 ) ; NEW_LINE DEDENT DEDENT N = 5 ; NEW_LINE PrintReverseOrder ( N ) ; NEW_LINE |
Find the XOR of first half and second half elements of an array | Function to find the xor of the first half elements and second half elements of an array ; xor of elements in FirstHalfXOR ; xor of elements in SecondHalfXOR ; Driver Code ; Function call | def XOROfElements ( arr , n ) : NEW_LINE INDENT FirstHalfXOR = 0 ; NEW_LINE SecondHalfXOR = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i < n // 2 ) : NEW_LINE INDENT FirstHalfXOR ^= arr [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT SecondHalfXOR ^= arr [ i ] ; NEW_LINE DEDENT DEDENT print ( FirstHalfXOR , " , " , SecondHalfXOR ) ; NEW_LINE DEDENT arr = [ 20 , 30 , 50 , 10 , 55 , 15 , 42 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE XOROfElements ( arr , N ) ; NEW_LINE |
Minimum volume of cone that can be circumscribed about a sphere of radius R | Python3 program to find the minimum Volume of the cone that can be circumscribed about a sphere of radius R ; Function to find the volume of the cone ; r = radius of cone h = height of cone Volume of cone = ( 1 / 3 ) * ( 3.14 ) * ( r * * 2 ) * ( h ) we get radius of cone from the derivation is root ( 2 ) times multiple of R we get height of cone from the derivation is 4 times multiple of R ; Driver code | import math NEW_LINE def Volume_of_cone ( R ) : NEW_LINE INDENT V = ( 1 / 3 ) * ( 3.14 ) * ( 2 * ( R ** 2 ) ) * ( 4 * R ) NEW_LINE return V NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT R = 10 NEW_LINE print ( Volume_of_cone ( R ) ) NEW_LINE DEDENT |
Program to find Surface Area and Volume of Octagonal Prism | Python3 program to find the Surface area and volume of octagonal prism ; Function to find the Volume of octagonal prism ; Formula to calculate volume = ( area * h ) ; Display volume ; Function to find the surface area of octagonal prism ; Formula to calculate Surface area ; Driver Code | import math NEW_LINE def find_volume ( area , h ) : NEW_LINE INDENT Volume = ( area * h ) NEW_LINE print ( " Volume : β " , end = " β " ) NEW_LINE print ( Volume ) NEW_LINE DEDENT def find_Surface_area ( area , a , h ) : NEW_LINE INDENT Surface_area = ( 2 * area ) + ( 8 * a * h ) NEW_LINE print ( " Surface β area : β " , end = " β " ) NEW_LINE print ( Surface_area ) NEW_LINE DEDENT h = 1 NEW_LINE a = 6 NEW_LINE d = 2 NEW_LINE area = 2 * a * d NEW_LINE find_Surface_area ( area , a , h ) NEW_LINE find_volume ( area , h ) NEW_LINE |
Count of pairs upto N such whose LCM is not equal to their product for Q queries | Python 3 program to find the count of pairs from 1 to N such that their LCM is not equal to their product ; To store Euler 's Totient Function ; To store prefix sum table ; Compute Totients of all numbers smaller than or equal to N ; Make phi [ 1 ] = 0 since 1 cannot form any pair ; Initialise all remaining phi [ ] with i ; Compute remaining phi ; If phi [ p ] is not computed already , then number p is prime ; phi of prime number is p - 1 ; Update phi of all multiples of p ; Add the contribution of p to its multiple i by multiplying it with ( 1 - 1 / p ) ; Function to store prefix sum table ; Prefix Sum of all Euler 's Totient Values ; Total number of pairs that can be formed ; Driver Code ; Function call to compute all phi ; Function call to store all prefix sum | N = 100005 NEW_LINE phi = [ 0 for i in range ( N ) ] NEW_LINE pref = [ 0 for i in range ( N ) ] NEW_LINE def precompute ( ) : NEW_LINE INDENT phi [ 1 ] = 0 NEW_LINE for i in range ( 2 , N , 1 ) : NEW_LINE INDENT phi [ i ] = i NEW_LINE DEDENT for p in range ( 2 , N ) : NEW_LINE INDENT if ( phi [ p ] == p ) : NEW_LINE INDENT phi [ p ] = p - 1 NEW_LINE for i in range ( 2 * p , N , p ) : NEW_LINE INDENT phi [ i ] = ( phi [ i ] // p ) * ( p - 1 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def prefix ( ) : NEW_LINE INDENT for i in range ( 1 , N , 1 ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + phi [ i ] NEW_LINE DEDENT DEDENT def find_pairs ( n ) : NEW_LINE INDENT total = ( n * ( n - 1 ) ) // 2 NEW_LINE ans = total - pref [ n ] NEW_LINE print ( " Number β of β pairs β from β 1 β to " , n , " are " , ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT precompute ( ) NEW_LINE prefix ( ) NEW_LINE q = [ 5 , 7 ] NEW_LINE n = len ( q ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT find_pairs ( q [ i ] ) NEW_LINE DEDENT DEDENT |
Program to balance the given Chemical Equation | Function to calculate GCD ; Function to calculate b1 , b2 and b3 ; Variable declaration ; temp variable to store gcd ; Computing GCD ; Driver code | def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def balance ( x , y , p , q ) : NEW_LINE INDENT if ( p % x == 0 and q % y == 0 ) : NEW_LINE INDENT b1 = p // x NEW_LINE b2 = q // y NEW_LINE b3 = 1 NEW_LINE DEDENT else : NEW_LINE INDENT p = p * y NEW_LINE q = q * x NEW_LINE b3 = x * y NEW_LINE temp = gcd ( p , gcd ( q , b3 ) ) NEW_LINE b1 = p // temp NEW_LINE b2 = q // temp NEW_LINE b3 = b3 // temp NEW_LINE DEDENT print ( b1 , b2 , b3 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 2 NEW_LINE y = 3 NEW_LINE p = 4 NEW_LINE q = 5 NEW_LINE balance ( x , y , p , q ) NEW_LINE DEDENT |
Find the Maximum Alternate Subsequence Sum from a given array | Function to find maximum alternating subsequence sum ; initialize sum to 0 ; calculate the sum ; return the final result ; array initiaisation ; length of array | def maxAlternatingSum ( arr , n ) : NEW_LINE INDENT max_sum = 0 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT current_max = arr [ i ] NEW_LINE k = i NEW_LINE while k < n and ( ( arr [ i ] > 0 and arr [ k ] > 0 ) or ( arr [ i ] < 0 and arr [ k ] < 0 ) ) : NEW_LINE INDENT current_max = max ( current_max , arr [ k ] ) NEW_LINE k += 1 NEW_LINE DEDENT max_sum += current_max NEW_LINE i = k NEW_LINE DEDENT return max_sum NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , - 1 , - 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxAlternatingSum ( arr , n ) ) NEW_LINE |
Minimum length subarray containing all unique elements after Q operations | Function to find minimum size subarray of all array elements ; Updating the array after processing each query ; Making it to 0 - indexing ; Prefix sum array concept is used to obtain the count array ; Iterating over the array to get the final array ; Variable to get count of all unique elements ; Hash to maintain perviously occurred elements ; Loop to find the all unique elements ; Array to maintain counter of encountered elements ; Variable to store answer ; Using two pointers approach ; Increment counter if occurred once ; When all unique elements are found ; update answer with minimum size ; Decrement count of elements from left ; Decrement counter ; Driver code | def subarrayLength ( A , R , N , M ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT l = R [ i ] [ 0 ] NEW_LINE r = R [ i ] [ 1 ] + 1 NEW_LINE l -= 1 NEW_LINE r -= 1 NEW_LINE A [ l ] += 1 NEW_LINE if ( r < N ) : NEW_LINE INDENT A [ r ] -= 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT A [ i ] += A [ i - 1 ] NEW_LINE DEDENT count = 0 NEW_LINE s = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] not in s ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT s . append ( A [ i ] ) NEW_LINE DEDENT repeat = [ 0 ] * ( count + 1 ) NEW_LINE ans = N NEW_LINE counter , left , right = 0 , 0 , 0 NEW_LINE while ( right < N ) : NEW_LINE INDENT cur_element = A [ right ] NEW_LINE repeat [ cur_element ] += 1 NEW_LINE if ( repeat [ cur_element ] == 1 ) : NEW_LINE INDENT counter += 1 NEW_LINE DEDENT while ( counter == count ) : NEW_LINE INDENT ans = min ( ans , right - left + 1 ) NEW_LINE cur_element = A [ left ] NEW_LINE repeat [ cur_element ] -= 1 NEW_LINE left += 1 NEW_LINE if ( repeat [ cur_element ] == 0 ) : NEW_LINE INDENT counter -= 1 NEW_LINE DEDENT DEDENT right += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N , queries = 8 , 6 NEW_LINE Q = [ [ 1 , 4 ] , [ 3 , 4 ] , [ 4 , 5 ] , [ 5 , 5 ] , [ 7 , 8 ] , [ 8 , 8 ] ] NEW_LINE A = [ 0 ] * N NEW_LINE print ( subarrayLength ( A , Q , N , queries ) ) NEW_LINE DEDENT |
Elements of Array which can be expressed as power of prime numbers | Function to mark all the exponent of prime numbers ; If number is prime then marking all of its exponent true ; Function to display all required elements ; Function to print the required numbers ; To find the largest number ; Function call to mark all the Exponential prime nos . ; Function call ; Driver code | def ModifiedSieveOfEratosthenes ( N , Expo_Prime ) : NEW_LINE INDENT primes = [ True ] * N ; NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT if ( primes [ i ] ) : NEW_LINE INDENT no = i ; NEW_LINE while ( no <= N ) : NEW_LINE INDENT Expo_Prime [ no ] = True ; NEW_LINE no *= i ; NEW_LINE DEDENT for j in range ( i * i , N , i ) : NEW_LINE INDENT primes [ j ] = False ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def Display ( arr , Expo_Prime , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( Expo_Prime [ arr [ i ] ] ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT DEDENT def FindExpoPrime ( arr , n ) : NEW_LINE INDENT max = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( max < arr [ i ] ) : NEW_LINE INDENT max = arr [ i ] ; NEW_LINE DEDENT DEDENT Expo_Prime = [ False ] * ( max + 1 ) ; NEW_LINE ModifiedSieveOfEratosthenes ( max + 1 , Expo_Prime ) ; NEW_LINE Display ( arr , Expo_Prime , n ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 6 , 9 , 16 , 1 , 3 , 12 , 36 , 625 , 1000 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE FindExpoPrime ( arr , n ) ; NEW_LINE DEDENT |
Elements of Array which can be expressed as power of some integer to given exponent K | Method returns Nth power of A ; Smaller eps , denotes more accuracy ; Initializing difference between two roots by INT_MAX ; x ^ K denotes current value of x ; loop untiwe reach desired accuracy ; calculating current value from previous value by newton 's method ; Function to check whether its k root is an integer or not ; Function to find the numbers ; Driver code | def nthRoot ( A , N ) : NEW_LINE INDENT xPre = 7 NEW_LINE eps = 1e-3 NEW_LINE delX = 10 ** 9 NEW_LINE xK = 0 NEW_LINE while ( delX > eps ) : NEW_LINE INDENT xK = ( ( N - 1.0 ) * xPre + A / pow ( xPre , N - 1 ) ) / N NEW_LINE delX = abs ( xK - xPre ) NEW_LINE xPre = xK NEW_LINE DEDENT return xK NEW_LINE DEDENT def check ( no , k ) : NEW_LINE INDENT kth_root = nthRoot ( no , k ) NEW_LINE num = int ( kth_root ) NEW_LINE if ( abs ( num - kth_root ) < 1e-4 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def printExpo ( arr , n , k ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( check ( arr [ i ] , k ) ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 6 NEW_LINE arr = [ 46656 , 64 , 256 , 729 , 16 , 1000 ] NEW_LINE n = len ( arr ) NEW_LINE printExpo ( arr , n , K ) NEW_LINE DEDENT |
Count of subsequences whose product is a difference of square of two integers | Function to count the number of contiguous subsequences whose product can be expressed as square of difference of two integers ; Iterating through the array ; Check if that number can be expressed as the square of difference of two numbers ; Variable to compute the product ; Finding the remaining subsequences ; Check if that number can be expressed as the square of difference of two numbers ; Return the number of subsequences ; Driver code | def CntcontSubs ( a , n ) : NEW_LINE INDENT c = 0 NEW_LINE d = 0 NEW_LINE sum = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 2 != 0 or a [ i ] % 4 == 0 ) : NEW_LINE INDENT d += 1 NEW_LINE DEDENT sum = a [ i ] NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT sum = sum * a [ j ] NEW_LINE if ( sum % 2 != 0 or sum % 4 == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT sum = 1 NEW_LINE DEDENT return c + d NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 4 , 2 , 9 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( CntcontSubs ( arr , n ) ) NEW_LINE DEDENT |
Count of subsequences whose product is a difference of square of two integers | Function to count all the contiguous subsequences whose product is expressed as the square of the difference of two integers ; Creating vectors to store the remainders and the subsequences ; Iterating through the array ; Finding the remainder when the element is divided by 4 ; Bringing all the elements in the range [ 0 , 3 ] ; If the remainder is 2 , store the index of the ; If the remainder is 2 , store the index of the ; Finding the total number of subsequences ; If there are no numbers which yield the remainder 2 ; Iterating through the vector ; If the element is 2 , find the nearest 2 or 0 and find the number of elements between them ; Returning the count ; Driver Code | def CntcontSubs ( a , n ) : NEW_LINE INDENT prod = 1 NEW_LINE vect = [ ] NEW_LINE vect . append ( ( 0 , 2 ) ) NEW_LINE two , zero = [ ] , [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] = a [ i ] % 4 NEW_LINE if ( a [ i ] < 0 ) : NEW_LINE INDENT a [ i ] = a [ i ] + 4 NEW_LINE DEDENT if ( a [ i ] == 2 ) : NEW_LINE INDENT two . append ( i + 1 ) NEW_LINE DEDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT zero . append ( i + 1 ) NEW_LINE DEDENT if ( a [ i ] == 0 or a [ i ] == 2 ) : NEW_LINE INDENT vect . append ( ( i + 1 , a [ i ] ) ) NEW_LINE DEDENT DEDENT vect . append ( ( n + 1 , 2 ) ) NEW_LINE total = ( n * ( n + 1 ) ) // 2 NEW_LINE if ( len ( two ) == 0 ) : NEW_LINE INDENT return total NEW_LINE DEDENT else : NEW_LINE INDENT Sum = 0 NEW_LINE pos1 , pos2 , pos3 = - 1 , - 1 , - 1 NEW_LINE sz = len ( vect ) NEW_LINE for i in range ( 1 , sz - 1 ) : NEW_LINE INDENT if ( vect [ i ] [ 1 ] == 2 ) : NEW_LINE INDENT Sum += ( ( vect [ i ] [ 0 ] - vect [ i - 1 ] [ 0 ] ) * ( vect [ i + 1 ] [ 0 ] - vect [ i ] [ 0 ] ) - 1 ) NEW_LINE DEDENT DEDENT return ( total - Sum - len ( two ) ) NEW_LINE DEDENT DEDENT a = [ 5 , 4 , 2 , 9 , 8 ] NEW_LINE n = len ( a ) NEW_LINE print ( CntcontSubs ( a , n ) ) NEW_LINE |
Count of possible subarrays and subsequences using given length of Array | Function to count the subarray for the given array ; Function to count the subsequence for the given array length ; Driver Code | def countSubarray ( n ) : NEW_LINE INDENT return ( ( n ) * ( n + 1 ) ) // 2 NEW_LINE DEDENT def countSubsequence ( n ) : NEW_LINE INDENT return ( 2 ** n ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE print ( countSubarray ( n ) ) NEW_LINE print ( countSubsequence ( n ) ) NEW_LINE DEDENT |
Program for finding the Integral of a given function using Boole 's Rule | Function to return the value of f ( x ) for the given value of x ; Function to computes the integrand of y at the given intervals of x with step size h and the initial limit a and final limit b ; Number of intervals ; Computing the step size ; Substituing a = 0 , b = 4 and h = 1 ; Driver code | def y ( x ) : NEW_LINE INDENT return ( 1 / ( 1 + x ) ) NEW_LINE DEDENT def BooleRule ( a , b ) : NEW_LINE INDENT n = 4 NEW_LINE h = ( ( b - a ) / n ) NEW_LINE sum = 0 NEW_LINE bl = ( 7 * y ( a ) + 32 * y ( a + h ) + 12 * y ( a + 2 * h ) + 32 * y ( a + 3 * h ) + 7 * y ( a + 4 * h ) ) * 2 * h / 45 NEW_LINE sum = sum + bl NEW_LINE return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT lowlimit = 0 NEW_LINE upplimit = 4 NEW_LINE print ( " f ( x ) β = " , round ( BooleRule ( 0 , 4 ) , 4 ) ) NEW_LINE DEDENT |
Number of subsets with same AND , OR and XOR values in an Array | Python3 program to find the number of subsets with equal bitwise AND , OR and XOR values ; Function to find the number of subsets with equal bitwise AND , OR and XOR values ; Precompute the modded powers of two for subset counting ; Loop to iterate and find the modded powers of two for subset counting ; Map to store the frequency of each element ; Loop to compute the frequency ; For every element > 0 , the number of subsets formed using this element only is equal to 2 ^ ( frequency [ element ] - 1 ) . And for 0 , we have to find all the subsets , so 2 ^ ( frequency [ element ] ) - 1 ; If element is greater than 0 ; Driver code | mod = 1000000007 NEW_LINE def countSubsets ( a , n ) : NEW_LINE INDENT answer = 0 NEW_LINE powerOfTwo = [ 0 for x in range ( 100005 ) ] NEW_LINE powerOfTwo [ 0 ] = 1 NEW_LINE for i in range ( 1 , 100005 ) : NEW_LINE INDENT powerOfTwo [ i ] = ( powerOfTwo [ i - 1 ] * 2 ) % mod NEW_LINE DEDENT frequency = { } NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if a [ i ] in frequency : NEW_LINE INDENT frequency [ a [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT frequency [ a [ i ] ] = 1 NEW_LINE DEDENT DEDENT for key , value in frequency . items ( ) : NEW_LINE INDENT if ( key != 0 ) : NEW_LINE INDENT answer = ( answer % mod + powerOfTwo [ value - 1 ] ) % mod NEW_LINE DEDENT else : NEW_LINE INDENT answer = ( answer % mod + powerOfTwo [ value ] - 1 + mod ) % mod NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT N = 6 NEW_LINE A = [ 1 , 3 , 2 , 1 , 2 , 1 ] NEW_LINE print ( countSubsets ( A , N ) ) NEW_LINE |
Sum of all Perfect numbers lying in the range [ L , R ] | Python3 implementation to find the sum of all perfect numbers lying in the range [ L , R ] ; Array to store the sum ; Function to check if a number is a perfect number or not ; Iterating till the square root of the number and checking if the sum of divisors is equal to the number or not ; If it is a perfect number , then return the number ; Else , return 0 ; Function to precompute the sum of perfect squares and store then in an array | from math import sqrt NEW_LINE pref = [ 0 ] * 10000 ; NEW_LINE def isPerfect ( n ) : NEW_LINE INDENT sum = 1 ; NEW_LINE for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( i * i != n ) : NEW_LINE INDENT sum = sum + i + n // i ; NEW_LINE DEDENT else : NEW_LINE INDENT sum = sum + i ; NEW_LINE DEDENT DEDENT DEDENT if ( sum == n and n != 1 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT def precomputation ( ) : NEW_LINE INDENT for i in range ( 1 , 10000 ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + isPerfect ( i ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 6 ; R = 28 ; NEW_LINE precomputation ( ) ; NEW_LINE print ( pref [ R ] - pref [ L - 1 ] ) ; NEW_LINE DEDENT |
Ternary number system or Base 3 numbers | Python3 program to convert a ternary number to decimal number ; Function to convert a ternary number to a decimal number ; If the number is greater than 0 , compute the decimal representation of the number ; Loop to iterate through the number ; Computing the decimal digit ; Driver code | import math ; NEW_LINE def convertToDecimal ( N ) : NEW_LINE INDENT print ( " Decimal β number β of " , N , " is : " , end = " β " ) ; NEW_LINE if ( N != 0 ) : NEW_LINE INDENT decimalNumber = 0 ; NEW_LINE i = 0 ; NEW_LINE remainder = 0 ; NEW_LINE while ( N != 0 ) : NEW_LINE INDENT remainder = N % 10 ; NEW_LINE N = N // 10 ; NEW_LINE decimalNumber += remainder * math . pow ( 3 , i ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT print ( decimalNumber ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( "0" ) ; NEW_LINE DEDENT DEDENT Ternary = 10202202 ; NEW_LINE convertToDecimal ( Ternary ) ; NEW_LINE |
Check if a given pair of Numbers are Betrothed numbers or not | Python3 program for the above approach ; Function to check whether N is Perfect Square or not ; Find sqrt ; Function to check whether the given pairs of numbers is Betrothed Numbers or not ; For finding the sum of all the divisors of first number n ; For finding the sum of all the divisors of second number m ; Driver Code ; Function Call | from math import sqrt , floor NEW_LINE def isPerfectSquare ( N ) : NEW_LINE INDENT sr = sqrt ( N ) NEW_LINE return ( sr - floor ( sr ) ) == 0 NEW_LINE DEDENT def BetrothedNumbers ( n , m ) : NEW_LINE INDENT Sum1 = 1 NEW_LINE Sum2 = 1 NEW_LINE for i in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( isPerfectSquare ( n ) ) : NEW_LINE INDENT Sum1 += i NEW_LINE DEDENT else : NEW_LINE INDENT Sum1 += i + n / i NEW_LINE DEDENT DEDENT DEDENT for i in range ( 2 , int ( sqrt ( m ) ) + 1 , 1 ) : NEW_LINE INDENT if ( m % i == 0 ) : NEW_LINE INDENT if ( isPerfectSquare ( m ) ) : NEW_LINE INDENT Sum2 += i NEW_LINE DEDENT else : NEW_LINE INDENT Sum2 += i + ( m / i ) NEW_LINE DEDENT DEDENT DEDENT if ( ( n + 1 == Sum2 ) and ( m + 1 == Sum1 ) ) : 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 = 9504 NEW_LINE M = 20734 NEW_LINE BetrothedNumbers ( N , M ) NEW_LINE DEDENT |
Count of numbers upto M with GCD equals to K when paired with M | Function to calculate GCD using euler totient function ; Finding the prime factors of limit to calculate it 's euler totient function ; Calculating the euler totient function of ( mk ) ; Function print the count of numbers whose GCD with M equals to K ; GCD of m with any integer cannot be equal to k ; 0 and m itself will be the only valid integers ; Finding the number upto which coefficient of k can come ; Driver code | def EulerTotientFunction ( limit ) : NEW_LINE INDENT copy = limit NEW_LINE primes = [ ] NEW_LINE for i in range ( 2 , limit + 1 ) : NEW_LINE INDENT if i * i > limit : NEW_LINE INDENT break NEW_LINE DEDENT if ( limit % i == 0 ) : NEW_LINE INDENT while ( limit % i == 0 ) : NEW_LINE INDENT limit //= i NEW_LINE DEDENT primes . append ( i ) NEW_LINE DEDENT DEDENT if ( limit >= 2 ) : NEW_LINE INDENT primes . append ( limit ) NEW_LINE DEDENT ans = copy NEW_LINE for it in primes : NEW_LINE INDENT ans = ( ans // it ) * ( it - 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def CountGCD ( m , k ) : NEW_LINE INDENT if ( m % k != 0 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT if ( m == k ) : NEW_LINE INDENT print ( 2 ) NEW_LINE return NEW_LINE DEDENT limit = m // k NEW_LINE ans = EulerTotientFunction ( limit ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = 9 NEW_LINE K = 1 NEW_LINE CountGCD ( M , K ) NEW_LINE DEDENT |
Find the product of sum of two diagonals of a square Matrix | Function to find the product of the sum of diagonals . ; Initialize sums of diagonals ; Return the answer ; Driven code ; Function call | def product ( mat , n ) : NEW_LINE INDENT d1 = 0 NEW_LINE d2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT d1 += mat [ i ] [ i ] NEW_LINE d2 += mat [ i ] [ n - i - 1 ] NEW_LINE DEDENT return d1 * d2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 5 , 8 , 1 ] , [ 5 , 10 , 3 ] , [ - 6 , 17 , - 9 ] ] NEW_LINE n = len ( mat ) NEW_LINE print ( product ( mat , n ) ) NEW_LINE DEDENT |
Program to calculate Percentile of a student based on rank | Program to calculate the percentile ; flat variable to store the result ; calculate and return the percentile ; Driver Code | def getPercentile ( rank , students ) : NEW_LINE INDENT result = ( students - rank ) / students * 100 ; NEW_LINE return result ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT your_rank = 805 ; NEW_LINE total_students = 97481 ; NEW_LINE print ( getPercentile ( your_rank , total_students ) ) ; NEW_LINE DEDENT |
Sum of numbers in the Kth level of a Fibonacci triangle | Python3 implementation to find the Sum of numbers in the Kth level of a Fibonacci triangle ; Function to return the nth Fibonacci number ; Function to return the required sum of the array ; Using our deduced result ; Function to return the sum of fibonacci in the Kth array ; Count of fibonacci which are in the arrays from 1 to k - 1 ; Driver code | import math NEW_LINE MAX = 1000000 NEW_LINE def fib ( n ) : NEW_LINE INDENT phi = ( 1 + math . sqrt ( 5 ) ) / 2 NEW_LINE return round ( pow ( phi , n ) / math . sqrt ( 5 ) ) NEW_LINE DEDENT def calculateSum ( l , r ) : NEW_LINE INDENT sum = fib ( r + 2 ) - fib ( l + 1 ) NEW_LINE return sum NEW_LINE DEDENT def sumFibonacci ( k ) : NEW_LINE INDENT l = ( k * ( k - 1 ) ) / 2 NEW_LINE r = l + k NEW_LINE sum = calculateSum ( l , r - 1 ) NEW_LINE return sum NEW_LINE DEDENT k = 3 NEW_LINE print ( sumFibonacci ( k ) ) NEW_LINE |
Print the sequence of size N in which every term is sum of previous K terms | Function to generate the series in the form of array ; Pick a starting point ; Find the sum of all elements till count < K ; Find the value of sum at i position ; Driver Code | def sumOfPrevK ( N , K ) : NEW_LINE INDENT arr = [ 0 for i in range ( N ) ] NEW_LINE arr [ 0 ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT j = i - 1 NEW_LINE count = 0 NEW_LINE sum = 0 NEW_LINE while ( j >= 0 and count < K ) : NEW_LINE INDENT sum = sum + arr [ j ] NEW_LINE j = j - 1 NEW_LINE count = count + 1 NEW_LINE DEDENT arr [ i ] = sum NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT print ( arr [ i ] ) NEW_LINE DEDENT DEDENT N = 10 NEW_LINE K = 4 NEW_LINE sumOfPrevK ( N , K ) NEW_LINE |
Print the sequence of size N in which every term is sum of previous K terms | Function to generate the series in the form of array ; Pick a starting point ; Computing the previous sum ; Loop to print the series ; Driver code | def sumOfPrevK ( N , K ) : NEW_LINE INDENT arr = [ 0 ] * N ; NEW_LINE prevsum = 0 ; NEW_LINE arr [ 0 ] = 1 ; NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( i < K ) : NEW_LINE INDENT arr [ i + 1 ] = arr [ i ] + prevsum ; NEW_LINE prevsum = arr [ i + 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i + 1 ] = arr [ i ] + prevsum - arr [ i + 1 - K ] ; NEW_LINE prevsum = arr [ i + 1 ] ; NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 ; NEW_LINE K = 3 ; NEW_LINE sumOfPrevK ( N , K ) ; NEW_LINE DEDENT |
Maximum GCD of all subarrays of length at least 2 | Function to find GCD ; To store the maximum GCD ; Traverse the array ; Find GCD of the consecutive element ; If calculated GCD > maxGCD then update it ; Print the maximum GCD ; Driver Code ; Function call | def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT return gcd ( b , a % b ) ; NEW_LINE DEDENT def findMaxGCD ( arr , n ) : NEW_LINE INDENT maxGCD = 0 ; NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT val = gcd ( arr [ i ] , arr [ i + 1 ] ) ; NEW_LINE if ( val > maxGCD ) : NEW_LINE INDENT maxGCD = val ; NEW_LINE DEDENT DEDENT print ( maxGCD ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 18 , 9 , 9 , 5 , 15 , 8 , 7 , 6 , 9 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findMaxGCD ( arr , n ) ; NEW_LINE DEDENT |
Sum of elements of an AP in the given range | Function to find sum in the given range ; Find the value of k ; Find the common difference ; Find the sum ; Driver code | def findSum ( arr , n , left , right ) : NEW_LINE INDENT k = right - left ; NEW_LINE d = arr [ 1 ] - arr [ 0 ] ; NEW_LINE ans = arr [ left - 1 ] * ( k + 1 ) ; NEW_LINE ans = ans + ( d * ( k * ( k + 1 ) ) ) // 2 ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 ] ; NEW_LINE queries = 3 ; NEW_LINE q = [ [ 2 , 4 ] , [ 2 , 6 ] , [ 5 , 6 ] ] ; NEW_LINE n = len ( arr ) ; NEW_LINE for i in range ( queries ) : NEW_LINE INDENT print ( findSum ( arr , n , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) ) ; NEW_LINE DEDENT DEDENT |
Check if a subarray exists with sum greater than the given Array | Function to check whether there exists a subarray whose sum is greater than or equal to sum of given array elements ; Initialize sum with 0 ; Checking possible prefix subarrays . If sum of them is less than or equal to zero , then return 1 ; again reset sum to zero ; Checking possible suffix subarrays . If sum of them is less than or equal to zero , then return 1 ; Otherwise return 0 ; Driver Code | def subarrayPossible ( arr , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE if ( sum <= 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT sum = 0 ; NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE if ( sum <= 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 5 , - 12 , 7 , - 10 , 20 , 30 , - 10 , 50 , 60 ] ; NEW_LINE size = len ( arr ) ; NEW_LINE if ( subarrayPossible ( arr , size ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Finding Integreand using Weedle 's Rule | A sample function f ( x ) = 1 / ( 1 + x ^ 2 ) ; Function to find the integral value of f ( x ) with step size h , with initial lower limit and upper limit a and b ; Find step size h ; To store the final sum ; Find sum using Weedle 's Formula ; Return the final sum ; Driver Code ; lower limit and upper limit ; Function Call | def y ( x ) : NEW_LINE INDENT num = 1 ; NEW_LINE denom = float ( 1.0 + x * x ) ; NEW_LINE return num / denom ; NEW_LINE DEDENT def WeedleRule ( a , b ) : NEW_LINE INDENT h = ( b - a ) / 6 ; NEW_LINE sum = 0 ; NEW_LINE sum = sum + ( ( ( 3 * h ) / 10 ) * ( y ( a ) + y ( a + 2 * h ) + 5 * y ( a + h ) + 6 * y ( a + 3 * h ) + y ( a + 4 * h ) + 5 * y ( a + 5 * h ) + y ( a + 6 * h ) ) ) ; NEW_LINE return sum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 0 ; NEW_LINE b = 6 ; NEW_LINE num = WeedleRule ( a , b ) ; NEW_LINE print ( " f ( x ) β = β { 0 : . 6f } " . format ( num ) ) ; NEW_LINE DEDENT |
Find the minimum number to be added to N to make it a prime number | Function to check if a given number is a prime or not ; Base cases ; This is checked so that we can skip middle five numbers in below loop ; For all the remaining numbers , check if any number is a factor if the number or not ; If none of the above numbers are the factors for the number , then the given number is prime ; Function to return the smallest number to be added to make a number prime ; Base case ; Loop continuously until isPrime returns true for a number greater than n ; If the number is not a prime , then increment the number by 1 and the counter which stores the number to be added ; Driver code | def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def findSmallest ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT prime , counter = N , 0 NEW_LINE found = False NEW_LINE while ( not found ) : NEW_LINE INDENT if ( isPrime ( prime ) ) : NEW_LINE INDENT found = True NEW_LINE DEDENT else : NEW_LINE INDENT prime += 1 NEW_LINE counter += 1 NEW_LINE DEDENT DEDENT return counter NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 10 NEW_LINE print ( findSmallest ( N ) ) NEW_LINE DEDENT |
Find the position of the given Prime Number | Python3 program to find the position of the given prime number ; Function to precompute the position of every prime number using Sieve ; 0 and 1 are not prime numbers ; Variable to store the position ; Incrementing the position for every prime number ; Driver code | limit = 1000000 NEW_LINE position = [ 0 ] * ( limit + 1 ) NEW_LINE def sieve ( ) : NEW_LINE INDENT position [ 0 ] = - 1 NEW_LINE position [ 1 ] = - 1 NEW_LINE pos = 0 NEW_LINE for i in range ( 2 , limit + 1 ) : NEW_LINE INDENT if ( position [ i ] == 0 ) : NEW_LINE INDENT pos += 1 NEW_LINE position [ i ] = pos NEW_LINE for j in range ( i * 2 , limit + 1 , i ) : NEW_LINE INDENT position [ j ] = - 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT sieve ( ) NEW_LINE n = 11 NEW_LINE print ( position [ n ] ) NEW_LINE DEDENT |
Minimum possible sum of array elements after performing the given operation | Function to find the maximum sum of the sub array ; max_so_far represents the maximum sum found till now and max_ending_here represents the maximum sum ending at a specific index ; Iterating through the array to find the maximum sum of the subarray ; If the maximum sum ending at a specific index becomes less than 0 , then making it equal to 0. ; Function to find the minimum possible sum of the array elements after performing the given operation ; Finding the sum of the array ; Computing the minimum sum of the array ; Driver code | def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - 10 ** 9 NEW_LINE max_ending_here = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] NEW_LINE if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_here NEW_LINE DEDENT if ( max_ending_here < 0 ) : NEW_LINE INDENT max_ending_here = 0 NEW_LINE DEDENT DEDENT return max_so_far NEW_LINE DEDENT def minPossibleSum ( a , n , x ) : NEW_LINE INDENT mxSum = maxSubArraySum ( a , n ) NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT sum = sum - mxSum + mxSum / x NEW_LINE print ( round ( sum , 2 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE X = 2 NEW_LINE A = [ 1 , - 2 , 3 ] NEW_LINE minPossibleSum ( A , N , X ) NEW_LINE DEDENT |
Print the two possible permutations from a given sequence | Function to check if the sequence is concatenation of two permutations or not ; Computing the sum of all the elements in the array ; Computing the prefix sum for all the elements in the array ; Iterating through the i from lengths 1 to n - 1 ; Sum of first i + 1 elements ; Sum of remaining n - i - 1 elements ; Lengths of the 2 permutations ; Checking if the sums satisfy the formula or not ; Function to print the two permutations ; Print the first permutation ; Print the second permutation ; Function to find the two permutations from the given sequence ; If the sequence is not a concatenation of two permutations ; Find the largest element in the array and set the lengths of the permutations accordingly ; Driver code | def checkPermutation ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT prefix = [ 0 for i in range ( n + 1 ) ] NEW_LINE prefix [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + arr [ i ] NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT lsum = prefix [ i ] NEW_LINE rsum = sum - prefix [ i ] NEW_LINE l_len = i + 1 NEW_LINE r_len = n - i - 1 NEW_LINE if ( ( ( 2 * lsum ) == ( l_len * ( l_len + 1 ) ) ) and ( ( 2 * rsum ) == ( r_len * ( r_len + 1 ) ) ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def printPermutations ( arr , n , l1 , l2 ) : NEW_LINE INDENT for i in range ( l1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT print ( " " , end β = β " " ) ; NEW_LINE for i in range ( l1 , n , 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def findPermutations ( arr , n ) : NEW_LINE INDENT if ( checkPermutation ( arr , n ) == False ) : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE return NEW_LINE DEDENT l1 = 0 NEW_LINE l2 = 0 NEW_LINE l1 = max ( arr ) NEW_LINE l2 = n - l1 NEW_LINE s1 = set ( ) NEW_LINE s2 = set ( ) NEW_LINE for i in range ( l1 ) : NEW_LINE INDENT s1 . add ( arr [ i ] ) NEW_LINE DEDENT for i in range ( l1 , n ) : NEW_LINE INDENT s2 . add ( arr [ i ] ) NEW_LINE DEDENT if ( len ( s1 ) == l1 and len ( s2 ) == l2 ) : NEW_LINE INDENT printPermutations ( arr , n , l1 , l2 ) NEW_LINE DEDENT else : NEW_LINE INDENT temp = l1 NEW_LINE l1 = l2 NEW_LINE l2 = temp NEW_LINE printPermutations ( arr , n , l1 , l2 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 1 , 10 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE findPermutations ( arr , n ) NEW_LINE DEDENT |
Count pairs in array such that one element is reverse of another | Function to reverse the digits of the number ; Loop to iterate till the number is greater than 0 ; Extract the last digit and keep multiplying it by 10 to get the reverse of the number ; Function to find the pairs from the such that one number is reverse of the other ; Iterate through all pairs ; Increment count if one is the reverse of other ; Driver code | def reverse ( num ) : NEW_LINE INDENT rev_num = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT rev_num = rev_num * 10 + num % 10 NEW_LINE num = num // 10 NEW_LINE DEDENT return rev_num NEW_LINE DEDENT def countReverse ( 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 ( reverse ( arr [ i ] ) == arr [ j ] ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 16 , 61 , 12 , 21 , 25 ] NEW_LINE n = len ( a ) NEW_LINE print ( countReverse ( a , n ) ) NEW_LINE DEDENT |
Count pairs in array such that one element is reverse of another | Python3 program to count the pairs in array such that one element is reverse of another ; Function to reverse the digits of the number ; Loop to iterate till the number is greater than 0 ; Extract the last digit and keep multiplying it by 10 to get the reverse of the number ; Function to find the pairs from the array such that one number is reverse of the other ; Iterate over every element in the array and increase the frequency of the element in hash map ; Iterate over every element in the array ; remove the current element from the hash map by decreasing the frequency to avoid counting when the number is a palindrome or when we visit its reverse ; Increment the count by the frequency of reverse of the number ; Driver code | from collections import defaultdict NEW_LINE def reverse ( num ) : NEW_LINE INDENT rev_num = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT rev_num = rev_num * 10 + num % 10 NEW_LINE num = num // 10 NEW_LINE DEDENT return rev_num NEW_LINE DEDENT def countReverse ( arr , n ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] -= 1 NEW_LINE res += freq [ reverse ( arr [ i ] ) ] NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 16 , 61 , 12 , 21 , 25 ] NEW_LINE n = len ( a ) NEW_LINE print ( countReverse ( a , n ) ) NEW_LINE DEDENT |
Sum of i * countDigits ( i ) ^ countDigits ( i ) for all i in range [ L , R ] | Python 3 program to find the required sum ; Function to return the required sum ; Iterating for all the number of digits from 1 to 10 ; If the range is valid ; Sum of AP ; Computing the next minimum and maximum numbers by for the ( i + 1 ) - th digit ; Driver code | MOD = 1000000007 NEW_LINE def rangeSum ( l , r ) : NEW_LINE INDENT a = 1 NEW_LINE b = 9 NEW_LINE res = 0 NEW_LINE for i in range ( 1 , 11 ) : NEW_LINE INDENT L = max ( l , a ) NEW_LINE R = min ( r , b ) NEW_LINE if ( L <= R ) : NEW_LINE INDENT sum = ( L + R ) * ( R - L + 1 ) // 2 NEW_LINE res += pow ( i , i ) * ( sum % MOD ) NEW_LINE res %= MOD NEW_LINE DEDENT a = a * 10 NEW_LINE b = b * 10 + 9 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 98 NEW_LINE r = 102 NEW_LINE print ( rangeSum ( l , r ) ) NEW_LINE DEDENT |
Trial division Algorithm for Prime Factorization | Function to check if a number is a prime number or not ; Initializing with the value 2 from where the number is checked ; Computing the square root of the number N ; While loop till the square root of N ; If any of the numbers between [ 2 , sqrt ( N ) ] is a factor of N Then the number is composite ; If none of the numbers is a factor , then it is a prime number ; Driver code ; To check if a number is a prime or not | def TrialDivision ( N ) : NEW_LINE INDENT i = 2 NEW_LINE k = int ( N ** 0.5 ) NEW_LINE while ( i <= k ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 49 NEW_LINE p = TrialDivision ( N ) NEW_LINE if ( p ) : NEW_LINE INDENT print ( " Prime " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Composite " ) NEW_LINE DEDENT DEDENT |
Find if it is possible to choose subarray that it contains exactly K even integers | Function to check if it is possible to choose a subarray that contains exactly K even integers ; Variable to store the count of even numbers ; If we have to select 0 even numbers but there is all odd numbers in the array ; If the count of even numbers is greater than or equal to K then we can select a subarray with exactly K even integers ; If the count of even numbers is less than K then we cannot select any subarray with exactly K even integers ; Driver code | def isPossible ( A , n , k ) : NEW_LINE INDENT countOfTwo = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( A [ i ] % 2 == 0 ) : NEW_LINE INDENT countOfTwo += 1 NEW_LINE DEDENT DEDENT if ( k == 0 and countOfTwo == n ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT elif ( countOfTwo >= 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 arr = [ 1 , 2 , 4 , 5 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE isPossible ( arr , N , K ) NEW_LINE DEDENT |
Count of pairs ( A , B ) in range 1 to N such that last digit of A is equal to the first digit of B | Function to Count of pairs ( A , B ) in range 1 to N ; count C i , j ; Calculate number of pairs ; Driver code ; Function call | def pairs ( n ) : NEW_LINE INDENT c = [ [ 0 for i in range ( 10 ) ] for i in range ( 10 ) ] NEW_LINE tmp = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i >= tmp * 10 ) : NEW_LINE INDENT tmp *= 10 NEW_LINE DEDENT c [ i // tmp ] [ i % 10 ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT for j in range ( 1 , 10 ) : NEW_LINE INDENT ans += c [ i ] [ j ] * c [ j ] [ i ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 25 NEW_LINE print ( pairs ( n ) ) NEW_LINE DEDENT |
Count ways to divide C in two parts and add to A and B to make A strictly greater than B | Function to count the number of ways to divide C into two parts and add to A and B such that A is strictly greater than B ; Minimum value added to A to satisfy the given relation ; Number of different values of A , i . e . , number of ways to divide C ; Driver code | def countWays ( A , B , C ) : NEW_LINE INDENT minAddA = max ( 0 , ( C + B - A + 2 ) // 2 ) NEW_LINE count_ways = max ( C - minAddA + 1 , 0 ) NEW_LINE return count_ways NEW_LINE DEDENT A = 3 NEW_LINE B = 5 NEW_LINE C = 5 NEW_LINE print ( countWays ( A , B , C ) ) NEW_LINE |
GCD of elements occurring Fibonacci number of times in an Array | Python 3 program to find the GCD of elements which occur Fibonacci number of times ; Function to create hash table to check Fibonacci numbers ; Inserting the first two numbers into the hash ; Adding the remaining Fibonacci numbers using the previously added elements ; Function to return the GCD of elements in an array having fibonacci frequency ; Creating the hash ; Map is used to store the frequencies of the elements ; Iterating through the array ; Traverse the map using iterators ; Calculate the gcd of elements having fibonacci frequencies ; Driver code | from collections import defaultdict NEW_LINE import math NEW_LINE def createHash ( hash1 , maxElement ) : NEW_LINE INDENT prev , curr = 0 , 1 NEW_LINE hash1 . add ( prev ) NEW_LINE hash1 . add ( curr ) NEW_LINE while ( curr <= maxElement ) : NEW_LINE INDENT temp = curr + prev NEW_LINE if temp <= maxElement : NEW_LINE INDENT hash1 . add ( temp ) NEW_LINE DEDENT prev = curr NEW_LINE curr = temp NEW_LINE DEDENT DEDENT def gcdFibonacciFreq ( arr , n ) : NEW_LINE INDENT hash1 = set ( ) NEW_LINE createHash ( hash1 , max ( arr ) ) NEW_LINE m = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ arr [ i ] ] += 1 NEW_LINE DEDENT gcd = 0 NEW_LINE for it in m . keys ( ) : NEW_LINE INDENT if ( m [ it ] in hash1 ) : NEW_LINE INDENT gcd = math . gcd ( gcd , it ) NEW_LINE DEDENT DEDENT return gcd NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 3 , 6 , 5 , 6 , 6 , 5 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( gcdFibonacciFreq ( arr , n ) ) NEW_LINE DEDENT |
Program to print the series 1 , 9 , 17 , 33 , 49 , 73 , 97. . . till N terms | Function to prthe series ; Generate the ith term and print ; Driver Code | def printSeries ( N ) : NEW_LINE INDENT ith_term = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT ith_term = 0 ; NEW_LINE if ( i % 2 == 0 ) : NEW_LINE INDENT ith_term = 2 * i * i + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ith_term = 2 * i * i - 1 ; NEW_LINE DEDENT print ( ith_term , end = " , β " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 ; NEW_LINE printSeries ( N ) ; NEW_LINE DEDENT |
Find Nth term of the series where each term differs by 6 and 2 alternately | Function to find Nth term ; Iterate from 1 till Nth term ; Check if i is even and then add 6 ; Else add 2 ; Print ans ; Driver Code | def findNthTerm ( N ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT ans = ans + 6 NEW_LINE DEDENT else : NEW_LINE INDENT ans = ans + 2 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE findNthTerm ( N ) NEW_LINE DEDENT |
Find the number of ordered pairs such that a * p + b * q = N , where p and q are primes | Python3 program to find the number of ordered pairs such that a * p + b * q = N where p and q are primes ; Sieve of erastothenes to store the prime numbers and their frequency in form a * p + b * q ; Performing Sieve of Eratosthenes to find the prime numbers unto 10001 ; Loop to find the number of ordered pairs for every combination of the prime numbers ; Driver code ; Printing the number of ordered pairs for every query | from math import sqrt NEW_LINE size = 1000 NEW_LINE prime = [ 0 for i in range ( size ) ] NEW_LINE freq = [ 0 for i in range ( size ) ] NEW_LINE def sieve ( a , b ) : NEW_LINE INDENT prime [ 1 ] = 1 NEW_LINE for i in range ( 2 , int ( sqrt ( size ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ i ] == 0 ) : NEW_LINE INDENT for j in range ( i * 2 , size , i ) : NEW_LINE INDENT prime [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT for p in range ( 1 , size , 1 ) : NEW_LINE INDENT for q in range ( 1 , size , 1 ) : NEW_LINE INDENT if ( prime [ p ] == 0 and prime [ q ] == 0 and a * p + b * q < size ) : NEW_LINE INDENT freq [ a * p + b * q ] += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT queries = 2 NEW_LINE a = 1 NEW_LINE b = 2 NEW_LINE sieve ( a , b ) NEW_LINE arr = [ 15 , 25 ] NEW_LINE for i in range ( queries ) : NEW_LINE INDENT print ( freq [ arr [ i ] ] , end = " β " ) NEW_LINE DEDENT DEDENT |
Find the Sum of the series 1 / 2 | Function to find the sum of series ; Generate the ith term and add it to the sum if i is even and subtract if i is odd ; Print the sum ; Driver Code | def printSeriesSum ( N ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT sum += i / ( i + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT sum -= i / ( i + 1 ) ; NEW_LINE DEDENT DEDENT print ( sum ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 10 ; NEW_LINE printSeriesSum ( N ) ; NEW_LINE DEDENT |
Find the Sum of the series 1 + 2 + 9 + 64 + 625 + 7776 . . . till N terms | Function to find the summ of series ; Generate the ith term and add it to the summ ; Prthe summ ; Driver Code | def printSeriessumm ( N ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT summ += pow ( i , i - 1 ) NEW_LINE DEDENT print ( summ ) NEW_LINE DEDENT N = 5 NEW_LINE printSeriessumm ( N ) NEW_LINE |
Find the Sum of the series 1 + 1 / 3 + 1 / 5 + 1 / 7 + ... till N terms | Function to find the sum of the given series ; Initialise the sum to 0 ; Generate the ith term and add it to the sum ; Print the final sum ; Driver Code | def printSumSeries ( N ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT sum += 1.0 / ( 2 * i - 1 ) ; NEW_LINE DEDENT print ( sum ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 ; NEW_LINE printSumSeries ( N ) ; NEW_LINE DEDENT |
Find the Sum of the series 1 , 2 , 3 , 6 , 9 , 18 , 27 , 54 , ... till N terms | Function to find the sum of series ; Flag to find the multiplicating factor . . i . e , by 2 or 3 / 2 ; First term ; If flag is true , multiply by 2 ; If flag is false , multiply by 3 / 2 ; Update the previous element to nextElement ; Print the sum ; Driver Code | def printSeriesSum ( N ) : NEW_LINE INDENT sum = 0 ; NEW_LINE a = 1 ; NEW_LINE cnt = 0 ; NEW_LINE flag = True ; NEW_LINE sum += a ; NEW_LINE while ( cnt < N ) : NEW_LINE INDENT nextElement = None ; NEW_LINE if ( flag ) : NEW_LINE INDENT nextElement = a * 2 ; NEW_LINE sum += nextElement ; NEW_LINE flag = not flag ; NEW_LINE DEDENT else : NEW_LINE INDENT nextElement = a * ( 3 / 2 ) ; NEW_LINE sum += nextElement ; NEW_LINE flag = not flag ; NEW_LINE DEDENT a = nextElement ; NEW_LINE cnt += 1 NEW_LINE DEDENT print ( sum ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 8 ; NEW_LINE printSeriesSum ( N ) ; NEW_LINE DEDENT |
Subsets and Splits