text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Maximum Prefix Sum possible by merging two given arrays | Python3 implementation of the above approach ; Stores the maximum prefix sum of the array A [ ] ; Traverse the array A [ ] ; Stores the maximum prefix sum of the array B [ ] ; Traverse the array B [ ] ; Driver code
def maxPresum ( a , b ) : NEW_LINE INDENT X = max ( a [ 0 ] , 0 ) NEW_LINE for i in range ( 1 , len ( a ) ) : NEW_LINE INDENT a [ i ] += a [ i - 1 ] NEW_LINE X = max ( X , a [ i ] ) NEW_LINE DEDENT Y = max ( b [ 0 ] , 0 ) NEW_LINE for i in range ( 1 , len ( b ) ) : NEW_LINE INDENT b [ i ] += b [ i - 1 ] NEW_LINE Y = max ( Y , b [ i ] ) NEW_LINE DEDENT return X + Y NEW_LINE DEDENT A = [ 2 , - 1 , 4 , - 5 ] NEW_LINE B = [ 4 , - 3 , 12 , 4 , - 3 ] NEW_LINE print ( maxPresum ( A , B ) ) NEW_LINE
Check if a number can be represented as sum of two positive perfect cubes | Python3 program for the above approach ; Function to check if N can be represented as sum of two perfect cubes or not ; If it is same return true ; ; If the curr smaller than n increment the lo ; If the curr is greater than curr decrement the hi ; Driver Code ; Function call to check if N can be represented as sum of two perfect cubes or not
import math NEW_LINE def sumOfTwoCubes ( n ) : NEW_LINE INDENT lo = 1 NEW_LINE hi = round ( math . pow ( n , 1 / 3 ) ) NEW_LINE while ( lo <= hi ) : NEW_LINE INDENT curr = ( lo * lo * lo + hi * hi * hi ) NEW_LINE if ( curr == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( curr < n ) : NEW_LINE INDENT lo += 1 NEW_LINE DEDENT else : NEW_LINE INDENT hi -= 1 NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT N = 28 NEW_LINE if ( sumOfTwoCubes ( N ) ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT
Generate an N | Python3 program for the above approach ; Function to generate all prime numbers upto 10 ^ 6 ; Initialize sieve [ ] as 1 ; Iterate over the range [ 2 , N ] ; If current element is non - prime ; Make all multiples of i as 0 ; Function to construct an array A [ ] satisfying the given conditions ; Stores the resultant array ; Stores all prime numbers ; Sieve of Erastosthenes ; Append the integer i if it is a prime ; Indicates current position in list of prime numbers ; Traverse the array arr [ ] ; If already filled with another prime number ; If A [ i ] is not filled but A [ ind ] is filled ; Store A [ i ] = A [ ind ] ; If none of them were filled ; To make sure A [ i ] does not affect other values , store next prime number ; Print the resultant array ; Driver Code ; Function Call
sieve = [ 1 ] * ( 1000000 + 1 ) NEW_LINE def sieveOfPrimes ( ) : NEW_LINE INDENT global sieve NEW_LINE N = 1000000 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT if ( sieve [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( i * i , N + 1 , i ) : NEW_LINE INDENT sieve [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT def getArray ( arr , N ) : NEW_LINE INDENT global sieve NEW_LINE A = [ 0 ] * N NEW_LINE v = [ ] NEW_LINE sieveOfPrimes ( ) NEW_LINE for i in range ( 2 , int ( 1e5 ) + 1 ) : NEW_LINE INDENT if ( sieve [ i ] ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT j = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT ind = arr [ i ] NEW_LINE if ( A [ i ] != 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( A [ ind ] != 0 ) : NEW_LINE INDENT A [ i ] = A [ ind ] NEW_LINE DEDENT else : NEW_LINE INDENT prime = v [ j ] NEW_LINE A [ i ] = prime NEW_LINE A [ ind ] = A [ i ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( A [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE getArray ( arr , N ) NEW_LINE DEDENT
Nth natural number after removing all numbers consisting of the digit 9 | Function to find Nth number in base 9 ; Stores the Nth number ; Iterate while N is greater than 0 ; Update result ; Divide N by 9 ; Multiply p by 10 ; Return result ; Driver Code
def findNthNumber ( N ) : NEW_LINE INDENT result = 0 NEW_LINE p = 1 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT result += ( p * ( N % 9 ) ) NEW_LINE N = N // 9 NEW_LINE p = p * 10 NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 9 NEW_LINE print ( findNthNumber ( N ) ) NEW_LINE DEDENT
Check if an integer is rotation of another given integer | Python3 implementation of the approach ; Function to check if the integer A is a rotation of the integer B ; Stores the count of digits in A ; Stores the count of digits in B ; If dig1 not equal to dig2 ; Stores position of first digit ; Stores the first digit ; Rotate the digits of the integer ; If A is equal to B ; If A is equal to the initial value of integer A ; Driver code
import math NEW_LINE def check ( A , B ) : NEW_LINE INDENT if ( A == B ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT dig1 = math . floor ( math . log10 ( A ) + 1 ) NEW_LINE dig2 = math . floor ( math . log10 ( B ) + 1 ) NEW_LINE if ( dig1 != dig2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT temp = A NEW_LINE while ( True ) : NEW_LINE INDENT power = pow ( 10 , dig1 - 1 ) NEW_LINE firstdigit = A // power NEW_LINE A = A - firstdigit * power NEW_LINE A = A * 10 + firstdigit NEW_LINE if ( A == B ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( A == temp ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT DEDENT A , B = 967 , 679 NEW_LINE if ( check ( A , B ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Count of quadruples with product of a pair equal to the product of the remaining pair | Function to count the number of unique quadruples from an array that satisfies the given condition ; Hashmap to store the product of pairs ; Store the count of required quadruples ; Traverse the array arr [ ] and generate all possible pairs ; Store their product ; Pair ( a , b ) can be used to generate 8 unique permutations with another pair ( c , d ) ; Increment umap [ prod ] by 1 ; Print the result ; Driver Code
def sameProductQuadruples ( nums , N ) : NEW_LINE INDENT umap = { } ; NEW_LINE res = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT prod = nums [ i ] * nums [ j ] ; NEW_LINE if prod in umap : NEW_LINE INDENT res += 8 * umap [ prod ] ; NEW_LINE umap [ prod ] += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT umap [ prod ] = 1 NEW_LINE DEDENT DEDENT DEDENT print ( res ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 6 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE sameProductQuadruples ( arr , N ) ; NEW_LINE DEDENT
Count ways to place M objects in distinct partitions of N boxes | Python3 implementation of the above Approach ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize Result ; Update x if x >= MOD to avoid multiplication overflow ; If y is odd , multiply x with result ; y = y / 2 ; Change x to x ^ 2 ; Utility function to find the Total Number of Ways ; Number of Even Indexed Boxes ; Number of partitions of Even Indexed Boxes ; Number of ways to distribute objects ; Driver Code ; N = number of boxes M = number of distinct objects ; Function call to get Total Number of Ways
MOD = 1000000007 NEW_LINE def power ( x , y , p = MOD ) : 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 totalWays ( N , M ) : NEW_LINE INDENT X = N // 2 NEW_LINE S = ( X * ( X + 1 ) ) % MOD NEW_LINE print ( power ( S , M , MOD ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , M = 5 , 2 NEW_LINE totalWays ( N , M ) NEW_LINE DEDENT
Check if a graph constructed from an array based on given conditions consists of a cycle or not | Function to check if the graph constructed from given array contains a cycle or not ; Traverse the array ; If arr [ i ] is less than arr [ i - 1 ] and arr [ i ] ; Driver Code ; Given array ; Size of the array
def isCycleExists ( arr , N ) : NEW_LINE INDENT valley = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i - 1 ] and arr [ i ] < arr [ i + 1 ] ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " No " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE isCycleExists ( arr , N ) NEW_LINE DEDENT
Maximize first array element by performing given operations at most K times | Function to maximize the first array element ; Traverse the array ; Initialize cur_val to a [ i ] ; If all operations are not over yet ; If current value is greater than zero ; Incrementing first element of array by 1 ; Decrementing current value of array by 1 ; Decrementing number of operations by i ; If current value is zero , then break ; Print first array element ; Driver Code ; Given array ; Size of the array ; Given K ; Prints the maximum possible value of the first array element
def getMax ( arr , N , K ) : NEW_LINE INDENT for i in range ( 1 , N , 1 ) : NEW_LINE INDENT cur_val = arr [ i ] NEW_LINE while ( K >= i ) : NEW_LINE INDENT if ( cur_val > 0 ) : NEW_LINE INDENT arr [ 0 ] = arr [ 0 ] + 1 NEW_LINE cur_val = cur_val - 1 NEW_LINE K = K - i NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT print ( arr [ 0 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 3 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE K = 5 NEW_LINE getMax ( arr , N , K ) NEW_LINE DEDENT
Count Non | Python3 program of the above approach ; Function to find the gcd of the two numbers ; Function to find distinct elements in the array by repeatidely inserting the absolute difference of all possible pairs ; Stores largest element of the array ; Traverse the array , arr [ ] ; Update max_value ; Stores GCD of array ; Update GCDArr ; Stores distinct elements in the array by repeatedely inserting absolute difference of all possible pairs ; Given array arr [ ]
import sys NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if a == 0 : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def DistinctValues ( arr , N ) : NEW_LINE INDENT max_value = - sys . maxsize - 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE max_value = max ( arr ) NEW_LINE GCDArr = arr [ 0 ] NEW_LINE INDENT GCDArr = gcd ( GCDArr , arr [ i ] ) NEW_LINE DEDENT answer = max_value // GCDArr NEW_LINE return answer + 1 NEW_LINE DEDENT arr = [ 4 , 12 , 16 , 24 ] NEW_LINE N = len ( arr ) NEW_LINE print ( DistinctValues ( arr , N ) ) NEW_LINE
Minimum row or column swaps required to make every pair of adjacent cell of a Binary Matrix distinct | Function to return number of moves to convert matrix into chessboard ; Size of the matrix ; Traverse the matrix ; Initialize rowSum to count 1 s in row ; Initialize colSum to count 1 s in column ; To store no . of rows to be corrected ; To store no . of columns to be corrected ; Traverse in the range [ 0 , N - 1 ] ; Check if rows is either N / 2 or ( N + 1 ) / 2 and return - 1 ; Check if rows is either N / 2 or ( N + 1 ) / 2 and return - 1 ; Check if N is odd ; Check if column required to be corrected is odd and then assign N - colSwap to colSwap ; Check if rows required to be corrected is odd and then assign N - rowSwap to rowSwap ; Take min of colSwap and N - colSwap ; Take min of rowSwap and N - rowSwap ; Finally return answer ; Driver Code ; Given matrix ; Function Call ; Print answer
def minSwaps ( b ) : NEW_LINE INDENT n = len ( b ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( b [ 0 ] [ 0 ] ^ b [ 0 ] [ j ] ^ b [ i ] [ 0 ] ^ b [ i ] [ j ] ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT DEDENT rowSum = 0 NEW_LINE colSum = 0 NEW_LINE rowSwap = 0 NEW_LINE colSwap = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT rowSum += b [ i ] [ 0 ] NEW_LINE colSum += b [ 0 ] [ i ] NEW_LINE rowSwap += b [ i ] [ 0 ] == i % 2 NEW_LINE colSwap += b [ 0 ] [ i ] == i % 2 NEW_LINE DEDENT if ( rowSum != n // 2 and rowSum != ( n + 1 ) // 2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( colSum != n // 2 and colSum != ( n + 1 ) // 2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( n % 2 == 1 ) : NEW_LINE INDENT if ( colSwap % 2 ) : NEW_LINE INDENT colSwap = n - colSwap NEW_LINE DEDENT if ( rowSwap % 2 ) : NEW_LINE INDENT rowSwap = n - rowSwap NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT colSwap = min ( colSwap , n - colSwap ) NEW_LINE rowSwap = min ( rowSwap , n - rowSwap ) NEW_LINE DEDENT return ( rowSwap + colSwap ) // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT M = [ [ 0 , 1 , 1 , 0 ] , [ 0 , 1 , 1 , 0 ] , [ 1 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 1 ] ] NEW_LINE ans = minSwaps ( M ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Minimum number of coins having value equal to powers of 2 required to obtain N | Function to count of set bit in N ; Stores count of set bit in N ; Iterate over the range [ 0 , 31 ] ; If current bit is set ; Update result ; Driver Code
def count_setbit ( N ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( 32 ) : NEW_LINE if ( ( 1 << i ) & N ) : NEW_LINE INDENT result = result + 1 NEW_LINE DEDENT print ( result ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 43 NEW_LINE count_setbit ( N ) NEW_LINE DEDENT
Evaluate the expression ( N1 * ( N | Python 3 program to implement the above approach ; Function to find the value of the expression ( N ^ 1 * ( N 1 ) ^ 2 * ... * 1 ^ N ) % ( 109 + 7 ) . ; factorial [ i ] : Stores factorial of i ; Base Case for factorial ; Precompute the factorial ; dp [ N ] : Stores the value of the expression ( N ^ 1 * ( N 1 ) ^ 2 * ... * 1 ^ N ) % ( 109 + 7 ) . ; Update dp [ i ] ; Return the answer . ; Driver Code ; Function call
mod = 1000000007 NEW_LINE def ValOfTheExpression ( n ) : NEW_LINE INDENT global mod NEW_LINE factorial = [ 0 for i in range ( n + 1 ) ] NEW_LINE factorial [ 0 ] = 1 NEW_LINE factorial [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT factorial [ i ] = ( ( factorial [ i - 1 ] % mod ) * ( i % mod ) ) % mod NEW_LINE DEDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE dp [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT dp [ i ] = ( ( dp [ i - 1 ] % mod ) * ( factorial [ i ] % mod ) ) % mod NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE print ( ValOfTheExpression ( n ) ) NEW_LINE DEDENT
Chocolate Distribution Problem | Set 2 | Function to print minimum number of candies required ; Distribute 1 chocolate to each ; Traverse from left to right ; Traverse from right to left ; Initialize sum ; Find total sum ; Return sum ; Driver Code ; Given array ; Size of the given array
def minChocolates ( A , N ) : NEW_LINE INDENT B = [ 1 for i in range ( N ) ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( A [ i ] > A [ i - 1 ] ) : NEW_LINE INDENT B [ i ] = B [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT B [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ i ] > A [ i + 1 ] ) : NEW_LINE INDENT B [ i ] = max ( B [ i + 1 ] + 1 , B [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT B [ i ] = max ( B [ i ] , 1 ) NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += B [ i ] NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 23 , 14 , 15 , 14 , 56 , 29 , 14 ] NEW_LINE N = len ( A ) NEW_LINE minChocolates ( A , N ) NEW_LINE DEDENT
Construct longest possible sequence of unique elements with given LCM | Python3 program to implement the above approach ; Function to construct an array of unique elements whose LCM is N ; Stores array elements whose LCM is N ; Iterate over the range [ 1 , sqrt ( N ) ] ; If N is divisible by i ; Insert i into newArr [ ] ; If N is not perfect square ; Sort the array newArr [ ] ; Print array elements ; Driver Code ; Given N ; Function Call
from math import sqrt , ceil , floor NEW_LINE def constructArrayWithGivenLCM ( N ) : NEW_LINE INDENT newArr = [ ] NEW_LINE for i in range ( 1 , ceil ( sqrt ( N + 1 ) ) ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT newArr . append ( i ) NEW_LINE if ( N // i != i ) : NEW_LINE INDENT newArr . append ( N // i ) NEW_LINE DEDENT DEDENT DEDENT newArr = sorted ( newArr ) NEW_LINE for i in newArr : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE constructArrayWithGivenLCM ( N ) NEW_LINE DEDENT
Count numbers from given range having odd digits at odd places and even digits at even places | Function to calculate 5 ^ p ; Stores the result ; Multiply 5 p times ; Return the result ; Function to count anumbers upto N having odd digits at odd places and even digits at even places ; Stores the count ; Stores the digits of N ; Insert the digits of N ; Reverse the vector to arrange the digits from first to last ; Stores count of digits of n ; Stores the count of numbers with i digits ; If the last digit is reached , subtract numbers eceeding range ; Iterate over athe places ; Stores the digit in the pth place ; Stores the count of numbers having a digit greater than x in the p - th position ; Calculate the count of numbers exceeding the range if p is even ; Calculate the count of numbers exceeding the range if p is odd ; Subtract the count of numbers exceeding the range from total count ; If the parity of p and the parity of x are not same ; Add count of numbers having i digits and satisfies the given conditions ; Return the total count of numbers tin ; Function to calculate the count of numbers from given range having odd digits places and even digits at even places ; Count of numbers in range [ L , R ] = Count of numbers tiR - ; Count of numbers ti ( L - 1 ) ; Driver Code
def getPower ( p ) : NEW_LINE INDENT res = 1 NEW_LINE while ( p ) : NEW_LINE INDENT res *= 5 NEW_LINE p -= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def countNumbersUtil ( N ) : NEW_LINE INDENT count = 0 NEW_LINE digits = [ ] NEW_LINE while ( N ) : NEW_LINE INDENT digits . append ( N % 10 ) NEW_LINE N //= 10 NEW_LINE DEDENT digits . reverse ( ) NEW_LINE D = len ( digits ) NEW_LINE for i in range ( 1 , D + 1 , 1 ) : NEW_LINE INDENT res = getPower ( i ) NEW_LINE if ( i == D ) : NEW_LINE INDENT for p in range ( 1 , D + 1 , 1 ) : NEW_LINE INDENT x = digits [ p - 1 ] NEW_LINE tmp = 0 NEW_LINE if ( p % 2 == 0 ) : NEW_LINE INDENT tmp = ( ( 5 - ( x // 2 + 1 ) ) * getPower ( D - p ) ) NEW_LINE DEDENT else : NEW_LINE INDENT tmp = ( ( 5 - ( x + 1 ) // 2 ) * getPower ( D - p ) ) NEW_LINE DEDENT res -= tmp NEW_LINE if ( p % 2 != x % 2 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT count += res NEW_LINE DEDENT return count NEW_LINE DEDENT def countNumbers ( L , R ) : NEW_LINE INDENT print ( countNumbersUtil ( R ) - countNumbersUtil ( L - 1 ) ) NEW_LINE DEDENT L = 128 NEW_LINE R = 162 NEW_LINE countNumbers ( L , R ) NEW_LINE
Sum of first N natural numbers with alternate signs | Function to find the sum of First N natural numbers with alternate signs ; Stores sum of alternate sign of First N natural numbers ; If is an even number ; Update alternateSum ; If i is an odd number ; Update alternateSum ; Driver Code
def alternatingSumOfFirst_N ( N ) : NEW_LINE INDENT alternateSum = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT alternateSum += - i NEW_LINE DEDENT else : NEW_LINE INDENT alternateSum += i NEW_LINE DEDENT DEDENT return alternateSum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE print ( alternatingSumOfFirst_N ( N ) ) NEW_LINE DEDENT
Sum of all numbers up to N that are co | Function to return gcd of a and b ; Base Case ; Recursive GCD ; Function to calculate the sum of all numbers till N that are coprime with N ; Stores the resultant sum ; Iterate over [ 1 , N ] ; If gcd is 1 ; Update sum ; Return the final sum ; Driver Code ; Given N ; Function Call
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b ; NEW_LINE DEDENT return gcd ( b % a , a ) ; NEW_LINE DEDENT def findSum ( N ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( gcd ( i , N ) == 1 ) : NEW_LINE INDENT sum += i ; NEW_LINE DEDENT DEDENT return sum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE print ( findSum ( N ) ) ; NEW_LINE DEDENT
Count all distinct pairs of repeating elements from the array for every array element | Function to prthe required count of pairs excluding the current element ; Store the frequency ; Find all the count ; Delete the contribution of each element for equal pairs ; Print the answer ; Driver Code ; Given array arr [ ] ; Function call
def solve ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in arr : NEW_LINE INDENT mp [ i ] = mp . get ( i , 0 ) + 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for x in mp : NEW_LINE INDENT cnt += ( ( mp [ x ] ) * ( mp [ x ] - 1 ) // 2 ) NEW_LINE DEDENT ans = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans [ i ] = cnt - ( mp [ arr [ i ] ] - 1 ) NEW_LINE DEDENT for i in ans : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE solve ( arr , N ) NEW_LINE DEDENT
Mode in a stream of integers ( running integers ) | Function that prints the Mode values ; Map used to mp integers to its frequency ; To store the maximum frequency ; To store the element with the maximum frequency ; Loop used to read the elements one by one ; Updates the frequency of that element ; Checks for maximum Number of occurrence ; Updates the maximum frequency ; Updates the Mode ; Driver Code ; Function call
def findMode ( a , n ) : NEW_LINE INDENT mp = { } NEW_LINE max = 0 NEW_LINE mode = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] in mp : NEW_LINE INDENT mp [ a [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ a [ i ] ] = 1 NEW_LINE DEDENT if ( mp [ a [ i ] ] >= max ) : NEW_LINE INDENT max = mp [ a [ i ] ] NEW_LINE mode = a [ i ] NEW_LINE DEDENT print ( mode , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 2 , 7 , 3 , 2 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE findMode ( arr , n ) NEW_LINE
Count of distinct numbers formed by shuffling the digits of a large number N | Recursive function to return the value of ( x ^ n ) % m ; Base Case ; If N is even ; Else N is odd ; Function to find modular inverse of a number x under modulo m ; Using Fermat 's little theorem ; Function to count of numbers formed by shuffling the digits of a large number N ; Modulo value ; Array to store the factorials upto the maximum value of N ; Store factorial of i at index i ; To store count of occurrence of a digit ; Increment the count of digit occured ; Assign the factorial of length of input ; Multiplying result with the modulo multiplicative inverse of factorial of count of i ; Print the result ; Given number as string ; Function call
def modexp ( x , n , m ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return modexp ( ( x * x ) % m , n / 2 , m ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( x * modexp ( ( x * x ) % m , ( n - 1 ) / 2 , m ) % m ) NEW_LINE DEDENT DEDENT DEDENT def modInverse ( x , m ) : NEW_LINE INDENT return modexp ( x , m - 2 , m ) NEW_LINE DEDENT def countNumbers ( N ) : NEW_LINE INDENT m = 1000000007 NEW_LINE factorial = [ 0 for x in range ( 100001 ) ] NEW_LINE factorial [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , 100001 ) : NEW_LINE INDENT factorial [ i ] = ( factorial [ i - 1 ] * i ) % m NEW_LINE DEDENT count = [ 0 for x in range ( 10 ) ] NEW_LINE for i in range ( 0 , 10 ) : NEW_LINE INDENT count [ i ] = 0 NEW_LINE DEDENT length = len ( N ) NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT count [ int ( N [ i ] ) ] += 1 NEW_LINE DEDENT result = factorial [ int ( length ) ] NEW_LINE for i in range ( 0 , 10 ) : NEW_LINE INDENT result = ( result * modInverse ( factorial [ int ( count [ i ] ) ] , m ) ) % m NEW_LINE DEDENT print ( result ) NEW_LINE DEDENT N = "0223" ; NEW_LINE countNumbers ( N ) NEW_LINE
Find prime factors of Array elements whose sum of exponents is divisible by K | To store the smallest prime factor till 10 ^ 5 ; Function to compute smallest prime factor array ; Initialize the spf array first element ; Marking smallest prime factor for every number to be itself ; Separately marking smallest prime factor for every even number as 2 ; Checking if i is prime ; Marking SPF for all numbers divisible by i ; Marking spf [ j ] if it is not previously marked ; Function that finds minimum operation ; Create a spf [ ] array ; Map created to store the unique prime numbers ; To store the result ; To store minimum operations ; To store every unique prime number ; Erase 1 as a key because it is not a prime number ; First Prime Number ; Frequency is divisible by K then insert primeNum in the result [ ] ; Print the elements if it exists ; Driver Code ; Given array arr [ ] ; Given K ; Function Call
spf = [ 0 for i in range ( 10001 ) ] NEW_LINE def spf_array ( spf ) : NEW_LINE INDENT spf [ 1 ] = 1 NEW_LINE for i in range ( 2 , 1000 , 1 ) : NEW_LINE INDENT spf [ i ] = i NEW_LINE DEDENT for i in range ( 4 , 1000 , 2 ) : NEW_LINE INDENT spf [ i ] = 2 NEW_LINE DEDENT i = 3 NEW_LINE while ( i * i < 1000 ) : NEW_LINE INDENT if ( spf [ i ] == i ) : NEW_LINE INDENT j = i * i NEW_LINE while ( j < 1000 ) : NEW_LINE INDENT if ( spf [ j ] == j ) : NEW_LINE INDENT spf [ j ] = i NEW_LINE DEDENT j += i NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def frequent_prime ( arr , N , K ) : NEW_LINE INDENT spf_array ( spf ) NEW_LINE Hmap = { } NEW_LINE result = [ ] NEW_LINE i = 0 NEW_LINE c = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = arr [ i ] NEW_LINE while ( x != 1 ) : NEW_LINE INDENT Hmap [ spf [ x ] ] = Hmap . get ( spf [ x ] , 0 ) + 1 NEW_LINE x = x // spf [ x ] NEW_LINE DEDENT DEDENT if ( 1 in Hmap ) : NEW_LINE Hmap . pop ( 1 ) NEW_LINE for key , value in Hmap . items ( ) : NEW_LINE INDENT primeNum = key NEW_LINE frequency = value NEW_LINE if ( frequency % K == 0 ) : NEW_LINE INDENT result . append ( primeNum ) NEW_LINE DEDENT DEDENT result = result [ : : - 1 ] NEW_LINE if ( len ( result ) > 0 ) : NEW_LINE INDENT for it in result : NEW_LINE INDENT print ( it , end = " ▁ " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " { } " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 6 ] NEW_LINE K = 1 NEW_LINE N = len ( arr ) NEW_LINE frequent_prime ( arr , N , K ) NEW_LINE DEDENT
Generate first K multiples of N using Bitwise operators | Function to print the first K multiples of N ; Print the value of N * i ; Iterate each bit of N and add pow ( 2 , pos ) , where pos is the index of each set bit ; Check if current bit at pos j is fixed or not ; For next set bit ; Driver Code
def Kmultiples ( n , k ) : NEW_LINE INDENT a = n NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT print ( " { } ▁ * ▁ { } ▁ = ▁ { } " . format ( n , i , a ) ) NEW_LINE j = 0 NEW_LINE while ( n >= ( 1 << j ) ) : NEW_LINE INDENT a += n & ( 1 << j ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT N = 16 NEW_LINE K = 7 NEW_LINE Kmultiples ( N , K ) NEW_LINE
Least Square Regression Line | Function to calculate b ; sum of array x ; sum of array y ; for sum of product of x and y ; sum of square of x ; Function to find the least regression line ; Finding b ; Calculating a ; Printing regression line ; Statistical data
def calculateB ( x , y , n ) : NEW_LINE INDENT sx = sum ( x ) NEW_LINE sy = sum ( y ) NEW_LINE sxsy = 0 NEW_LINE sx2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sxsy += x [ i ] * y [ i ] NEW_LINE sx2 += x [ i ] * x [ i ] NEW_LINE DEDENT b = ( n * sxsy - sx * sy ) / ( n * sx2 - sx * sx ) NEW_LINE return b NEW_LINE DEDENT def leastRegLine ( X , Y , n ) : NEW_LINE INDENT b = calculateB ( X , Y , n ) NEW_LINE meanX = int ( sum ( X ) / n ) NEW_LINE meanY = int ( sum ( Y ) / n ) NEW_LINE a = meanY - b * meanX NEW_LINE print ( " Regression ▁ line : " ) NEW_LINE print ( " Y ▁ = ▁ " , ' % .3f ' % a , " ▁ + ▁ " , ' % .3f ' % b , " * X " , sep = " " ) NEW_LINE DEDENT X = [ 95 , 85 , 80 , 70 , 60 ] NEW_LINE Y = [ 90 , 80 , 70 , 65 , 60 ] NEW_LINE n = len ( X ) NEW_LINE leastRegLine ( X , Y , n ) NEW_LINE
Count of repeating digits in a given Number | Function that returns the count of repeating digits of the given number ; Initialize a variable to store count of Repeating digits ; Initialize cnt array to store digit count ; Iterate through the digits of N ; Retrieve the last digit of N ; Increase the count of digit ; Remove the last digit of N ; Iterate through the cnt array ; If frequency of digit is greater than 1 ; Increment the count of Repeating digits ; Return count of repeating digit ; Given array arr [ ] ; Function call
def countRepeatingDigits ( N ) : NEW_LINE INDENT res = 0 NEW_LINE cnt = [ 0 ] * 10 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT rem = N % 10 NEW_LINE cnt [ rem ] += 1 NEW_LINE N = N // 10 NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT if ( cnt [ i ] > 1 ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT N = 12 NEW_LINE print ( countRepeatingDigits ( N ) ) NEW_LINE
Find temperature of missing days using given sum and average | Function for finding the temperature ; Store Day1 - Day2 in diff ; Remaining from s will be Day1 ; Print Day1 and Day2 ; Driver Code ; Functions
def findTemperature ( x , y , s ) : NEW_LINE INDENT diff = ( x - y ) * 6 NEW_LINE Day2 = ( diff + s ) // 2 NEW_LINE Day1 = s - Day2 NEW_LINE print ( " Day1 ▁ : ▁ " , Day1 ) NEW_LINE print ( " Day2 ▁ : ▁ " , Day2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 5 NEW_LINE y = 10 NEW_LINE s = 40 NEW_LINE findTemperature ( x , y , s ) NEW_LINE DEDENT
Find two numbers whose sum is N and does not contain any digit as K | Function to find two numbers whose sum is N and do not contain any digit as k ; Check every number i and ( n - i ) ; Check if i and n - i doesn 't contain k in them print i and n-i ; check if flag is 0 then print - 1 ; Driver Code ; Given N and K ; Function Call
def findAandB ( n , k ) : NEW_LINE INDENT flag = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if str ( i ) . count ( chr ( k + 48 ) ) == 0 and str ( n - i ) . count ( chr ( k + 48 ) ) == 0 : NEW_LINE INDENT print ( i , n - i ) NEW_LINE flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 100 NEW_LINE K = 0 NEW_LINE findAandB ( N , K ) NEW_LINE DEDENT
Find the value of P and modular inverse of Q modulo 998244353 | Function to find the value of P * Q ^ - 1 mod 998244353 ; Loop to find the value until the expo is not zero ; Multiply p with q if expo is odd ; Reduce the value of expo by 2 ; Driver code ; Function call
def calculate ( p , q ) : NEW_LINE INDENT mod = 998244353 NEW_LINE expo = 0 NEW_LINE expo = mod - 2 NEW_LINE while ( expo ) : NEW_LINE INDENT if ( expo & 1 ) : NEW_LINE INDENT p = ( p * q ) % mod NEW_LINE DEDENT q = ( q * q ) % mod NEW_LINE expo >>= 1 NEW_LINE DEDENT return p NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT p = 1 NEW_LINE q = 4 NEW_LINE print ( calculate ( p , q ) ) NEW_LINE DEDENT
Find two numbers with given sum and maximum possible LCM | Function that print two numbers with the sum X and maximum possible LCM ; If X is odd ; If X is even ; If floor ( X / 2 ) is even ; If floor ( X / 2 ) is odd ; Print the result ; Driver Code ; Given Number ; Function call
def maxLCMWithGivenSum ( X ) : NEW_LINE INDENT if X % 2 != 0 : NEW_LINE INDENT A = X / 2 NEW_LINE B = X / 2 + 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( X / 2 ) % 2 == 0 : NEW_LINE INDENT A = X / 2 - 1 NEW_LINE B = X / 2 + 1 NEW_LINE DEDENT else : NEW_LINE INDENT A = X / 2 - 2 NEW_LINE B = X / 2 + 2 NEW_LINE DEDENT DEDENT print ( int ( A ) , int ( B ) , end = " ▁ " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 30 NEW_LINE maxLCMWithGivenSum ( X ) NEW_LINE DEDENT
Length of longest subarray whose sum is not divisible by integer K | Function to find the longest subarray with sum is not divisible by k ; left is the index of the leftmost element that is not divisible by k ; sum of the array ; Find the element that is not multiple of k ; left = - 1 means we are finding the leftmost element that is not divisible by k ; Updating the rightmost element ; Update the sum of the array up to the index i ; Check if the sum of the array is not divisible by k , then return the size of array ; All elements of array are divisible by k , then no such subarray possible so return - 1 ; length of prefix elements that can be removed ; length of suffix elements that can be removed ; Return the length of subarray after removing the elements which have lesser number of elements ; Driver Code
def MaxSubarrayLength ( arr , n , k ) : NEW_LINE INDENT left = - 1 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( arr [ i ] % k ) != 0 ) : NEW_LINE INDENT if ( left == - 1 ) : NEW_LINE INDENT left = i NEW_LINE DEDENT right = i NEW_LINE DEDENT sum += arr [ i ] NEW_LINE DEDENT if ( ( sum % k ) != 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT elif ( left == - 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT prefix_length = left + 1 NEW_LINE suffix_length = n - right NEW_LINE return n - min ( prefix_length , suffix_length ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 3 , 12 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( MaxSubarrayLength ( arr , n , K ) ) NEW_LINE DEDENT
Minimum steps to convert X to Y by repeated division and multiplication | Python3 implementation to find minimum steps to convert X to Y by repeated division and multiplication ; Check if X is greater than Y then swap the elements ; Check if X equals Y ; Driver code
def solve ( X , Y ) : NEW_LINE INDENT if ( X > Y ) : NEW_LINE INDENT temp = X NEW_LINE X = Y NEW_LINE Y = temp NEW_LINE DEDENT if ( X == Y ) : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT elif ( Y % X == 0 ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 2 ) NEW_LINE DEDENT DEDENT X = 8 NEW_LINE Y = 13 NEW_LINE solve ( X , Y ) NEW_LINE
Count quadruplets ( A , B , C , D ) till N such that sum of square of A and B is equal to that of C and D | Python3 program for the above approach ; Function to count the quadruples ; Counter variable ; Map to store the sum of pair ( a ^ 2 + b ^ 2 ) ; Iterate till N ; Calculate a ^ 2 + b ^ 2 ; Increment the value in map ; Check if this sum was also in a ^ 2 + b ^ 2 ; Return the count ; Driver Code ; Given N ; Function Call
from collections import defaultdict NEW_LINE def countQuadraples ( N ) : NEW_LINE INDENT cnt = 0 NEW_LINE m = defaultdict ( int ) NEW_LINE for a in range ( 1 , N + 1 ) : NEW_LINE INDENT for b in range ( 1 , N + 1 ) : NEW_LINE INDENT x = a * a + b * b NEW_LINE m [ x ] += 1 NEW_LINE DEDENT DEDENT for c in range ( 1 , N + 1 ) : NEW_LINE INDENT for d in range ( 1 , N + 1 ) : NEW_LINE INDENT x = c * c + d * d NEW_LINE if x in m : NEW_LINE INDENT cnt += m [ x ] NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE print ( countQuadraples ( N ) ) NEW_LINE DEDENT
Count of distinct index pair ( i , j ) such that element sum of First Array is greater | Python3 program of the above approach ; Function to find the number of pairs . ; Array c [ ] where c [ i ] = a [ i ] - b [ i ] ; Sort the array c ; Initialise answer as 0 ; Iterate from index 0 to n - 1 ; If c [ i ] <= 0 then in the sorted array c [ i ] + c [ pos ] can never greater than 0 where pos < i ; Find the minimum index such that c [ i ] + c [ j ] > 0 which is equivalent to c [ j ] >= - c [ i ] + 1 ; Add ( i - pos ) to answer ; Return the answer ; Driver code ; Number of elements in a and b ; Array a ; Array b
from bisect import bisect_left NEW_LINE def numberOfPairs ( a , b , n ) : NEW_LINE INDENT c = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT c [ i ] = a [ i ] - b [ i ] NEW_LINE DEDENT c = sorted ( c ) NEW_LINE answer = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( c [ i ] <= 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT pos = bisect_left ( c , - c [ i ] + 1 ) NEW_LINE answer += ( i - pos ) NEW_LINE DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE a = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE b = [ 2 , 5 , 6 , 1 , 9 ] NEW_LINE print ( numberOfPairs ( a , b , n ) ) NEW_LINE DEDENT
Find K for every Array element such that at least K prefixes are Γ’ ‰Β₯ K | Function to find the K - value for every index in the array ; Multiset to store the array in the form of red - black tree ; Iterating over the array ; Inserting the current value in the multiset ; Condition to check if the smallest value in the set is less than it 's size ; Erase the smallest value ; h - index value will be the size of the multiset ; Driver Code ; Array ; Size of the array ; Function call
def print_h_index ( arr , N ) : NEW_LINE INDENT ms = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT ms . append ( arr [ i ] ) NEW_LINE ms . sort ( ) NEW_LINE if ( ms [ 0 ] < len ( ms ) ) : NEW_LINE INDENT ms . pop ( 0 ) NEW_LINE DEDENT print ( len ( ms ) , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 10 , 7 , 5 , 0 , 10 , 2 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE print_h_index ( arr , N ) NEW_LINE DEDENT
Non | Function to find count of prime ; Find maximum value in the array ; Find and store all prime numbers up to max_val using Sieve Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to print Non - repeating primes ; Precompute primes using Sieve ; Create HashMap to store frequency of prime numbers ; Traverse through array elements and Count frequencies of all primes ; Traverse through map and print non repeating primes ; Driver code
def findPrimes ( arr , n ) : NEW_LINE INDENT max_val = max ( arr ) NEW_LINE prime = [ True for i in range ( max_val + 1 ) ] NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while ( p * p <= max_val ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , max_val + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT return prime ; NEW_LINE DEDENT def nonRepeatingPrimes ( arr , n ) : NEW_LINE INDENT prime = findPrimes ( arr , n ) ; NEW_LINE mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( prime [ arr [ i ] ] ) : NEW_LINE INDENT if ( arr [ i ] in mp ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT DEDENT for entry in mp . keys ( ) : NEW_LINE INDENT if ( mp [ entry ] == 1 ) : NEW_LINE INDENT print ( entry ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 6 , 7 , 9 , 7 , 23 , 21 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE nonRepeatingPrimes ( arr , n ) ; NEW_LINE DEDENT
Prefix Product Array | Function to generate prefix product array ; Update the array with the product of prefixes ; Print the array ; Driver Code
def prefixProduct ( a , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT a [ i ] = a [ i ] * a [ i - 1 ] ; NEW_LINE DEDENT for j in range ( 0 , n ) : NEW_LINE INDENT print ( a [ j ] , end = " , ▁ " ) ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT arr = [ 2 , 4 , 6 , 5 , 10 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE prefixProduct ( arr , N ) ; NEW_LINE
Count of ways to distribute N items among 3 people with one person receiving maximum | Function to find the number of ways to distribute N items among 3 people ; No distribution possible ; Total number of ways to distribute N items among 3 people ; Store the number of distributions which are not possible ; Count possibilities of two persons receiving the maximum ; If N is divisible by 3 ; Return the final count of ways to distribute ; Driver Code
def countWays ( N ) : NEW_LINE INDENT if ( N < 4 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = ( ( N - 1 ) * ( N - 2 ) ) // 2 NEW_LINE s = 0 NEW_LINE for i in range ( 2 , N - 2 , 1 ) : NEW_LINE INDENT for j in range ( 1 , i , 1 ) : NEW_LINE INDENT if ( N == 2 * i + j ) : NEW_LINE INDENT s += 1 NEW_LINE DEDENT DEDENT DEDENT if ( N % 3 == 0 ) : NEW_LINE INDENT s = 3 * s + 1 NEW_LINE DEDENT else : NEW_LINE INDENT s = 3 * s NEW_LINE DEDENT return ans - s NEW_LINE DEDENT N = 10 NEW_LINE print ( countWays ( N ) ) NEW_LINE
Magnanimous Numbers | Function to check if n is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to check if the number is Magnanimous or not ; Converting the number to string ; Finding length of string ; Number should not be of single digit ; Loop to find all left and right part of the string ; 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 = i + 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def isMagnanimous ( N ) : NEW_LINE INDENT s = str ( N ) NEW_LINE l = len ( s ) NEW_LINE if ( l < 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( l - 1 ) : NEW_LINE INDENT left = s [ 0 : i + 1 ] NEW_LINE right = s [ i + 1 : ] NEW_LINE x = int ( left ) NEW_LINE y = int ( right ) NEW_LINE if ( not isPrime ( x + y ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT N = 12 NEW_LINE if isMagnanimous ( N ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Honaker Prime Number | Python3 program for the above approach ; 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 ; Function to get sum of digits ; Function to check whether the given number is Honaker Prime number or not ; Precompute the prime numbers till 10 ^ 6 ; Given Number ; Function Call
limit = 10000000 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 def getSum ( n ) : NEW_LINE INDENT Sum = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT Sum = Sum + n % 10 NEW_LINE n = n // 10 NEW_LINE DEDENT return Sum NEW_LINE DEDENT def isHonakerPrime ( n ) : NEW_LINE INDENT pos = position [ n ] NEW_LINE if ( pos == - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return bool ( getSum ( n ) == getSum ( pos ) ) NEW_LINE DEDENT sieve ( ) NEW_LINE N = 121 NEW_LINE if ( isHonakerPrime ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Check if Matrix sum is prime or not | Python3 implementation to check if the sum of matrix is prime or not ; Function to check whether a number is prime or not ; Corner case ; Check from 2 to n - 1 ; Function for to find the sum of the given matrix ; Driver Code
import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( 2 , ( int ) ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def takeSum ( a ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( 0 , 4 ) : NEW_LINE INDENT for j in range ( 0 , 5 ) : NEW_LINE INDENT s += a [ i ] [ j ] NEW_LINE DEDENT DEDENT return s ; NEW_LINE DEDENT a = [ [ 1 , 2 , 3 , 4 , 2 ] , [ 0 , 1 , 2 , 3 , 34 ] , [ 0 , 34 , 21 , 12 , 12 ] , [ 1 , 2 , 3 , 6 , 6 ] ] ; NEW_LINE sum = takeSum ( a ) ; NEW_LINE if ( isPrime ( sum ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
Sum of sum | Function to find the sum ; Calculate sum - series for every natural number and add them ; Driver code
def sumOfSumSeries ( N ) : NEW_LINE INDENT _sum = 0 NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT _sum = _sum + ( i * ( i + 1 ) ) // 2 NEW_LINE DEDENT return _sum NEW_LINE DEDENT N = 5 NEW_LINE print ( sumOfSumSeries ( N ) ) NEW_LINE
Sum of sum | Function to find the sum ; Driver code
def sumOfSumSeries ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) * ( n + 2 ) ) // 6 NEW_LINE DEDENT N = 5 NEW_LINE print ( sumOfSumSeries ( N ) ) NEW_LINE
Tetradic Primes | Function to check if the number N having all digits lies in the set ( 0 , 1 , 8 ) ; Function to check if the number N is palindrome ; Function to check if a number N is Tetradic ; Function to generate all primes and checking whether number is Tetradic or not ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Print all Tetradic prime numbers ; checking whether the given number is prime Tetradic or not ; Driver Code
def isContaindigit ( n ) : NEW_LINE INDENT temp = str ( n ) NEW_LINE for i in temp : NEW_LINE INDENT if i not in [ '0' , '1' , '8' ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def ispalindrome ( n ) : NEW_LINE INDENT temp = str ( n ) NEW_LINE if temp == temp [ : : - 1 ] : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def isTetradic ( n ) : NEW_LINE INDENT if ispalindrome ( n ) : NEW_LINE INDENT if isContaindigit ( n ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def printTetradicPrimesLessThanN ( n ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT p += 1 ; NEW_LINE DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ p ] and isTetradic ( p ) ) : NEW_LINE INDENT print ( p , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT n = 1000 ; NEW_LINE printTetradicPrimesLessThanN ( n ) ; NEW_LINE
Astonishing Numbers | Function to concatenate two integers into one ; Convert both the integers to string ; Concatenate both strings ; Convert the concatenated string to integer ; return the formed integer ; Function to check if N is a Astonishing number ; Loop to find sum of all integers from i till the sum becomes >= n ; variable to store sum of all integers from i to j and check if sum and concatenation equals n or not ; finding concatenation of i and j ; condition for Astonishing number ; Given Number ; Function Call
def concat ( a , b ) : NEW_LINE INDENT s1 = str ( a ) NEW_LINE s2 = str ( b ) NEW_LINE s = s1 + s2 NEW_LINE c = int ( s ) NEW_LINE return c NEW_LINE DEDENT def isAstonishing ( n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT sum += j NEW_LINE if ( sum == n ) : NEW_LINE INDENT concatenation = concat ( i , j ) NEW_LINE if ( concatenation == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT DEDENT return False NEW_LINE DEDENT n = 429 NEW_LINE if ( isAstonishing ( n ) ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT
Digitally balanced numbers | Function to check if the digits in the number is the same number of digits ; Loop to iterate over the digits of the number N ; Loop to iterate over the map ; Driver code ; Function to check
def checkSame ( n , b ) : NEW_LINE INDENT m = { } NEW_LINE while ( n != 0 ) : NEW_LINE INDENT r = n % b NEW_LINE n = n // b NEW_LINE if r in m : NEW_LINE INDENT m [ r ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ r ] = 1 NEW_LINE DEDENT DEDENT last = - 1 NEW_LINE for i in m : NEW_LINE INDENT if last != - 1 and m [ i ] != last : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT last = m [ i ] NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT n = 9 NEW_LINE base = 2 NEW_LINE if ( checkSame ( n , base ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
Sum of series formed by difference between product and sum of N natural numbers | Function to calculate the sum upto Nth term ; Stores the sum of the series ; Stores the product of natural numbers upto the current term ; Stores the sum of natural numbers upto the upto current term ; Generate the remaining terms and calculate sum ; Update the sum ; Return the sum ; Driver Code
def seriesSum ( n ) : NEW_LINE INDENT sum1 = 0 ; NEW_LINE currProd = 1 ; NEW_LINE currSum = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT currProd *= i ; NEW_LINE currSum += i ; NEW_LINE sum1 += currProd - currSum ; NEW_LINE DEDENT return sum1 ; NEW_LINE DEDENT N = 5 ; NEW_LINE print ( seriesSum ( N ) , end = " ▁ " ) ; NEW_LINE
Count of elements not divisible by any other elements of Array | Function to count the number of elements of array which are not divisible by any other element in the array arr [ ] ; Iterate over the array ; Check if the element is itself or not ; Check for divisibility ; Return the final result ; Driver Code ; Given array ; Function Call
def count ( a , n ) : NEW_LINE INDENT countElements = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT flag = True NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( a [ i ] % a [ j ] == 0 ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == True ) : NEW_LINE INDENT countElements += 1 NEW_LINE DEDENT DEDENT return countElements NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 86 , 45 , 18 , 4 , 8 , 28 , 19 , 33 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( count ( arr , n ) ) NEW_LINE DEDENT
Smallest N digit number divisible by N | Python3 program for the above approach ; Function to find the smallest N - digit number divisible by N ; Return the smallest N - digit number calculated using above formula ; Given N ; Function Call
import math NEW_LINE def smallestNumber ( N ) : NEW_LINE INDENT return N * math . ceil ( pow ( 10 , ( N - 1 ) ) // N ) ; NEW_LINE DEDENT N = 2 ; NEW_LINE print ( smallestNumber ( N ) ) ; NEW_LINE
Count pairs in an array containing at least one even value | Function to count the pairs in the array such as there is at least one even element in each pair ; Generate all possible pairs and increment then count if the condition is satisfied ; Driver code ; Function call
def CountPairs ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 or arr [ j ] % 2 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 8 , 2 , 3 , 1 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( CountPairs ( arr , n ) ) NEW_LINE
Count pairs in an array containing at least one even value | Function to count the pairs in the array such as there is at least one even element in each pair ; Store count of even and odd elements ; Check element is even or odd ; Driver Code
def CountPairs ( arr , n ) : NEW_LINE INDENT even = 0 NEW_LINE odd = 0 NEW_LINE for i in range ( n ) : NEW_LINE if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT even += 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT return ( ( even * ( even - 1 ) ) // 2 + ( even * odd ) ) NEW_LINE DEDENT arr = [ 8 , 2 , 3 , 1 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( CountPairs ( arr , n ) ) NEW_LINE
Giuga Numbers | Python program for the above approach ; Function to check if n is a composite number ; Corner cases ; This is checked to skip middle 5 numbers ; Function to check if N is a Giuga Number ; N should be composite to be a Giuga Number ; Print the number of 2 s that divide n ; N must be odd at this point . So we can skip one element ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number > 2 ; Given Number N ; Function Call
import math NEW_LINE def isComposite ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT i += 6 NEW_LINE DEDENT return False NEW_LINE DEDENT def isGiugaNum ( n ) : NEW_LINE INDENT if ( not ( isComposite ( n ) ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT N = n NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT if ( ( int ( N / 2 ) - 1 ) % 2 != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = int ( 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 if ( ( int ( N / i ) - 1 ) % i != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = int ( n / i ) NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT if ( ( int ( N / n ) - 1 ) % n != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT n = 30 NEW_LINE if ( isGiugaNum ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Droll Numbers | Python3 program for the above approach ; Function to check droll numbers ; To store sum of even prime factors ; To store sum of odd prime factors ; Add the number of 2 s that divide n in sum_even ; N must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Condition to check droll number ; Given Number N ; Function Call
import math ; NEW_LINE def isDroll ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT sum_even = 0 ; NEW_LINE sum_odd = 0 ; NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT sum_even += 2 ; 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 sum_odd += i ; NEW_LINE n = n // i ; NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT sum_odd += n ; NEW_LINE DEDENT return sum_even == sum_odd ; NEW_LINE DEDENT N = 72 ; NEW_LINE if ( isDroll ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT
Count all pairs of divisors of a number N whose sum is coprime with N | Python3 program to count all pairs of divisors such that their sum is coprime with N ; Function to count all valid pairs ; initialize count ; Check if sum of pair and n are coprime ; Return the result ; Driver code
import math as m NEW_LINE def CountPairs ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE i = 1 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT div1 = i NEW_LINE div2 = n // i NEW_LINE sum = div1 + div2 ; NEW_LINE if ( m . gcd ( sum , n ) == 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return cnt NEW_LINE DEDENT n = 24 NEW_LINE print ( CountPairs ( n ) ) NEW_LINE
Check if A can be converted to B by reducing with a Prime number | Function to find if it is possible to make A equal to B ; Driver Code ; Function Call
def isPossible ( A , B ) : NEW_LINE INDENT return ( A - B > 1 ) ; NEW_LINE DEDENT A = 10 ; B = 4 ; NEW_LINE if ( isPossible ( A , B ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT
Maximize sum of minimum difference of divisors of nodes in N | Python3 program to maximize the sum of minimum difference of divisors of nodes in an n - ary tree ; Array to store the result at each node ; Function to get minimum difference between the divisors of a number ; Iterate from square root of N to N ; Return absolute difference ; DFS function to calculate the maximum sum ; Store the min difference ; Add the maximum of all children to sub [ u ] ; Return maximum sum of node ' u ' to its parent ; Driver code
import math NEW_LINE sub = [ 0 for i in range ( 100005 ) ] NEW_LINE def minDivisorDifference ( n ) : NEW_LINE INDENT num1 = 0 NEW_LINE num2 = 0 NEW_LINE for i in range ( int ( math . sqrt ( n ) ) , n + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT num1 = i NEW_LINE num2 = n // i NEW_LINE break NEW_LINE DEDENT DEDENT return abs ( num1 - num2 ) NEW_LINE DEDENT def dfs ( g , u , par ) : NEW_LINE INDENT sub [ u ] = minDivisorDifference ( u ) NEW_LINE mx = 0 NEW_LINE for c in g [ u ] : NEW_LINE INDENT if ( c != par ) : NEW_LINE INDENT ans = dfs ( g , c , u ) NEW_LINE mx = max ( mx , ans ) NEW_LINE DEDENT DEDENT sub [ u ] += mx NEW_LINE return sub [ u ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT g = [ [ ] for i in range ( 100005 ) ] NEW_LINE edges = 6 NEW_LINE g [ 18 ] . append ( 7 ) NEW_LINE g [ 7 ] . append ( 18 ) NEW_LINE g [ 18 ] . append ( 15 ) NEW_LINE g [ 15 ] . append ( 18 ) NEW_LINE g [ 15 ] . append ( 2 ) NEW_LINE g [ 2 ] . append ( 15 ) NEW_LINE g [ 7 ] . append ( 4 ) NEW_LINE g [ 4 ] . append ( 7 ) NEW_LINE g [ 7 ] . append ( 12 ) NEW_LINE g [ 12 ] . append ( 7 ) NEW_LINE g [ 12 ] . append ( 9 ) NEW_LINE g [ 9 ] . append ( 12 ) NEW_LINE root = 18 NEW_LINE print ( dfs ( g , root , - 1 ) ) NEW_LINE DEDENT
Program to check if N is a Centered Cubic Number | Function to check if N is a centered cubic number ; Iterating from 1 ; Infinite loop ; Finding ith_term ; Checking if the number N is a centered cube number ; If ith_term > N then N is not a centered cube number ; Incrementing i ; Driver code ; Function call
def isCenteredcube ( N ) : NEW_LINE INDENT i = 1 ; NEW_LINE while ( True ) : NEW_LINE INDENT ith_term = ( ( 2 * i + 1 ) * ( i * i + i + 1 ) ) ; NEW_LINE if ( ith_term == N ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( ith_term > N ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT DEDENT N = 9 ; NEW_LINE if ( isCenteredcube ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT
Product of N terms of a given Geometric series | Function to calculate product of geometric series ; Initialise final product with 1 ; Multiply product with each term stored in a ; Return the final product ; Given first term and common ratio ; Number of terms ; Function Call
def productOfGP ( a , r , n ) : NEW_LINE INDENT product = 1 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT product = product * a ; NEW_LINE a = a * r ; NEW_LINE DEDENT return product ; NEW_LINE DEDENT a = 1 NEW_LINE r = 2 ; NEW_LINE N = 4 ; NEW_LINE print ( productOfGP ( a , r , N ) ) NEW_LINE
Sum of given N fractions in reduced form | Function to find GCD of a & b using Euclid Lemma ; Base Case ; Function to find the LCM of all elements in arr [ ] ; Initialize result ; Iterate arr [ ] to find LCM ; Return the final LCM ; Function to find the sum of N fraction in reduced form ; To store the sum of all final numerators ; Find the LCM of all denominator ; Find the sum of all N numerators & denominators ; Add each fraction one by one ; Find GCD of final numerator and denominator ; Convert into reduced form by dividing from GCD ; Print the final fraction ; Given N ; Given Numerator ; Given Denominator ; 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 findlcm ( arr , n ) : NEW_LINE INDENT ans = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ans = ( ( ( arr [ i ] * ans ) ) // ( gcd ( arr [ i ] , ans ) ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def addReduce ( n , num , den ) : NEW_LINE INDENT final_numerator = 0 NEW_LINE final_denominator = findlcm ( den , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT final_numerator = ( final_numerator + ( num [ i ] ) * ( final_denominator // den [ i ] ) ) NEW_LINE DEDENT GCD = gcd ( final_numerator , final_denominator ) NEW_LINE final_numerator //= GCD NEW_LINE final_denominator //= GCD NEW_LINE print ( final_numerator , " / " , final_denominator ) NEW_LINE DEDENT N = 3 NEW_LINE arr1 = [ 1 , 2 , 5 ] NEW_LINE arr2 = [ 2 , 1 , 6 ] NEW_LINE addReduce ( N , arr1 , arr2 ) NEW_LINE
Minimum LCM of all pairs in a given array | Python3 program to find minimum possible lcm from any pair ; Function to compute GCD of two numbers ; Function that return minimum possible lcm from any pair ; Fix the ith element and iterate over all the array to find minimum LCM ; Driver code
import sys NEW_LINE 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 minLCM ( arr , n ) : NEW_LINE INDENT ans = 1000000000 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT g = gcd ( arr [ i ] , arr [ j ] ) ; NEW_LINE lcm = arr [ i ] / g * arr [ j ] ; NEW_LINE ans = min ( ans , lcm ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT arr = [ 2 , 4 , 3 , 6 , 5 ] ; NEW_LINE print ( minLCM ( arr , 5 ) ) NEW_LINE
Find two numbers whose difference of fourth power is equal to N | Python3 implementation to find the values of x and y for the given equation with integer N ; Function which find required x & y ; Upper limit of x & y , if such x & y exists ; num1 stores x ^ 4 ; num2 stores y ^ 4 ; If condition is satisfied the print and return ; If no such pair exists ; Driver code
from math import pow , ceil NEW_LINE def solve ( n ) : NEW_LINE INDENT upper_limit = ceil ( pow ( n , 1.0 / 4 ) ) ; NEW_LINE for x in range ( upper_limit + 1 ) : NEW_LINE INDENT for y in range ( upper_limit + 1 ) : NEW_LINE INDENT num1 = x * x * x * x ; NEW_LINE num2 = y * y * y * y ; NEW_LINE if ( num1 - num2 == n ) : NEW_LINE INDENT print ( " x ▁ = " , x , " , ▁ y ▁ = " , y ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT DEDENT print ( - 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 15 ; NEW_LINE solve ( n ) ; NEW_LINE DEDENT
Check if count of even divisors of N is equal to count of odd divisors | Python3 program for the above approach ; Function to check if count of even and odd divisors are equal ; To store the count of even factors and odd factors ; Loop till [ 1 , sqrt ( N ) ] ; If divisors are equal add only one ; Check for even divisor ; Odd divisor ; Check for both divisor i . e . , i and N / i ; Check if i is odd or even ; Check if N / i is odd or even ; Return true if count of even_div and odd_div are equals ; Given Number ; Function Call
import math NEW_LINE def divisorsSame ( n ) : NEW_LINE INDENT even_div = 0 ; odd_div = 0 ; NEW_LINE for i in range ( 1 , int ( math . sqrt ( n ) ) ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n // i == i ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT even_div += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT odd_div += 1 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT even_div += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT odd_div += 1 ; NEW_LINE DEDENT if ( n // ( i % 2 ) == 0 ) : NEW_LINE INDENT even_div += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT odd_div += 1 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return ( even_div == odd_div ) ; NEW_LINE DEDENT N = 6 ; NEW_LINE if ( divisorsSame ( N ) == 0 ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT
Check if N is a Balanced Prime number or not | Utility function to check if a number is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function that returns true if n is a Balanced prime ; If n is not a prime number or n is the first prime then return false ; Initialize previous_prime to n - 1 and next_prime to n + 1 ; Find next prime number ; Find previous prime number ; Arithmetic mean ; If n is a weak prime ; 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 isBalancedPrime ( n ) : NEW_LINE INDENT if not isPrime ( n ) or n == 2 : NEW_LINE INDENT return False NEW_LINE DEDENT previous_prime = n - 1 NEW_LINE next_prime = n + 1 NEW_LINE while not isPrime ( next_prime ) : NEW_LINE INDENT next_prime += 1 NEW_LINE DEDENT while not isPrime ( previous_prime ) : NEW_LINE INDENT previous_prime -= 1 NEW_LINE DEDENT mean = ( previous_prime + next_prime ) / 2 NEW_LINE if n == mean : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = 53 NEW_LINE if isBalancedPrime ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Count of nodes having odd divisors in the given subtree for Q queries | Python3 implementation to count the number of nodes having odd number of divisors for each query ; Adjacency list for tree . ; Array for values and answer at ith node . ; Function to check whether N has odd divisors or not ; DFS function to pre - compute the answers ; Initialize the count ; Repeat for every child ; Increase the count if current node has odd number of divisors ; Driver Code ; Adjacency List ; Function call
import math NEW_LINE N = 100001 NEW_LINE adj = [ [ ] for i in range ( N ) ] NEW_LINE a = [ 0 for i in range ( N ) ] NEW_LINE ans = [ 0 for i in range ( N ) ] NEW_LINE def hasOddNumberOfDivisors ( n ) : NEW_LINE INDENT if ( math . sqrt ( n ) == int ( math . sqrt ( n ) ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def dfs ( node , parent ) : NEW_LINE INDENT count = 0 NEW_LINE for i in adj [ node ] : NEW_LINE INDENT if ( i != parent ) : NEW_LINE INDENT count += dfs ( i , node ) NEW_LINE DEDENT DEDENT if ( hasOddNumberOfDivisors ( a [ node ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT ans [ node ] = count NEW_LINE return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE i = 0 NEW_LINE q = [ 4 , 1 , 5 , 3 ] NEW_LINE adj [ 1 ] . append ( 2 ) NEW_LINE adj [ 2 ] . append ( 1 ) NEW_LINE adj [ 2 ] . append ( 3 ) NEW_LINE adj [ 3 ] . append ( 2 ) NEW_LINE adj [ 3 ] . append ( 4 ) NEW_LINE adj [ 4 ] . append ( 3 ) NEW_LINE adj [ 1 ] . append ( 5 ) NEW_LINE adj [ 5 ] . append ( 1 ) NEW_LINE a [ 1 ] = 4 NEW_LINE a [ 2 ] = 9 NEW_LINE a [ 3 ] = 14 NEW_LINE a [ 4 ] = 100 NEW_LINE a [ 5 ] = 5 NEW_LINE dfs ( 1 , - 1 ) NEW_LINE for i in range ( len ( q ) ) : NEW_LINE INDENT print ( ans [ q [ i ] ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT
Minimum Cost to make all array elements equal using given operations | Python3 implementation to find the minimum cost to make all array elements equal ; Checks if the value is less than middle element of the array ; Function that returns the cost of making all elements equal to current element ; Compute the lower bound of current element ; Calculate the requirement of add operation ; Calculate the requirement of subtract operation ; Compute minimum of left and right ; Computing the total cost of add and subtract operations ; Function that prints minimum cost of making all elements equal ; Sort the given array ; Calculate minimum from a + r and m ; Compute prefix sum and store in pref array ; Find the minimum cost from the given elements ; Finding the minimum cost from the other cases where minimum cost can occur ; Printing the minimum cost of making all elements equal ; Driver Code ; Function call
def lowerBound ( array , length , value ) : NEW_LINE INDENT low = 0 NEW_LINE high = length NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( value <= array [ mid ] ) : NEW_LINE INDENT high = mid NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT def costCalculation ( current , arr , n , pref , a , r , minimum ) : NEW_LINE INDENT index = lowerBound ( arr , len ( arr ) , current ) NEW_LINE left = index * current - pref [ index ] NEW_LINE right = ( pref [ n ] - pref [ index ] - ( n - index ) * current ) NEW_LINE res = min ( left , right ) NEW_LINE left -= res NEW_LINE right -= res NEW_LINE total = res * minimum NEW_LINE total += left * a NEW_LINE total += right * r NEW_LINE return total NEW_LINE DEDENT def solve ( arr , n , a , r , m ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE minimum = min ( a + r , m ) NEW_LINE pref = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT pref [ i + 1 ] = pref [ i ] + arr [ i ] NEW_LINE DEDENT ans = 10000 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = min ( ans , costCalculation ( arr [ i ] , arr , n , pref , a , r , minimum ) ) NEW_LINE DEDENT ans = min ( ans , costCalculation ( pref [ n ] // n , arr , n , pref , a , r , minimum ) ) NEW_LINE ans = min ( ans , costCalculation ( pref [ n ] // n + 1 , arr , n , pref , a , r , minimum ) ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 5 , 3 , 6 , 5 ] NEW_LINE A = 1 NEW_LINE R = 2 NEW_LINE M = 4 NEW_LINE size = len ( arr ) NEW_LINE solve ( arr , size , A , R , M ) NEW_LINE DEDENT
Count of integers up to N which represent a Binary number | Python3 program to count the number of integers upto N which are of the form of binary representations ; Function to return the count ; If the current last digit is 1 ; Add 2 ^ ( ctr - 1 ) possible integers to the answer ; If the current digit exceeds 1 ; Set answer as 2 ^ ctr - 1 as all possible binary integers with ctr number of digits can be obtained ; Driver Code
from math import * NEW_LINE def countBinaries ( N ) : NEW_LINE INDENT ctr = 1 NEW_LINE ans = 0 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N % 10 == 1 ) : NEW_LINE INDENT ans += pow ( 2 , ctr - 1 ) NEW_LINE DEDENT elif ( N % 10 > 1 ) : NEW_LINE INDENT ans = pow ( 2 , ctr ) - 1 NEW_LINE DEDENT ctr += 1 NEW_LINE N //= 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 20 NEW_LINE print ( int ( countBinaries ( N ) ) ) NEW_LINE DEDENT
Count of integers up to N which represent a Binary number | Function to return the count ; PreCompute and store the powers of 2 ; If the current last digit is 1 ; Add 2 ^ ( ctr - 1 ) possible integers to the answer ; If the current digit exceeds 1 ; Set answer as 2 ^ ctr - 1 as all possible binary integers with ctr number of digits can be obtained ; Driver code
def countBinaries ( N ) : NEW_LINE INDENT powersOfTwo = [ 0 ] * 11 NEW_LINE powersOfTwo [ 0 ] = 1 NEW_LINE for i in range ( 1 , 11 ) : NEW_LINE INDENT powersOfTwo [ i ] = powersOfTwo [ i - 1 ] * 2 NEW_LINE DEDENT ctr = 1 NEW_LINE ans = 0 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N % 10 == 1 ) : NEW_LINE INDENT ans += powersOfTwo [ ctr - 1 ] NEW_LINE DEDENT elif ( N % 10 > 1 ) : NEW_LINE INDENT ans = powersOfTwo [ ctr ] - 1 NEW_LINE DEDENT ctr += 1 NEW_LINE N = N // 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 20 NEW_LINE print ( countBinaries ( N ) ) NEW_LINE
Find the sum of the first Nth Centered Hexadecagonal Number | Centered_Hexadecagonal number function ; Formula to calculate nth Centered_Hexadecagonal number & return it into main function . ; Function to find the sum of the first N Centered Hexadecagonal number ; Variable to store the sum ; Loop to iterate through the first N numbers ; Find the sum ; Driver Code ; display first Nth Centered_Hexadecagonal number
def Centered_Hexadecagonal_num ( n ) : NEW_LINE INDENT return ( 8 * n * n - 8 * n + 1 ) NEW_LINE DEDENT def sum_Centered_Hexadecagonal_num ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ += Centered_Hexadecagonal_num ( i ) NEW_LINE DEDENT return summ NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( sum_Centered_Hexadecagonal_num ( n ) ) NEW_LINE DEDENT
Find the sum of the first N Centered heptagonal number | Function to find N - th centered heptagonal number ; Formula to calculate nth centered heptagonal number ; Function to find the sum of the first N centered heptagonal numbers ; Variable to store the sum ; Iterate through the range 1 to N ; Driver code
def center_heptagonal_num ( n ) : NEW_LINE INDENT return ( 7 * n * n - 7 * n + 2 ) // 2 NEW_LINE DEDENT def sum_center_heptagonal_num ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ += center_heptagonal_num ( i ) NEW_LINE DEDENT return summ NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( sum_center_heptagonal_num ( n ) ) NEW_LINE DEDENT
Find the sum of the first N Centered Dodecagonal Number | Function to find the N - th Centered Dodecagonal number ; Formula to calculate nth Centered_Dodecagonal number ; Function to find the sum of the first N Centered_Dodecagonal number ; Variable to store the sum ; Iterating from 1 to N ; Finding the sum ; Driver code
def Centered_Dodecagonal_num ( n ) : NEW_LINE INDENT return 6 * n * ( n - 1 ) + 1 NEW_LINE DEDENT def sum_Centered_Dodecagonal_num ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ += Centered_Dodecagonal_num ( i ) NEW_LINE DEDENT return summ NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( sum_Centered_Dodecagonal_num ( n ) ) NEW_LINE DEDENT
Find the sum of the first N Centered Octagonal Number | Function to find N - th Centered Octagonal number ; Formula to calculate nth centered Octagonal number ; Function to find the sum of the first N Centered Octagonal numbers ; Variable to store the sum ; Iterating through the first N numbers ; Driver code
def center_Octagonal_num ( n ) : NEW_LINE INDENT return ( 4 * n * n - 4 * n + 1 ) NEW_LINE DEDENT def sum_center_Octagonal_num ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ += center_Octagonal_num ( i ) NEW_LINE DEDENT return summ NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( sum_center_Octagonal_num ( n ) ) NEW_LINE DEDENT
Find the sum of the first N Centered Decagonal Numbers | Function to find the N - th centred decagonal number ; Formula to calculate nth Centered_decagonal number & return it into main function . ; Function to find the sum of the first N Centered decagonal numbers ; Variable to store the sum ; Iterating through the range ; Driver code ; display first Nth Centered_decagonal number
def Centered_decagonal_num ( n ) : NEW_LINE INDENT return ( 5 * n * n - 5 * n + 1 ) NEW_LINE DEDENT def sum_Centered_decagonal_num ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ += Centered_decagonal_num ( i ) NEW_LINE DEDENT return summ NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( sum_Centered_decagonal_num ( n ) ) NEW_LINE DEDENT
Find the sum of the first N Centered Octadecagonal Numbers | Function to find the N - th Centered octadecagonal number ; Formula to calculate nth centered octadecagonal number ; Function to find the sum of the first N Centered octadecagonal numbers ; Variable to store the sum ; Iterating through the range 1 to N ; Driver code
def center_octadecagon_num ( n ) : NEW_LINE INDENT return ( 9 * n * n - 9 * n + 1 ) NEW_LINE DEDENT def sum_center_octadecagon_num ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ += center_octadecagon_num ( i ) NEW_LINE DEDENT return summ NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE print ( sum_center_octadecagon_num ( n ) ) NEW_LINE DEDENT
Find the sum of the first Nth Centered Pentadecagonal Number | Function to find the Centered_Pentadecagonal number ; Formula to calculate N - th Centered_Pentadecagonal number ; Function to find the sum of the first N Centered_Pentadecagonal numbers ; Variable to store the sum ; Driver code
def Centered_Pentadecagonal_num ( n ) : NEW_LINE INDENT return ( 15 * n * n - 15 * n + 2 ) // 2 NEW_LINE DEDENT def sum_Centered_Pentadecagonal_num ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ += Centered_Pentadecagonal_num ( i ) NEW_LINE DEDENT return summ NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( sum_Centered_Pentadecagonal_num ( n ) ) NEW_LINE DEDENT
Program to check if N is a Octagonal Number | Python3 program for the above approach ; Function to check if N is a octagonal number ; Condition to check if the number is a octagonal number ; Driver Code ; Given number ; Function call
from math import sqrt NEW_LINE def isoctagonal ( N ) : NEW_LINE INDENT n = ( 2 + sqrt ( 12 * N + 4 ) ) / 6 ; NEW_LINE return ( n - int ( n ) ) == 0 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 8 ; NEW_LINE if ( isoctagonal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Program to check if N is a Pentadecagonal Number | Python3 program for the above approach ; Function to check if N is a pentadecagon number ; Condition to check if the number is a pentadecagon number ; Driver Code ; Given number ; Function call
from math import sqrt NEW_LINE def isPentadecagon ( N ) : NEW_LINE INDENT n = ( 11 + sqrt ( 104 * N + 121 ) ) / 26 ; NEW_LINE return ( n - int ( n ) == 0 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 15 ; NEW_LINE if ( isPentadecagon ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Program to check if N is a Tetradecagonal Number | Python3 program for the above approach ; Function to check if N is a Tetradecagonal Number ; Condition to check if the number is a tetradecagonal number ; Given Number ; Function call
import math NEW_LINE def istetradecagonal ( N ) : NEW_LINE INDENT n = ( 10 + math . sqrt ( 96 * N + 100 ) ) / 24 NEW_LINE if ( n - int ( n ) ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT N = 11 NEW_LINE if ( istetradecagonal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Find the sum of the first Nth Icosagonal Numbers | Function to calculate the N - th Icosagonal number ; Formula to calculate nth Icosagonal number & return it ; Function to find the sum of the first N Icosagonal numbers ; Variable to store the sum ; Loop to iterate through the first N values and find the sum of first N Icosagonal numbers ; function to get the Icosagonal_num ; Driver Code ; Display the sum of first N Icosagonal number
def Icosagonal_num ( n ) : NEW_LINE INDENT return ( 18 * n * n - 16 * n ) // 2 NEW_LINE DEDENT def sum_Icosagonal_num ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ += Icosagonal_num ( i ) NEW_LINE DEDENT return summ NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( sum_Icosagonal_num ( n ) ) NEW_LINE DEDENT
Find the sum of the first N Centered Pentagonal Number | Function to find the Centered_Pentagonal number ; Formula to calculate nth Centered_Pentagonal number & return it into main function . ; Function to find the sum of the first N Centered_Pentagonal numbers ; To get the sum ; Function to get the Centered_Pentagonal_num ; Driver Code ; display first Nth Centered_Pentagonal number
def Centered_Pentagonal_num ( n ) : NEW_LINE INDENT return ( 5 * n * n - 5 * n + 2 ) // 2 NEW_LINE DEDENT def sum_Centered_Pentagonal_num ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ += Centered_Pentagonal_num ( i ) NEW_LINE DEDENT return summ NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( sum_Centered_Pentagonal_num ( n ) ) NEW_LINE DEDENT
Find the sum of the first Nth Centered Tridecagonal Numbers | Function to calculate the N - th Centered tridecagonal number ; Formula to calculate Nth Centered tridecagonal number & return it ; Function to find the sum of the first N Centered tridecagonal numbers ; Variable to store the sum ; Loop to iterate and find the sum of first N Centered tridecagonal numbers ; Driver Code
def Centered_tridecagonal_num ( n ) : NEW_LINE INDENT return ( 13 * n * ( n - 1 ) + 2 ) // 2 NEW_LINE DEDENT def sum_Centered_tridecagonal_num ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ += Centered_tridecagonal_num ( i ) NEW_LINE DEDENT return summ NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( sum_Centered_tridecagonal_num ( n ) ) NEW_LINE DEDENT
Program to check if N is a Concentric Hexagonal Number | Python3 program to check if N is a concentric hexagonal number ; Function to check if the number is a concentric hexagonal number ; Condition to check if the number is a concentric hexagonal number ; Driver code ; Function call
import math NEW_LINE def isConcentrichexagonal ( N ) : NEW_LINE INDENT n = math . sqrt ( ( 2 * N ) / 3 ) NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT N = 6 NEW_LINE if isConcentrichexagonal ( N ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Count Sexy Prime Pairs in the given array | A utility function that find the Prime Numbers till N ; Resize the Prime Number ; Loop till sqrt ( N ) to find prime numbers and make their multiple false in the bool array Prime ; Function that returns the count of SPP ( Sexy Prime Pair ) Pairs ; Find the maximum element in the given array arr [ ] ; Function to calculate the prime numbers till N ; To store the count of pairs ; To store the frequency of element in the array arr [ ] ; Sort before traversing the array ; Traverse the array and find the pairs with SPP ( Sexy Prime Pair ) s ; If current element is Prime , then check for ( current element + 6 ) ; Return the count of pairs ; Driver code ; Function call to find SPP ( Sexy Prime Pair ) s pair
def computePrime ( N ) : NEW_LINE INDENT Prime = [ True ] * ( N + 1 ) NEW_LINE Prime [ 0 ] = False NEW_LINE Prime [ 1 ] = False NEW_LINE i = 2 NEW_LINE while i * i <= N : NEW_LINE INDENT if ( Prime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , N , i ) : NEW_LINE INDENT Prime [ j ] = False NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return Prime NEW_LINE DEDENT def countSexyPairs ( arr , n ) : NEW_LINE INDENT maxE = max ( arr ) NEW_LINE Prime = computePrime ( maxE ) NEW_LINE count = 0 NEW_LINE freq = [ 0 ] * ( maxE + 6 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Prime [ arr [ i ] ] ) : NEW_LINE INDENT if ( ( arr [ i ] + 6 ) <= ( maxE ) and freq [ arr [ i ] + 6 ] > 0 and Prime [ arr [ i ] + 6 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 7 , 5 , 11 , 13 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countSexyPairs ( arr , n ) ) NEW_LINE DEDENT
Count of ways to write N as a sum of three numbers | Function to find the number of ways ; Check if number is less than 2 ; Calculate the sum ; Driver code
def countWays ( N ) : NEW_LINE INDENT if ( N <= 2 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = ( N - 1 ) * ( N - 2 ) / 2 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE countWays ( N ) NEW_LINE DEDENT
Logarithm tricks for Competitive Programming | Python3 implementation to check that a integer is a power of two ; Function to check if the number is a power of two ; Driver code
import math NEW_LINE def isPowerOfTwo ( n ) : NEW_LINE INDENT return ( math . ceil ( math . log ( n ) // math . log ( 2 ) ) == math . floor ( math . log ( n ) // math . log ( 2 ) ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE if isPowerOfTwo ( N ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT DEDENT
Count of pairs having bit size at most X and Bitwise OR equal to X | Function to count the pairs ; Initializing answer with 1 ; Iterating through bits of x ; Check if bit is 1 ; Multiplying ans by 3 if bit is 1 ; Driver code
def count_pairs ( x ) : NEW_LINE INDENT ans = 1 ; NEW_LINE while ( x > 0 ) : NEW_LINE INDENT if ( x % 2 == 1 ) : NEW_LINE INDENT ans = ans * 3 ; NEW_LINE DEDENT x = x // 2 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 6 ; NEW_LINE print ( count_pairs ( X ) ) ; NEW_LINE DEDENT
Find the Kth number which is not divisible by N | Python3 implementation for above approach ; Function to find the Kth not divisible by N ; Lowest possible value ; Highest possible value ; To store the Kth non divisible number of N ; Using binary search ; Calculating mid value ; Sol would have the value by subtracting all multiples of n till mid ; Check if sol is greater than k ; H should be reduced to find minimum possible value ; Check if sol is less than k then L will be mid + 1 ; Check if sol is equal to k ; ans will be mid ; H would be reduced to find any more possible value ; Print the answer ; Driver Code ; Function call
import sys NEW_LINE def kthNonDivisible ( N , K ) : NEW_LINE INDENT L = 1 NEW_LINE H = sys . maxsize NEW_LINE ans = 0 NEW_LINE while ( L <= H ) : NEW_LINE INDENT mid = ( L + H ) // 2 NEW_LINE sol = mid - mid // N NEW_LINE if ( sol > K ) : NEW_LINE INDENT H = mid - 1 NEW_LINE DEDENT elif ( sol < K ) : NEW_LINE L = mid + 1 NEW_LINE else : NEW_LINE INDENT ans = mid NEW_LINE H = mid - 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT N = 3 NEW_LINE K = 7 NEW_LINE kthNonDivisible ( N , K ) NEW_LINE
Print any pair of integers with sum of GCD and LCM equals to N | Function to print the required pair ; Print the pair ; Driver code
def printPair ( n ) : NEW_LINE INDENT print ( "1" , end = " ▁ " ) NEW_LINE print ( n - 1 ) NEW_LINE DEDENT n = 14 NEW_LINE printPair ( n ) NEW_LINE
Find the length of largest subarray in which all elements are Autobiographical Numbers | Function to check number is autobiographical ; Convert integer to string ; Iterate for every digit to check for their total count ; Check occurrence of every number and count them ; Check if any position mismatches with total count them return with false else continue with loop ; Function to return the length of the largest subarray whose every element is a autobiographical number ; Utility function which checks every element of array for autobiographical number ; Check if element arr [ i ] is an autobiographical number ; Increment the current length ; Update max_length value ; Return the final result ; Driver code
def isAutoBiographyNum ( number ) : NEW_LINE INDENT count = 0 ; NEW_LINE NUM = str ( number ) ; NEW_LINE size = len ( NUM ) ; NEW_LINE for i in range ( size ) : NEW_LINE INDENT position = ord ( NUM [ i ] ) - ord ( '0' ) ; NEW_LINE count = 0 ; NEW_LINE for j in range ( size ) : NEW_LINE INDENT digit = ord ( NUM [ j ] ) - ord ( '0' ) ; NEW_LINE if ( digit == i ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT if ( position != count ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def checkArray ( arr , n ) : NEW_LINE INDENT current_length = 0 ; NEW_LINE max_length = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( isAutoBiographyNum ( 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 = [ 21200 , 1 , 1303 , 1210 , 2020 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( checkArray ( arr , n ) ) ; NEW_LINE DEDENT
Print the nodes of the Binary Tree whose height is a Prime number | Python3 implementation of nodes at prime height in the given tree ; To store Prime Numbers ; To store height of each node ; Function to find the prime numbers till 10 ^ 5 ; Traverse all multiple of i and make it false ; Function to perform dfs ; Store the height of node ; Function to find the nodes at prime height ; To precompute prime number till 10 ^ 5 ; Check if height [ node ] is prime ; Driver code ; Number of nodes ; Edges of the tree
MAX = 100000 NEW_LINE graph = [ [ ] for i in range ( MAX + 1 ) ] NEW_LINE Prime = [ True for i in range ( MAX + 1 ) ] NEW_LINE height = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT Prime [ 0 ] = Prime [ 1 ] = False NEW_LINE i = 2 NEW_LINE while i * i <= MAX : NEW_LINE INDENT if ( Prime [ i ] ) : NEW_LINE INDENT for j in range ( 2 * i , MAX , i ) : NEW_LINE INDENT Prime [ j ] = False NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def dfs ( node , parent , h ) : NEW_LINE INDENT height [ node ] = h NEW_LINE for to in graph [ node ] : NEW_LINE INDENT if ( to == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( to , node , h + 1 ) NEW_LINE DEDENT DEDENT def primeHeightNode ( N ) : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( Prime [ height [ i ] ] ) : NEW_LINE INDENT print ( i , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE graph [ 1 ] . append ( 2 ) NEW_LINE graph [ 1 ] . append ( 3 ) NEW_LINE graph [ 2 ] . append ( 4 ) NEW_LINE graph [ 2 ] . append ( 5 ) NEW_LINE dfs ( 1 , 1 , 0 ) NEW_LINE primeHeightNode ( N ) NEW_LINE DEDENT
Find Prime Adam integers in the given range [ L , R ] | Python3 program to find all prime adam numbers in the given range ; Reversing a number by taking remainder at a time ; Function to check if a number is a prime or not ; Iterating till the number ; Checking for factors ; Returning 1 if the there are no factors of the number other than 1 or itself ; Function to check whether a number is an adam number or not ; Reversing given number ; Squaring given number ; Squaring reversed number ; Reversing the square of the reversed number ; Checking if the square of the number and the square of its reverse are equal or not ; Function to find all the prime adam numbers in the given range ; If the first number is greater than the second number , print invalid ; Iterating through all the numbers in the given range ; Checking for prime number ; Checking for Adam number ; Driver code
def reverse ( a ) : NEW_LINE INDENT rev = 0 ; NEW_LINE while ( a != 0 ) : NEW_LINE INDENT r = a % 10 ; NEW_LINE rev = rev * 10 + r ; NEW_LINE a = a // 10 ; NEW_LINE DEDENT return ( rev ) ; NEW_LINE DEDENT def prime ( a ) : NEW_LINE INDENT k = 0 ; NEW_LINE for i in range ( 2 , a ) : NEW_LINE INDENT if ( a % i == 0 ) : NEW_LINE INDENT k = 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( k == 1 ) : NEW_LINE INDENT return ( 0 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( 1 ) ; NEW_LINE DEDENT DEDENT def adam ( a ) : NEW_LINE INDENT r1 = reverse ( a ) ; NEW_LINE s1 = a * a ; NEW_LINE s2 = r1 * r1 ; NEW_LINE r2 = reverse ( s2 ) ; NEW_LINE if ( s1 == r2 ) : NEW_LINE INDENT return ( 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( 0 ) ; NEW_LINE DEDENT DEDENT def find ( m , n ) : NEW_LINE INDENT if ( m > n ) : NEW_LINE INDENT print ( " INVALID INPUT " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT c = 0 ; NEW_LINE DEDENT for i in range ( m , n ) : NEW_LINE INDENT l = prime ( i ) ; NEW_LINE k = adam ( i ) ; NEW_LINE if ( ( l == 1 ) and ( k == 1 ) ) : NEW_LINE INDENT print ( i , " TABSYMBOL " , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT L = 5 ; R = 100 ; NEW_LINE find ( L , R ) ; NEW_LINE
Determine whether the given integer N is a Peculiar Number or not | Function to get sum of digits of a number ; Function to check if the number is peculiar ; Store a duplicate of n ; Driver code
def sumDig ( n ) : NEW_LINE INDENT s = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT s = s + int ( n % 10 ) NEW_LINE n = int ( n / 10 ) NEW_LINE DEDENT return s NEW_LINE DEDENT def Pec ( n ) : NEW_LINE INDENT dup = n NEW_LINE dig = sumDig ( n ) NEW_LINE if ( dig * 3 == dup ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT n = 36 NEW_LINE if Pec ( n ) == True : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Find N numbers such that a number and its reverse are divisible by sum of its digits | Function to calculate the sum of digits ; Loop to iterate through every digit of the number ; Returning the sum of digits ; Function to calculate the reverse of a number ; Loop to calculate the reverse of the number ; Return the reverse of the number ; Function to print the first N numbers such that every number and the reverse of the number is divisible by its sum of digits ; Loop to continuously check and generate number until there are n outputs ; Variable to hold the sum of the digit of the number ; Computing the reverse of the number ; Checking if the condition satisfies . Increment the count and print the number if it satisfies . ; Driver code
def digit_sum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT m = n % 10 ; NEW_LINE sum = sum + m ; NEW_LINE n = n // 10 NEW_LINE DEDENT return ( sum ) NEW_LINE DEDENT def reverse ( n ) : NEW_LINE INDENT r = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT r = r * 10 NEW_LINE r = r + n % 10 NEW_LINE n = n // 10 NEW_LINE DEDENT return ( r ) NEW_LINE DEDENT def operation ( n ) : NEW_LINE INDENT i = 1 NEW_LINE count = 0 NEW_LINE while ( count < n ) : NEW_LINE INDENT a = digit_sum ( i ) NEW_LINE r = reverse ( i ) NEW_LINE if ( i % a == 0 and r % a == 0 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE count += 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE operation ( 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 ; No such split possible for N <= 2 ; Print the first set consisting of even elements ; Print the second set consisting of odd ones ; Driver Code
def createSets ( N ) : NEW_LINE INDENT if ( N <= 2 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT for i in range ( 2 , N + 1 , 2 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE DEDENT print ( " " ) ; NEW_LINE for i in range ( 1 , N + 1 , 2 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 ; NEW_LINE createSets ( N ) ; NEW_LINE DEDENT
Count the nodes in the given tree whose weight is a powerful number | Python3 implementation to Count the Nodes in the given tree whose weight is a powerful number ; 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 ; Find highest power of " factor " that divides n ; Check 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 perform dfs ; Check if weight of the current Node is a powerful number ; Driver code ; Weights of the Node ; Edges of the tree
graph = [ [ ] for i in range ( 100 ) ] NEW_LINE weight = [ 0 ] * 100 NEW_LINE ans = 0 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 factor = 3 NEW_LINE while ( factor * factor <= n ) : 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 factor += 2 ; NEW_LINE DEDENT return ( n == 1 ) ; NEW_LINE DEDENT def dfs ( Node , parent ) : NEW_LINE INDENT global ans ; NEW_LINE if ( isPowerful ( weight [ Node ] ) ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT for to in graph [ Node ] : NEW_LINE INDENT if ( to == parent ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT dfs ( to , Node ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT weight [ 1 ] = 5 ; NEW_LINE weight [ 2 ] = 10 ; NEW_LINE weight [ 3 ] = 11 ; NEW_LINE weight [ 4 ] = 8 ; NEW_LINE weight [ 5 ] = 6 ; NEW_LINE graph [ 1 ] . append ( 2 ) ; NEW_LINE graph [ 2 ] . append ( 3 ) ; NEW_LINE graph [ 2 ] . append ( 4 ) ; NEW_LINE graph [ 1 ] . append ( 5 ) ; NEW_LINE dfs ( 1 , 1 ) ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT
Number of ways to color boundary of each block of M * N table | Function to compute all way to fill the boundary of all sides of the unit square ; Count possible ways to fill all upper and left side of the rectangle M * N ; Count possible ways to fill all side of the all squares unit size ; Number of rows ; Number of columns
def CountWays ( N , M ) : NEW_LINE INDENT count = 1 NEW_LINE count = pow ( 3 , M + N ) NEW_LINE count *= pow ( 2 , M * N ) ; NEW_LINE return count NEW_LINE DEDENT N = 3 NEW_LINE M = 2 NEW_LINE print ( CountWays ( N , M ) ) NEW_LINE
Nth positive number whose absolute difference of adjacent digits is at most 1 | Return Nth number with absolute difference between all adjacent digits at most 1. ; To store all such numbers ; Enqueue all integers from 1 to 9 in increasing order . ; Perform the operation N times so that we can get all such N numbers . ; Store the front element of queue , in array and pop it from queue . ; If the last digit of dequeued integer is not 0 , then enqueue the next such number . ; Enqueue the next such number ; If the last digit of dequeued integer is not 9 , then enqueue the next such number . ; Driver Code
def findNthNumber ( N ) : NEW_LINE INDENT arr = [ 0 for i in range ( N + 1 ) ] NEW_LINE q = [ ] NEW_LINE for i in range ( 1 , 10 , 1 ) : NEW_LINE INDENT q . append ( i ) NEW_LINE DEDENT for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT arr [ i ] = q [ 0 ] NEW_LINE q . remove ( q [ 0 ] ) NEW_LINE if ( arr [ i ] % 10 != 0 ) : NEW_LINE INDENT q . append ( arr [ i ] * 10 + arr [ i ] % 10 - 1 ) NEW_LINE DEDENT q . append ( arr [ i ] * 10 + arr [ i ] % 10 ) NEW_LINE if ( arr [ i ] % 10 != 9 ) : NEW_LINE INDENT q . append ( arr [ i ] * 10 + arr [ i ] % 10 + 1 ) NEW_LINE DEDENT DEDENT print ( arr [ N ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 21 NEW_LINE findNthNumber ( N ) NEW_LINE DEDENT
Unique element in an array where all elements occur K times except one | Set 2 | Function that find the unique element in the array arr [ ] ; Store all unique element in set ; Sum of all element of the array ; Sum of element in the set ; Print the unique element using formula ; Driver Code ; Function call
def findUniqueElements ( arr , N , K ) : NEW_LINE INDENT s = set ( ) NEW_LINE for x in arr : NEW_LINE INDENT s . add ( x ) NEW_LINE DEDENT arr_sum = sum ( arr ) NEW_LINE set_sum = 0 NEW_LINE for x in s : NEW_LINE INDENT set_sum += x NEW_LINE DEDENT print ( ( K * set_sum - arr_sum ) // ( K - 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE findUniqueElements ( arr , N , K ) NEW_LINE DEDENT
Form the Cubic equation from the given roots | Function to find the cubic equation whose roots are a , b and c ; Find the value of coefficient ; Print the equation as per the above coefficients ; Driver Code ; Function Call
def findEquation ( a , b , c ) : NEW_LINE INDENT X = ( a + b + c ) ; NEW_LINE Y = ( a * b ) + ( b * c ) + ( c * a ) ; NEW_LINE Z = ( a * b * c ) ; NEW_LINE print ( " x ^ 3 ▁ - ▁ " , X , " x ^ 2 ▁ + ▁ " , Y , " x ▁ - ▁ " , Z , " ▁ = ▁ 0" ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 5 ; NEW_LINE b = 2 ; NEW_LINE c = 3 ; NEW_LINE findEquation ( a , b , c ) ; NEW_LINE DEDENT
Gill 's 4th Order Method to solve Differential Equations | Python3 program to implement Gill 's method ; A sample differential equation " dy / dx ▁ = ▁ ( x ▁ - ▁ y ) /2" ; Finds value of y for a given x using step size h and initial value y0 at x0 ; Count number of iterations using step size or height h ; Initial value of y ( 0 ) ; Iterate for number of iteration ; Value of K1 ; Value of K2 ; Value of K3 ; Value of K4 ; Find the next value of y ( n + 1 ) using y ( n ) and values of K in the above steps ; Update next value of x ; Return the final value of dy / dx ; Driver Code
from math import sqrt NEW_LINE def dydx ( x , y ) : NEW_LINE INDENT return ( x - y ) / 2 NEW_LINE DEDENT def Gill ( x0 , y0 , x , h ) : NEW_LINE INDENT n = ( ( x - x0 ) / h ) NEW_LINE y = y0 NEW_LINE for i in range ( 1 , int ( n + 1 ) , 1 ) : NEW_LINE INDENT k1 = h * dydx ( x0 , y ) NEW_LINE k2 = h * dydx ( x0 + 0.5 * h , y + 0.5 * k1 ) NEW_LINE k3 = h * dydx ( x0 + 0.5 * h , y + 0.5 * ( - 1 + sqrt ( 2 ) ) * k1 + k2 * ( 1 - 0.5 * sqrt ( 2 ) ) ) NEW_LINE k4 = h * dydx ( x0 + h , y - ( 0.5 * sqrt ( 2 ) ) * k2 + k3 * ( 1 + 0.5 * sqrt ( 2 ) ) ) NEW_LINE y = y + ( 1 / 6 ) * ( k1 + ( 2 - sqrt ( 2 ) ) * k2 + ( 2 + sqrt ( 2 ) ) * k3 + k4 ) NEW_LINE x0 = x0 + h NEW_LINE DEDENT return y NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x0 = 0 NEW_LINE y = 3.0 NEW_LINE x = 5.0 NEW_LINE h = 0.2 NEW_LINE print ( " y ( x ) ▁ = " , round ( Gill ( x0 , y , x , h ) , 6 ) ) NEW_LINE DEDENT
Program to print numbers from N to 1 in reverse order | Recursive function to print from N to 1 ; Driver code
def PrintReverseOrder ( N ) : NEW_LINE INDENT for i in range ( N , 0 , - 1 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE PrintReverseOrder ( N ) ; NEW_LINE DEDENT
Find count of numbers from 0 to n which satisfies the given equation for a value K | Function to find the values ; Calculate the LCM ; Calculate the multiples of lcm ; Find the values which satisfies the given condition ; Subtract the extra values ; Return the final result ; Driver code
def findAns ( a , b , n ) : NEW_LINE INDENT lcm = ( a * b ) // __gcd ( a , b ) ; NEW_LINE multiples = ( n // lcm ) + 1 ; NEW_LINE answer = max ( a , b ) * multiples ; NEW_LINE lastvalue = lcm * ( n // lcm ) + max ( a , b ) ; NEW_LINE if ( lastvalue > n ) : NEW_LINE INDENT answer = answer - ( lastvalue - n - 1 ) ; NEW_LINE DEDENT return answer ; NEW_LINE DEDENT def __gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT else : NEW_LINE INDENT return __gcd ( b , a % b ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 1 ; NEW_LINE b = 13 ; NEW_LINE n = 500 ; NEW_LINE print ( findAns ( a , b , n ) ) ; NEW_LINE DEDENT
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
137
Edit dataset card