text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Program to check if N is a Myriagon Number | Python3 implementation to check that a number is a myriagon number or not ; Function to check that the number is a myriagon number ; Condition to check if the number is a myriagon number ; Given Number ; Function call
import math NEW_LINE def isMyriagon ( N ) : NEW_LINE INDENT n = ( 9996 + math . sqrt ( 79984 * N + 99920016 ) ) / 19996 NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT n = 10000 NEW_LINE if ( isMyriagon ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE D...
Program to check if N is a Heptagonal Number | Python3 program for the above approach ; Function to check if N is a heptagonal number ; Condition to check if the number is a heptagonal number ; Given Number ; Function call
import math NEW_LINE def isheptagonal ( N ) : NEW_LINE INDENT n = ( 3 + math . sqrt ( 40 * N + 9 ) ) / 10 NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT N = 7 NEW_LINE if ( isheptagonal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Program to check if N is a Enneadecagonal Number | Python3 program for the above approach ; Function to check if number N is a enneadecagonal number ; Condition to check if N is a enneadecagonal number ; Given Number ; Function call
import math NEW_LINE def isenneadecagonal ( N ) : NEW_LINE INDENT n = ( 15 + math . sqrt ( 136 * N + 225 ) ) / 34 NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT N = 19 NEW_LINE if ( isenneadecagonal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDE...
Program to check if N is a Centered Tridecagonal Number | Python3 program for the above approach ; Function to check if the number N is a centered tridecagonal number ; Condition to check if N is centered tridecagonal number ; Given Number ; Function call
import numpy as np NEW_LINE def isCenteredtridecagonal ( N ) : NEW_LINE INDENT n = ( 13 + np . sqrt ( 104 * N + 65 ) ) / 26 NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT N = 14 NEW_LINE if ( isCenteredtridecagonal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No "...
Find the Nth natural number which is not divisible by A | Python3 code to Find the Nth number which is not divisible by A from the series ; Find the quotient and the remainder when k is divided by n - 1 ; if remainder is 0 then multiply n by q and add the remainder ; print the answer ; driver code
def findNum ( n , k ) : NEW_LINE INDENT q = k // ( n - 1 ) NEW_LINE r = k % ( n - 1 ) NEW_LINE if ( r != 0 ) : NEW_LINE INDENT a = ( n * q ) + r NEW_LINE DEDENT else : NEW_LINE INDENT a = ( n * q ) - 1 NEW_LINE DEDENT print ( a ) NEW_LINE DEDENT A = 4 NEW_LINE N = 6 NEW_LINE findNum ( A , N ) NEW_LINE
Count the nodes in the given Tree whose weight is a Perfect Number | Python3 implementation to Count the Nodes in the given tree whose weight is a Perfect Number ; Function that returns True if n is perfect ; Variable to store sum of divisors ; Find all divisors and add them ; Check if sum of divisors is equal to n , t...
graph = [ [ ] for i in range ( 100 ) ] NEW_LINE weight = [ 0 ] * 100 NEW_LINE ans = 0 NEW_LINE def isPerfect ( n ) : NEW_LINE INDENT sum = 1 ; NEW_LINE i = 2 ; NEW_LINE while ( i * i < n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( i * i != n ) : NEW_LINE INDENT sum = sum + i + n / i ; NEW_LINE DEDENT e...
Minimum cost to merge numbers from 1 to N | Function returns the minimum cost ; Min Heap representation ; Add all elements to heap ; First minimum ; Second minimum ; Multiply them ; Add to the cost ; Push the product into the heap again ; Return the optimal cost ; Driver code
def GetMinCost ( N ) : NEW_LINE INDENT pq = [ ] NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT pq . append ( i ) NEW_LINE DEDENT pq . sort ( reverse = False ) NEW_LINE cost = 0 NEW_LINE while ( len ( pq ) > 1 ) : NEW_LINE INDENT mini = pq [ 0 ] NEW_LINE pq . remove ( pq [ 0 ] ) NEW_LINE secondmini = pq [ 0...
Permutation of first N positive integers such that prime numbers are at prime indices | Set 2 | Python3 program to count permutations from 1 to N such that prime numbers occur at prime indices ; ; Computing count of prime numbers using sieve ; Computing permutations for primes ; Computing permutations for non - primes...
import math ; NEW_LINE def numPrimeArrangements ( n ) : NEW_LINE INDENT prime = [ True for i in range ( n + 1 ) ] NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if prime [ i ] : NEW_LINE INDENT factor = 2 NEW_LINE while factor * ...
Probability of getting K heads in N coin tosses | Function to calculate factorial ; Applying the formula ; Driver code ; Call count_heads with n and r
def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def count_heads ( n , r ) : NEW_LINE INDENT output = fact ( n ) / ( fact ( r ) * fact ( n - r ) ) NEW_LINE output = output / ( pow ( 2 , n ) ) NEW_LINE return output ...
Largest component size in a graph formed by connecting non | ; mark this node as visited ; apply dfs and add nodes belonging to this component ; create graph and store in adjacency list form ; iterate over all pair of nodes ; if not co - prime ; build undirected graph ; visited array for dfs ; Driver Code
from math import gcd NEW_LINE def dfs ( u , adj , vis ) : NEW_LINE INDENT vis [ u ] = 1 NEW_LINE componentSize = 1 NEW_LINE for x in adj [ u ] : NEW_LINE INDENT if ( vis [ x ] == 0 ) : NEW_LINE INDENT componentSize += dfs ( x , adj , vis ) NEW_LINE DEDENT DEDENT return componentSize NEW_LINE DEDENT def maximumComponent...
Largest component size in a graph formed by connecting non | smallest prime factor ; Sieve of Eratosthenes ; is spf [ i ] = 0 , then it 's prime ; smallest prime factor of all multiples is i ; Prime factorise n , and store prime factors in set s ; for implementing DSU ; root of component of node i ; finding root as wel...
spf = [ 0 for i in range ( 100005 ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT for i in range ( 2 , 100005 ) : NEW_LINE INDENT if ( spf [ i ] == 0 ) : NEW_LINE INDENT spf [ i ] = i ; NEW_LINE for j in range ( 2 * i , 100005 , i ) : NEW_LINE INDENT if ( spf [ j ] == 0 ) : NEW_LINE INDENT spf [ j ] = i ; NEW_LINE DEDENT ...
Count of nodes in a Binary Tree whose child is its prime factors | Python program for Counting nodes whose immediate children are its factors ; To store all prime numbers ; Create a boolean array " prime [ 0 . . N ] " and initialize all its entries as true . A value in prime [ i ] will finally be false if i is Not a pr...
from collections import deque NEW_LINE N = 1000000 NEW_LINE prime = [ ] NEW_LINE def SieveOfEratosthenes ( ) -> None : NEW_LINE INDENT check = [ True for _ in range ( N + 1 ) ] NEW_LINE p = 2 NEW_LINE while p * p <= N : NEW_LINE INDENT if ( check [ p ] ) : NEW_LINE INDENT prime . append ( p ) NEW_LINE for i in range ( ...
Check if original Array is retained after performing XOR with M exactly K times | Function to check if original Array can be retained by performing XOR with M exactly K times ; Check if O is present or not ; If K is odd and 0 is not present then the answer will always be No . ; Else it will be Yes ; Driver Code
def check ( Arr , n , M , K ) : NEW_LINE INDENT flag = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Arr [ i ] == 0 ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT if ( K % 2 != 0 and flag == 0 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT else : NEW_LINE INDENT return " Yes " ; NEW_LINE DEDENT DEDENT ...
Dixon 's Factorization Method with implementation | Python 3 implementation of Dixon factorization algo ; Function to find the factors of a number using the Dixon Factorization Algorithm ; Factor base for the given number ; Starting from the ceil of the root of the given number N ; Storing the related squares ; For eve...
from math import sqrt , gcd NEW_LINE import numpy as np NEW_LINE def factor ( n ) : NEW_LINE INDENT base = [ 2 , 3 , 5 , 7 ] NEW_LINE start = int ( sqrt ( n ) ) NEW_LINE pairs = [ ] NEW_LINE for i in range ( start , n ) : NEW_LINE INDENT for j in range ( len ( base ) ) : NEW_LINE INDENT lhs = i ** 2 % n NEW_LINE rhs = ...
Longest sub | Python3 program to find longest subarray of prime numbers ; To store the prime numbers ; Function that find prime numbers till limit ; Find primes using Sieve of Eratosthenes ; Function that finds all prime numbers in given range using Segmented Sieve ; Find the limit ; To store the prime numbers ; Comput...
import math NEW_LINE allPrimes = set ( ) NEW_LINE def simpleSieve ( limit , prime ) : NEW_LINE INDENT mark = [ False ] * ( limit + 1 ) NEW_LINE for i in range ( 2 , limit + 1 ) : NEW_LINE INDENT if mark [ i ] == False : NEW_LINE INDENT prime . append ( i ) NEW_LINE for j in range ( i , limit + 1 , i ) : NEW_LINE INDENT...
Sum of all armstrong numbers lying in the range [ L , R ] for Q queries | pref [ ] array to precompute the sum of all armstrong number ; Function that return number num if num is armstrong else return 0 ; Function to precompute the sum of all armstrong numbers upto 100000 ; checkarmstrong ( ) return the number i if i i...
pref = [ 0 ] * 100001 NEW_LINE def checkArmstrong ( x ) : NEW_LINE INDENT n = len ( str ( x ) ) NEW_LINE sum1 = 0 NEW_LINE temp = x NEW_LINE while temp > 0 : NEW_LINE INDENT digit = temp % 10 NEW_LINE sum1 += digit ** n NEW_LINE temp //= 10 NEW_LINE DEDENT if sum1 == x : NEW_LINE INDENT return x NEW_LINE DEDENT return ...
Count of pairs in an array whose product is a perfect square | prime [ ] array to calculate Prime Number ; Array to store the value of k for each element in arr [ ] ; For value of k , Sieve implemented ; Initialize k [ i ] to i ; Prime sieve ; If i is prime then remove all factors of prime from it ; Update that j is no...
prime = [ 0 ] * 100001 NEW_LINE k = [ 0 ] * 100001 NEW_LINE def Sieve ( ) : NEW_LINE INDENT for i in range ( 1 , 100001 ) : NEW_LINE INDENT k [ i ] = i NEW_LINE DEDENT for i in range ( 2 , 100001 ) : NEW_LINE INDENT if ( prime [ i ] == 0 ) : NEW_LINE INDENT for j in range ( i , 100001 , i ) : NEW_LINE INDENT prime [ j ...
Sum of all Perfect Cubes lying in the range [ L , R ] for Q queries | Array to precompute the sum of cubes from 1 to 100010 so that for every query , the answer can be returned in O ( 1 ) . ; Function to check if a number is a perfect Cube or not ; Find floating point value of cube root of x . ; If cube root of x is cr...
pref = [ 0 ] * 100010 ; NEW_LINE def isPerfectCube ( x ) : NEW_LINE INDENT cr = round ( x ** ( 1 / 3 ) ) ; NEW_LINE rslt = x if ( cr * cr * cr == x ) else 0 ; NEW_LINE return rslt ; NEW_LINE DEDENT def compute ( ) : NEW_LINE INDENT for i in range ( 1 , 100001 ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + isPerfectC...
Total number of Subsets of size at most K | Function to compute the value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to calculate sum of nCj from j = 1 to k ; Calling the nCr function for each...
def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ [ 0 for i in range ( k + 1 ) ] for j in range ( n + 1 ) ] ; NEW_LINE i , j = 0 , 0 ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 ; NEW_LINE DEDEN...
Tree Isomorphism Problem | A Binary tree node ; Check if the binary tree is isomorphic or not ; Both roots are None , trees isomorphic by definition ; Exactly one of the n1 and n2 is None , trees are not isomorphic ; There are two possible cases for n1 and n2 to be isomorphic Case 1 : The subtrees rooted at these nodes...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isIsomorphic ( n1 , n2 ) : NEW_LINE INDENT if n1 is None and n2 is None : NEW_LINE INDENT return True NEW_LINE DEDENT if n1 is None or n2 is ...
Find smallest number with given number of digits and sum of digits under given constraints | Function to find the number having sum of digits as s and d number of digits such that the difference between the maximum and the minimum digit the minimum possible ; To store the final number ; To store the value that is evenl...
def findNumber ( s , d ) : NEW_LINE INDENT num = " " NEW_LINE val = s // d NEW_LINE rem = s % d NEW_LINE for i in range ( 1 , d - rem + 1 ) : NEW_LINE INDENT num = num + str ( val ) NEW_LINE DEDENT if ( rem ) : NEW_LINE INDENT val += 1 NEW_LINE for i in range ( d - rem + 1 , d + 1 ) : NEW_LINE INDENT num = num + str ( ...
Find the sum of power of bit count raised to the power B | Function to calculate a ^ b mod m using fast - exponentiation method ; Function to calculate sum ; Itereate for all values of array A ; Calling fast - exponentiation and appending ans to sum ; Driver code .
def fastmod ( base , exp , mod ) : NEW_LINE INDENT if ( exp == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( exp % 2 == 0 ) : NEW_LINE INDENT ans = fastmod ( base , exp / 2 , mod ) ; NEW_LINE return ( ans % mod * ans % mod ) % mod ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( fastmod ( base , exp - 1 , mo...
Count the total number of triangles after Nth operation | Function to return the total no . of Triangles ; For every subtriangle formed there are possibilities of generating ( curr * 3 ) + 2 ; Changing the curr value to Tri_count ;
def countTriangles ( n ) : NEW_LINE INDENT curr = 1 NEW_LINE Tri_count = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT Tri_count = ( curr * 3 ) + 2 NEW_LINE curr = Tri_count NEW_LINE DEDENT return Tri_count NEW_LINE DEDENT / * Driver code * / NEW_LINE n = 10 NEW_LINE print ( countTriangles ( n ) ) NEW_LINE
In how many ways the ball will come back to the first boy after N turns | Function to return the number of sequences that get back to Bob ; Driver code
def numSeq ( n ) : NEW_LINE INDENT return ( pow ( 3 , n ) + 3 * pow ( - 1 , n ) ) // 4 NEW_LINE DEDENT N = 10 NEW_LINE print ( numSeq ( N ) ) NEW_LINE
Count subarrays such that remainder after dividing sum of elements by K gives count of elements | Function to return the number of subarrays of the given array such that the remainder when dividing the sum of its elements by K is equal to the number of its elements ; To store prefix sum ; We are dealing with zero index...
def sub_arrays ( a , n , k ) : NEW_LINE INDENT sum = [ 0 for i in range ( n + 2 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] -= 1 NEW_LINE a [ i ] %= k NEW_LINE sum [ i + 1 ] += sum [ i ] + a [ i ] NEW_LINE sum [ i + 1 ] %= k NEW_LINE DEDENT ans = 0 NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE mp = dict ( ) NE...
Sum of all the prime numbers with the maximum position of set bit Γ’ ‰€ D | Python 3 implementation of the approach ; Function for Sieve of Eratosthenes ; Function to return the sum of the required prime numbers ; Maximum number of the required range ; Sieve of Eratosthenes ; To store the required sum ; If current eleme...
from math import sqrt , pow NEW_LINE def sieve ( prime , n ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = F...
Check whether the exchange is possible or not | Python3 implementation of the approach ; Function that returns true if the exchange is possible ; Find the GCD of the array elements ; If the exchange is possible ; Driver code
from math import gcd as __gcd NEW_LINE def isPossible ( arr , n , p ) : NEW_LINE INDENT gcd = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT gcd = __gcd ( gcd , arr [ i ] ) ; NEW_LINE DEDENT if ( p % gcd == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main...
Choose two elements from the given array such that their sum is not present in any of the arrays | Function to find the numbers from the given arrays such that their sum is not present in any of the given array ; Find the maximum element from both the arrays ; Driver code
def findNum ( a , n , b , m ) : NEW_LINE INDENT x = max ( a ) ; NEW_LINE y = max ( b ) ; NEW_LINE print ( x , y ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 3 , 2 , 2 ] ; NEW_LINE n = len ( a ) ; NEW_LINE b = [ 1 , 5 , 7 , 7 , 9 ] ; NEW_LINE m = len ( b ) ; NEW_LINE findNum ( a , n , b , ...
Generate an array B [ ] from the given array A [ ] which satisfies the given conditions | Python3 implementation of the approach ; Utility function to print the array elements ; Function to generate and print the required array ; To switch the ceil and floor function alternatively ; For every element of the array ; If ...
from math import ceil , floor NEW_LINE def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def generateArr ( arr , n ) : NEW_LINE INDENT flip = True NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDE...
Number of K length subsequences with minimum sum | Function to return the value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to return the count of valid subsequences ; Sort the array ; Maximum ...
def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ [ 0 for i in range ( n + 1 ) ] for j in range ( k + 1 ) ] NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT for j in range ( 0 , min ( i , k ) + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE IND...
Find all even length binary sequences with same sum of first and second half bits | Iterative | Function to convert the number into binary and store the number into an array ; Function to check if the sum of the digits till the mid of the array and the sum of the digits from mid till n is the same , if they are same th...
def convertToBinary ( num , a , n ) : NEW_LINE INDENT pointer = n - 1 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT a [ pointer ] = num % 2 NEW_LINE num = num // 2 NEW_LINE pointer -= 1 NEW_LINE DEDENT DEDENT def checkforsum ( a , n ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE mid = n // 2 NEW_LINE for i in r...
Find out the prime numbers in the form of A + nB or B + nA | Python3 implementation of the above approach ; Utility function to check whether two numbers is co - prime or not ; Utility function to check whether a number is prime or not ; Corner case ; Check from 2 to sqrt ( n ) ; finding the Prime numbers ; Checking wh...
from math import gcd , sqrt NEW_LINE def coprime ( a , b ) : NEW_LINE INDENT if ( gcd ( a , b ) == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( n ==...
Find the integers that doesnot ends with T1 or T2 when squared and added X | Function to print the elements Not ending with T1 or T2 ; Flag to check if none of the elements Do not end with t1 or t2 ; Traverse through all the elements ; Temporary variable to store the value ; If the last digit is neither t1 nor t2 then ...
def findIntegers ( n , a , x , t1 , t2 ) : NEW_LINE INDENT flag = True NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = pow ( a [ i ] , 2 ) + x NEW_LINE if ( temp % 10 != t1 and temp % 10 != t2 ) : NEW_LINE INDENT print ( temp , end = " ▁ " ) NEW_LINE flag = False NEW_LINE DEDENT DEDENT if flag : NEW_LINE INDENT ...
First N terms whose sum of digits is a multiple of 10 | Python3 code for above implementation ; Function to return the sum of digits of n ; Add last digit to the sum ; Remove last digit ; Function to return the nth term of the required series ; If sum of digit is already a multiple of 10 then append 0 ; To store the mi...
TEN = 10 NEW_LINE def digitSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT sum += n % TEN NEW_LINE n //= TEN NEW_LINE DEDENT return sum NEW_LINE DEDENT def getNthTerm ( n ) : NEW_LINE INDENT sum = digitSum ( n ) NEW_LINE if ( sum % TEN == 0 ) : NEW_LINE INDENT return ( n * TEN ) NEW_LINE ...
Nearest greater number by interchanging the digits | Python3 program to find nearest greater value ; Find all the possible permutation of Value A . ; Convert into Integer ; Find the minimum value of A by interchanging the digits of A and store min1 . ; Driver code ; Convert integer value into to find all the permutatio...
min1 = 10 ** 9 NEW_LINE _count = 0 NEW_LINE def permutation ( str1 , i , n , p ) : NEW_LINE INDENT global min1 , _count NEW_LINE if ( i == n ) : NEW_LINE INDENT str1 = " " . join ( str1 ) NEW_LINE q = int ( str1 ) NEW_LINE if ( q - p > 0 and q < min1 ) : NEW_LINE INDENT min1 = q NEW_LINE _count = 1 NEW_LINE DEDENT DEDE...
Alcuin 's Sequence | Python3 program for AlcuinaTMs Sequence ; find the nth term of Alcuin 's sequence ; return the ans ; print first n terms of Alcuin number ; display the number ; Driver code
from math import ceil , floor NEW_LINE def Alcuin ( n ) : NEW_LINE INDENT _n = n NEW_LINE ans = 0 NEW_LINE ans = ( round ( ( _n * _n ) / 12 ) - floor ( _n / 4 ) * floor ( ( _n + 2 ) / 4 ) ) NEW_LINE return ans NEW_LINE DEDENT def solve ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( Alcui...
Find the final sequence of the array after performing given operations | Python3 implementation of the approach ; Driver Code
def solve ( arr , n ) : NEW_LINE INDENT b = [ 0 for i in range ( n ) ] NEW_LINE p = 0 NEW_LINE i = n - 1 NEW_LINE while i >= 0 : NEW_LINE INDENT b [ p ] = arr [ i ] NEW_LINE i -= 1 NEW_LINE if ( i >= 0 ) : NEW_LINE INDENT b [ n - 1 - p ] = arr [ i ] NEW_LINE DEDENT p += 1 NEW_LINE i -= 1 NEW_LINE DEDENT return b NEW_LI...
Check if the product of every contiguous subsequence is different or not in a number | Function that returns true if the product of every digit of a contiguous subsequence is distinct ; To store the given number as a string ; Append all the digits starting from the end ; Reverse the string to get the original number ; ...
def productsDistinct ( N ) : NEW_LINE INDENT s = " " NEW_LINE while ( N ) : NEW_LINE INDENT s += chr ( N % 10 + ord ( '0' ) ) NEW_LINE N //= 10 NEW_LINE DEDENT s = s [ : : - 1 ] NEW_LINE sz = len ( s ) NEW_LINE se = [ ] NEW_LINE for i in range ( sz ) : NEW_LINE INDENT product = 1 NEW_LINE for j in range ( i , sz , 1 ) ...
Number of ways to arrange 2 * N persons on the two sides of a table with X and Y persons on opposite sides | Function to find factorial of a number ; Function to find nCr ; Function to find the number of ways to arrange 2 * N persons ; Driver code ; Function call
def factorial ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return n * factorial ( n - 1 ) ; NEW_LINE DEDENT def nCr ( n , r ) : NEW_LINE INDENT return ( factorial ( n ) / ( factorial ( n - r ) * factorial ( r ) ) ) ; NEW_LINE DEDENT def NumberOfWays ( n , x , y ) : NEW_LINE INDENT ...
Find smallest positive number Y such that Bitwise AND of X and Y is Zero | Method to find smallest number Y for a given value of X such that X AND Y is zero ; Convert the number into its binary form ; Case 1 : If all bits are ones , then return the next number ; Case 2 : find the first 0 - bit index and return the Y ; ...
def findSmallestNonZeroY ( A_num ) : NEW_LINE INDENT A_binary = bin ( A_num ) NEW_LINE B = 1 NEW_LINE length = len ( A_binary ) ; NEW_LINE no_ones = ( A_binary ) . count ( '1' ) ; NEW_LINE if length == no_ones : NEW_LINE INDENT return A_num + 1 ; NEW_LINE DEDENT for i in range ( length ) : NEW_LINE INDENT ch = A_binary...
Count number of set bits in a range using bitset | Python3 implementation of above approach ; function for converting binary string into integer value ; function to count number of 1 's using bitset ; Converting the string into bitset ; Bitwise operations Left shift ; Right shifts ; return count of one in [ L , R ] ; ...
N = 32 NEW_LINE def binStrToInt ( binary_str ) : NEW_LINE INDENT length = len ( binary_str ) NEW_LINE num = 0 NEW_LINE for i in range ( length ) : NEW_LINE INDENT num = num + int ( binary_str [ i ] ) NEW_LINE num = num * 2 NEW_LINE DEDENT return num / 2 NEW_LINE DEDENT def GetOne ( s , L , R ) : NEW_LINE INDENT length ...
Maximum element in an array such that its previous and next element product is maximum | Function to return the largest element such that its previous and next element product is maximum ; Calculate the product of the previous and the next element for the current element ; Update the maximum product ; If current produc...
def maxElement ( a , n ) : NEW_LINE INDENT if n < 3 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT maxElement = a [ 0 ] NEW_LINE maxProd = a [ n - 1 ] * a [ 1 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT currprod = a [ i - 1 ] * a [ ( i + 1 ) % n ] NEW_LINE if currprod > maxProd : NEW_LINE INDENT maxProd = currp...
Total ways of choosing X men and Y women from a total of M men and W women | Function to return the value of ncr effectively ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the count of required ways ;
def ncr ( n , r ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , r + 1 ) : NEW_LINE INDENT ans *= ( n - r + i ) NEW_LINE ans //= i NEW_LINE DEDENT return ans NEW_LINE DEDENT def totalWays ( X , Y , M , W ) : NEW_LINE INDENT return ( ncr ( M , X ) * ncr ( W , Y ) ) NEW_LINE DEDENT / * Driver code * / NEW_LINE X...
Generate elements of the array following given conditions | Function to generate the required array ; Initialize cnt variable for assigning unique value to prime and its multiples ; When we get a prime for the first time then assign a unique smallest value to it and all of its multiples ; Print the generated array ; Dr...
def specialSieve ( n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE prime = [ 0 ] * ( n + 1 ) ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( not prime [ i ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE for j in range ( i , n + 1 , i ) : NEW_LINE INDENT prime [ j ] = cnt ; NEW_LINE DEDENT DEDENT DEDENT for i in range...
Find the node whose sum with X has maximum set bits | Python implementation of the approach ; Function to perform dfs to find the maximum set bits value ; If current set bits value is greater than the current maximum ; If count is equal to the maximum then choose the node with minimum value ; Driver Code ; Weights of t...
from sys import maxsize NEW_LINE maximum , x , ans = - maxsize , None , maxsize NEW_LINE graph = [ [ ] for i in range ( 100 ) ] NEW_LINE weight = [ 0 ] * 100 NEW_LINE def dfs ( node , parent ) : NEW_LINE INDENT global x , ans , graph , weight , maximum NEW_LINE a = bin ( weight [ node ] + x ) . count ( '1' ) NEW_LINE i...
Count Pairs from two arrays with even sum | Function to return count of required pairs ; Count of odd and even numbers from both the arrays ; Find the count of odd and even elements in a [ ] ; Find the count of odd and even elements in b [ ] ; Count the number of pairs ; Return the number of pairs ; Driver code
def count_pairs ( a , b , n , m ) : NEW_LINE INDENT odd1 = 0 NEW_LINE even1 = 0 NEW_LINE odd2 = 0 NEW_LINE even2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 2 == 1 ) : NEW_LINE INDENT odd1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even1 += 1 NEW_LINE DEDENT DEDENT for i in range ( m ) : NEW_LIN...
Find an index such that difference between product of elements before and after it is minimum | ; Function to find index ; Array to store log values of elements ; Prefix Array to Maintain Sum of log values till index i ; Answer Index ; Find minimum absolute value ; Driver Code
import math NEW_LINE def solve ( Array , N ) : NEW_LINE INDENT Arraynew = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT Arraynew [ i ] = math . log ( Array [ i ] ) NEW_LINE DEDENT prefixsum = [ 0 ] * N NEW_LINE prefixsum [ 0 ] = Arraynew [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT prefixsum [ ...
Find the value of N when F ( N ) = f ( a ) + f ( b ) where a + b is the minimum possible and a * b = N | Function to return the value of F ( N ) ; Base cases ; Count the number of times a number if divisible by 2 ; Return the summation ; Driver code
def getValueOfF ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT cnt = 0 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE n /= 2 NEW_LINE DEDENT return 2 * cnt NEW_LINE DEDENT n = 20 NEW_LINE print ( getValueOfF ( ...
Find the sum of the number of divisors | Python3 code for above given approach ; To store the number of divisors ; Function to find the number of divisors of all numbers in the range 1 to n ; For every number 1 to n ; Increase divisors count for every number ; Function to find the sum of divisors ; To store sum ; Count...
N = 100005 NEW_LINE mod = 1000000007 NEW_LINE cnt = [ 0 ] * N ; NEW_LINE def Divisors ( ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 1 , N // i ) : NEW_LINE INDENT cnt [ i * j ] += 1 ; NEW_LINE DEDENT DEDENT DEDENT def Sumofdivisors ( A , B , C ) : NEW_LINE INDENT sum = 0 ; NEW_LINE D...
Find ( 1 ^ n + 2 ^ n + 3 ^ n + 4 ^ n ) mod 5 | Set 2 | Function to return A mod B ; length of the string ; to store required answer ; Function to return ( 1 ^ n + 2 ^ n + 3 ^ n + 4 ^ n ) % 5 ; Calculate and return ans ; Driver code
def A_mod_B ( N , a ) : NEW_LINE INDENT Len = len ( N ) NEW_LINE ans = 0 NEW_LINE for i in range ( Len ) : NEW_LINE INDENT ans = ( ans * 10 + int ( N [ i ] ) ) % a NEW_LINE DEDENT return ans % a NEW_LINE DEDENT def findMod ( N ) : NEW_LINE INDENT mod = A_mod_B ( N , 4 ) NEW_LINE ans = ( 1 + pow ( 2 , mod ) + pow ( 3 , ...
Elements greater than the previous and next element in an Array | Function to print elements greater than the previous and next element in an Array ; Traverse array from index 1 to n - 2 and check for the given condition ; Driver Code
def printElements ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n - 1 , 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] and arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 1 , 5 , 4 ...
Sum of the series Kn + ( K ( n | ; Recursive python3 program to compute modular power ; Base cases ; If B is even ; If B is odd ; Function to return sum ; Driver code
/ * Python program of above approach * / NEW_LINE def exponent ( A , B ) : NEW_LINE INDENT if ( A == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( B == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( B % 2 == 0 ) : NEW_LINE INDENT y = exponent ( A , B / 2 ) ; NEW_LINE y = ( y * y ) ; NEW_LINE DEDENT else ...
Minimize the cost to split a number | Python3 implementation of the approach ; check if a number is prime or not ; run a loop upto square root of x ; Function to return the minimized cost ; If n is prime ; If n is odd and can be split into ( prime + 2 ) then cost will be 1 + 1 = 2 ; Every non - prime even number can be...
from math import sqrt NEW_LINE def isPrime ( x ) : NEW_LINE INDENT for i in range ( 2 , int ( sqrt ( x ) ) + 1 ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT return 1 ; NEW_LINE DEDENT def minimumCost ( n ) : NEW_LINE INDENT if ( isPrime ( n ) ) : NEW_LINE INDENT return 1 ; NE...
Find amount of water wasted after filling the tank | Function to calculate amount of wasted water ; filled amount of water in one minute ; total time taken to fill the tank because of leakage ; wasted amount of water ; Driver code
def wastedWater ( V , M , N ) : NEW_LINE INDENT amt_per_min = M - N NEW_LINE time_to_fill = V / amt_per_min NEW_LINE wasted_amt = N * time_to_fill NEW_LINE return wasted_amt NEW_LINE DEDENT V = 700 NEW_LINE M = 10 NEW_LINE N = 3 NEW_LINE print ( wastedWater ( V , M , N ) ) NEW_LINE V = 1000 NEW_LINE M = 100 NEW_LINE N ...
Smallest and Largest N | Python3 implementation of the approach ; Function to print the largest and the smallest n - digit perfect cube ; Smallest n - digit perfect cube ; Largest n - digit perfect cube ; Driver code
from math import ceil NEW_LINE def nDigitPerfectCubes ( n ) : NEW_LINE INDENT print ( pow ( ceil ( ( pow ( 10 , ( n - 1 ) ) ) ** ( 1 / 3 ) ) , 3 ) , end = " ▁ " ) NEW_LINE print ( pow ( ceil ( ( pow ( 10 , ( n ) ) ) ** ( 1 / 3 ) ) - 1 , 3 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_L...
Count numbers which are divisible by all the numbers from 2 to 10 | Function to return the count of numbers from 1 to n which are divisible by all the numbers from 2 to 10 ; Driver code
def countNumbers ( n ) : NEW_LINE INDENT return n // 2520 NEW_LINE DEDENT n = 3000 NEW_LINE print ( countNumbers ( n ) ) NEW_LINE
Sum of all odd factors of numbers in the range [ l , r ] | Python3 implementation of the approach ; Function to calculate the prefix sum of all the odd factors ; Add i to all the multiples of i ; Update the prefix sum ; Function to return the sum of all the odd factors of the numbers in the given range ; Driver code
MAX = 100001 ; NEW_LINE prefix = [ 0 ] * MAX ; NEW_LINE def sieve_modified ( ) : NEW_LINE INDENT for i in range ( 1 , MAX , 2 ) : NEW_LINE INDENT for j in range ( i , MAX , i ) : NEW_LINE INDENT prefix [ j ] += i ; NEW_LINE DEDENT DEDENT for i in range ( 1 , MAX ) : NEW_LINE INDENT prefix [ i ] += prefix [ i - 1 ] ; NE...
Number of ways in which an item returns back to its initial position in N swaps in array of size K | Python3 program to find the number of ways in which an item returns back to its initial position in N swaps in an array of size K ; Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it...
mod = 1000000007 NEW_LINE def power ( x , y ) : NEW_LINE INDENT p = mod NEW_LINE res = 1 NEW_LINE x = x % p NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) != 0 : 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 solve ( n ...
XOR of a submatrix queries | Python implementation of the approach ; Function to pre - compute the xor ; Left to right prefix xor for each row ; Top to bottom prefix xor for each column ; Function to process the queries x1 , x2 , y1 , y2 represent the positions of the top - left and bottom right corners ; To store the ...
n = 3 NEW_LINE def preComputeXor ( arr , prefix_xor ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT prefix_xor [ i ] [ j ] = arr [ i ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT prefix_xor [ i ] [ j ] = ( prefix_xor [ i ] [ j - 1 ] ^ ar...
Numbers less than N that are perfect cubes and the sum of their digits reduced to a single digit is 1 | Python3 implementation of the approach ; Function that returns true if the eventual digit sum of number nm is 1 ; if reminder will 1 then eventual sum is 1 ; Function to print the required numbers less than n ; If it...
import math NEW_LINE def isDigitSumOne ( nm ) : NEW_LINE INDENT if ( nm % 9 == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def printValidNums ( n ) : NEW_LINE INDENT cbrt_n = math . ceil ( n ** ( 1. / 3. ) ) NEW_LINE for i in range ( 1 , cbrt_n + 1 ) : NE...
Count the number of rhombi possible inside a rectangle of given size | Function to return the count of rhombi possible ; All possible diagonal lengths ; Update rhombi possible with the current diagonal lengths ; Return the total count of rhombi possible ; Driver code
def countRhombi ( h , w ) : NEW_LINE INDENT ct = 0 ; NEW_LINE for i in range ( 2 , h + 1 , 2 ) : NEW_LINE INDENT for j in range ( 2 , w + 1 , 2 ) : NEW_LINE INDENT ct += ( h - i + 1 ) * ( w - j + 1 ) NEW_LINE DEDENT DEDENT return ct NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT h = 2 NEW_LINE w = 2 ...
Program to calculate the area between two Concentric Circles | Function to find area between the two given concentric circles ; Declare value of pi ; Calculate area of outer circle ; Calculate area of inner circle ; Difference in areas ; Driver Code
def calculateArea ( x , y ) : NEW_LINE INDENT pi = 3.1415926536 NEW_LINE arx = pi * x * x NEW_LINE ary = pi * y * y NEW_LINE return arx - ary NEW_LINE DEDENT x = 2 NEW_LINE y = 1 NEW_LINE print ( calculateArea ( x , y ) ) NEW_LINE
Find the winner by adding Pairwise difference of elements in the array until Possible | Python3 implementation of the approach ; Function to return the winner of the game ; To store the gcd of the original array ; To store the maximum element from the original array ; If number of moves are odd ; Driver Code
from math import gcd NEW_LINE def getWinner ( arr , n ) : NEW_LINE INDENT __gcd = arr [ 0 ] ; NEW_LINE maxEle = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT __gcd = gcd ( __gcd , arr [ i ] ) ; NEW_LINE maxEle = max ( maxEle , arr [ i ] ) ; NEW_LINE DEDENT totalMoves = ( maxEle / __gcd ) - n ; NEW_LIN...
Count of pairs of ( i , j ) such that ( ( n % i ) % j ) % n is maximized | Function to return the count of required pairs ; Number which will give the Max value for ( ( n % i ) % j ) % n ; To store the Maximum possible value of ( ( n % i ) % j ) % n ; To store the count of possible pairs ; Check all possible pairs ; Ca...
def countPairs ( n ) : NEW_LINE INDENT num = ( ( n // 2 ) + 1 ) NEW_LINE Max = n % num NEW_LINE count = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT val = ( ( n % i ) % j ) % n NEW_LINE if ( val == Max ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDE...
Program to check if a number is divisible by any of its digits | Function to check if given number is divisible by any of its digits ; check if any of digit divides n ; check if K divides N ; Driver Code
def isDivisible ( n ) : NEW_LINE INDENT temp = n NEW_LINE while ( n ) : NEW_LINE INDENT k = n % 10 NEW_LINE if ( temp % k == 0 ) : NEW_LINE INDENT return " YES " NEW_LINE DEDENT n /= 10 ; NEW_LINE DEDENT return " NO " NEW_LINE DEDENT n = 9876543 NEW_LINE print ( isDivisible ( n ) ) NEW_LINE
Program to find sum of harmonic series | Function to return sum of harmonic series ; Driver Code
def sum ( n ) : NEW_LINE INDENT i = 1 NEW_LINE s = 0.0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT s = s + 1 / i ; NEW_LINE DEDENT return s ; NEW_LINE DEDENT n = 5 NEW_LINE print ( " Sum ▁ is " , round ( sum ( n ) , 6 ) ) NEW_LINE
Check if a number can be expressed as sum two abundant numbers | Python 3 program to check if number n is expressed as sum of two abundant numbers ; Function to return all abundant numbers This function will be helpful for multiple queries ; To store abundant numbers ; to store sum of the divisors include 1 in the sum ...
from math import sqrt NEW_LINE N = 100005 NEW_LINE def ABUNDANT ( ) : NEW_LINE INDENT v = set ( ) ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT sum = 1 NEW_LINE for j in range ( 2 , int ( sqrt ( i ) ) + 1 ) : NEW_LINE INDENT if ( i % j == 0 ) : NEW_LINE INDENT sum += j NEW_LINE DEDENT if ( i / j != j ) : NEW_LI...
Find nth term of the series 5 2 13 41 | Python3 program to find nth term of the series 5 2 13 41 ; function to calculate nth term of the series ; if n is even number ; if n is odd number ; return nth term ; Driver code
from math import pow NEW_LINE def nthTermOfTheSeries ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT nthTerm = pow ( n - 1 , 2 ) + n NEW_LINE DEDENT else : NEW_LINE INDENT nthTerm = pow ( n + 1 , 2 ) + n NEW_LINE DEDENT return nthTerm NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 8 N...
Find cost price from given selling price and profit or loss percentage | Function to calculate cost price with profit ; required formula to calculate CP with profit ; Function to calculate cost price with loss ; required formula to calculate CP with loss ; Driver code
def CPwithProfit ( sellingPrice , profit ) : NEW_LINE INDENT costPrice = ( ( sellingPrice * 100.0 ) / ( 100 + profit ) ) NEW_LINE return costPrice NEW_LINE DEDENT def CPwithLoss ( sellingPrice , loss ) : NEW_LINE INDENT costPrice = ( ( sellingPrice * 100.0 ) / ( 100 - loss ) ) NEW_LINE return costPrice NEW_LINE DEDENT ...
Check whether a number is Non | Python3 program to check if a given number is Non - Hypotenuse number or not . ; Function to find prime factor and check if it is of the form 4 k + 1 or not ; 2 is a prime number but not of the form 4 k + 1 so , keep Dividing n by 2 until n is divisible by 2 ; n must be odd at this point...
from math import sqrt NEW_LINE def isNonHypotenuse ( n ) : NEW_LINE INDENT while ( n % 2 == 0 ) : NEW_LINE INDENT n = n // 2 NEW_LINE DEDENT for i in range ( 3 , int ( sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( ( i - 1 ) % 4 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT wh...
Find the n | Python3 implementation of the above approach ; Function to return the nth string in the required sequence ; Length of the resultant string ; Relative index ; Initial string of length len consists of all a 's since the list is sorted ; Convert relative index to Binary form and set 0 = a and 1 = b ; Reverse ...
from math import log2 NEW_LINE def obtain_str ( n ) : NEW_LINE INDENT length = int ( log2 ( n + 1 ) ) NEW_LINE rel_ind = n + 1 - pow ( 2 , length ) NEW_LINE i = 0 NEW_LINE string = " " NEW_LINE for i in range ( length ) : NEW_LINE INDENT string += ' a ' NEW_LINE DEDENT i = 0 NEW_LINE string_list = list ( string ) NEW_L...
Program to find the Nth term of the series 0 , 3 / 1 , 8 / 3 , 15 / 5. . ... ... | Function to return the nth term of the given series ; nth term ; Driver code
def Nthterm ( n ) : NEW_LINE INDENT numerator = n ** 2 - 1 NEW_LINE denomenator = 2 * n - 3 NEW_LINE print ( numerator , " / " , denomenator ) NEW_LINE DEDENT n = 3 NEW_LINE Nthterm ( n ) NEW_LINE
Sum of each element raised to ( prime | Function to return the required sum ; Driver code
def getSum ( arr , p ) : NEW_LINE INDENT return len ( arr ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 6 , 8 ] NEW_LINE p = 7 NEW_LINE print ( getSum ( arr , p ) ) NEW_LINE DEDENT
Count numbers upto N which are both perfect square and perfect cube | Function to return required count ; Driver code ; function call to print required answer
def SquareCube ( N ) : NEW_LINE INDENT cnt , i = 0 , 1 NEW_LINE while ( i ** 6 <= N ) : NEW_LINE INDENT cnt += 1 NEW_LINE i += 1 NEW_LINE DEDENT return cnt NEW_LINE DEDENT N = 100000 NEW_LINE print ( SquareCube ( N ) ) NEW_LINE
Sum of integers upto N with given unit digit | Function to return the required sum ; Driver code
def getSum ( n , d ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( d <= n ) : NEW_LINE INDENT sum += d NEW_LINE d += 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 30 NEW_LINE d = 3 NEW_LINE print ( getSum ( n , d ) ) NEW_LINE
Summing the sum series | Python3 program to calculate the terms of summing of sum series ; Function to calculate twice of sum of first N natural numbers ; Function to calculate the terms of summing of sum series ;
MOD = 1000000007 NEW_LINE def Sum ( N ) : NEW_LINE INDENT val = N * ( N + 1 ) NEW_LINE val = val % MOD NEW_LINE return val NEW_LINE DEDENT def sumX ( N , M , K ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT N = int ( Sum ( K + N ) ) NEW_LINE DEDENT N = N % MOD NEW_LINE return N NEW_LINE DEDENT / * Driver co...
Logarithm | Python 3 program to find log ( n ) using Recursion ; Driver code
def Log2n ( n ) : NEW_LINE INDENT return 1 + Log2n ( n / 2 ) if ( n > 1 ) else 0 NEW_LINE DEDENT n = 32 NEW_LINE print ( Log2n ( n ) ) NEW_LINE
Mode | Function that sort input array a [ ] and calculate mode and median using counting sort . ; variable to store max of input array which will to have size of count array ; auxiliary ( count ) array to store count . Initialize count array as 0. Size of count array will be equal to ( max + 1 ) . ; Store count of each...
def printMode ( a , n ) : NEW_LINE INDENT max_element = max ( a ) NEW_LINE t = max_element + 1 NEW_LINE count = [ 0 ] * t NEW_LINE for i in range ( t ) : NEW_LINE INDENT count [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT count [ a [ i ] ] += 1 NEW_LINE DEDENT mode = 0 NEW_LINE k = count [ 0 ] NEW_LI...
Harmonic Progression | Python3 program to check if a given array can form harmonic progression ; Find reciprocal of arr [ ] ; After finding reciprocal , check if the reciprocal is in A . P . To check for A . P . , first Sort the reciprocal array , then check difference between consecutive elements ; Driver code ; serie...
def checkIsHP ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT rec = [ ] NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT a = 1 / arr [ i ] NEW_LINE rec . append ( a ) NEW_LINE DEDENT return ( rec ) NEW_LINE rec . sort ( ) NEW_LINE d = rec [ 1 ]...
Arithmetic Mean | Prints N arithmetic means between A and B . ; Calculate common difference ( d ) ; For finding N the arithmetic mean between A and B ; Driver code
def printAMeans ( A , B , N ) : NEW_LINE INDENT d = ( B - A ) / ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( int ( A + i * d ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT A = 20 ; B = 32 ; N = 5 NEW_LINE printAMeans ( A , B , N ) NEW_LINE
Prime Factor | Python program to print prime factors ; A function to print all prime factors of a given number n ; Print the number of two 's that divide n ; n must be odd at this point so a skip of 2 ( i = i + 2 ) can be used ; while i divides n , print i ad divide n ; Condition if n is a prime number greater than 2 ;...
import math NEW_LINE def primeFactors ( n ) : NEW_LINE INDENT while n % 2 == 0 : NEW_LINE INDENT print 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 print i , NEW_LINE n = n / i NEW_LINE DEDENT DEDENT if n > 2 : NEW_L...
Time taken by two persons to meet on a circular track | Python 3 implementation of above approach ; Function to return the time when both the persons will meet at the starting point ; Time to cover 1 round by both ; Finding LCM to get the meeting point ; Function to return the time when both the persons will meet for t...
from math import gcd NEW_LINE def startingPoint ( Length , Speed1 , Speed2 ) : NEW_LINE INDENT result1 = 0 NEW_LINE result2 = 0 NEW_LINE time1 = Length // Speed1 NEW_LINE time2 = Length // Speed2 NEW_LINE result1 = gcd ( time1 , time2 ) NEW_LINE result2 = time1 * time2 // ( result1 ) NEW_LINE return result2 NEW_LINE DE...
Check if the array has an element which is equal to product of remaining elements | Function to Check if the array has an element which is equal to product of all the remaining elements ; Calculate the product of all the elements ; Return true if any such element is found ; If no element is found ; Driver code
def CheckArray ( arr , n ) : NEW_LINE INDENT prod = 1 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT prod *= arr [ i ] NEW_LINE DEDENT for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( arr [ i ] == prod / arr [ i ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name_...
Sum of common divisors of two numbers A and B | print the sum of common factors ; sum of common factors ; iterate from 1 to minimum of a and b ; if i is the common factor of both the numbers ; Driver Code ; print the sum of common factors
def sum ( a , b ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , min ( a , b ) ) : NEW_LINE INDENT if ( a % i == 0 and b % i == 0 ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT A = 10 NEW_LINE B = 15 NEW_LINE print ( " Sum ▁ = " , sum ( A , B ) ) NEW_LINE
Minimum number of cuts required to make circle segments equal sized | Python 3 program to find the minimum number of additional cuts required to make circle segments equal sized ; Function to find the minimum number of additional cuts required to make circle segments are equal sized ; Sort the array ; Initial gcd value...
import math NEW_LINE def minimumCuts ( a , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE gcd = a [ 1 ] - a [ 0 ] NEW_LINE s = gcd NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT gcd = math . gcd ( gcd , a [ i ] - a [ i - 1 ] ) NEW_LINE s += a [ i ] - a [ i - 1 ] NEW_LINE DEDENT if ( 360 - s > 0 ) : NEW_LINE INDENT gc...
Find a number that divides maximum array elements | Python3 program to find a number that divides maximum array elements ; stores smallest prime factor for every number ; Calculating SPF ( Smallest Prime Factor ) for every number till MAXN . Time Complexity : O ( nloglogn ) ; marking smallest prime factor for every num...
import math as mt NEW_LINE MAXN = 100001 NEW_LINE spf = [ 0 for i in range ( MAXN ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT spf [ 1 ] = 1 NEW_LINE for i in range ( 2 , MAXN ) : NEW_LINE INDENT spf [ i ] = i NEW_LINE DEDENT for i in range ( 4 , MAXN , 2 ) : NEW_LINE INDENT spf [ i ] = 2 NEW_LINE DEDENT for i in range...
Find Selling Price from given Profit Percentage and Cost | Function to calculate the Selling Price ; Decimal Equivalent of Profit Percentage ; Find the Selling Price ; return the calculated Selling Price ; Driver code ; Get the CP and Profit % ; Printing the returned value
def SellingPrice ( CP , PP ) : NEW_LINE INDENT Pdecimal = 1 + ( PP / 100 ) NEW_LINE res = Pdecimal * CP NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT C = 720 NEW_LINE P = 13 NEW_LINE print ( SellingPrice ( C , P ) ) NEW_LINE DEDENT
Product of all the Composite Numbers in an array | Python3 program to find product of all the composite numberes in given array ; function to find the product of all composite niumbers in the given array ; find the maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a b...
import math as mt NEW_LINE def compositeProduct ( arr , n ) : NEW_LINE INDENT max_val = max ( arr ) NEW_LINE prime = [ True for i in range ( max_val + 1 ) ] NEW_LINE prime [ 0 ] = True NEW_LINE prime [ 1 ] = True NEW_LINE for p in range ( 2 , mt . ceil ( mt . sqrt ( max_val ) ) ) : NEW_LINE INDENT if prime [ p ] : NEW_...
Primality test for the sum of digits at odd places of a number | Function that return sum of the digits at odd places ; Function to check if a number is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; driver code ; Get the sum of the digits at odd places
def sum_odd ( n ) : NEW_LINE INDENT sums = 0 NEW_LINE pos = 1 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( pos % 2 == 1 ) : NEW_LINE INDENT sums += n % 10 NEW_LINE DEDENT n = n // 10 NEW_LINE pos += 1 NEW_LINE DEDENT return sums NEW_LINE DEDENT def check_prime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT...
Find amount to be added to achieve target ratio in a given mixture | Python3 program to find amount of water to be added to achieve given target ratio . ; Driver code
def findAmount ( X , W , Y ) : NEW_LINE INDENT return ( X * ( Y - W ) / ( 100 - Y ) ) NEW_LINE DEDENT X = 100 NEW_LINE W = 50 ; Y = 60 NEW_LINE print ( " Water ▁ to ▁ be ▁ added " , findAmount ( X , W , Y ) ) NEW_LINE
Check if a number is a Mystery Number | Finds reverse of given num x . ; if found print the pair , return
def reverseNum ( x ) : NEW_LINE INDENT s = str ( x ) NEW_LINE s = s [ : : - 1 ] NEW_LINE return int ( s ) NEW_LINE DEDENT def isMysteryNumber ( n ) : NEW_LINE INDENT for i in range ( 1 , n // 2 + 1 ) : NEW_LINE INDENT j = reverseNum ( i ) NEW_LINE if i + j == n : NEW_LINE INDENT print ( i , j ) NEW_LINE return True NEW...
Replace every element of the array by product of all other elements | Python 3 program to Replace every element by the product of all other elements ; Calculate the product of all the elements ; Replace every element product of all other elements ; Driver Code ; Print the modified array .
def ReplaceElements ( arr , n ) : NEW_LINE INDENT prod = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT prod *= arr [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = prod // arr [ i ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 3 , 5 , 7 ] NEW_LINE ...
Check if there is any pair in a given range with GCD is divisible by k | function to count such possible numbers ; if i is divisible by k ; if count of such numbers is greater than one ; Driver code
def Check_is_possible ( l , r , k ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT if ( i % k == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return ( count > 1 ) ; NEW_LINE DEDENT l = 4 ; NEW_LINE r = 12 ; NEW_LINE k = 5 ; NEW_LINE if ( Check_is_possible ( l , r , k ...
Check if any permutation of N equals any power of K | function to check if N and K are anagrams ; Function to check if any permutation of N exist such that it is some power of K ; generate all power of K under 10 ^ 18 ; check if any power of K is valid ; Driver Code ; function call to print required answer
def isValid ( N , K ) : NEW_LINE INDENT m1 = [ ] NEW_LINE m2 = [ ] NEW_LINE while ( N > 0 ) : NEW_LINE INDENT m1 . append ( N % 10 ) NEW_LINE N //= 10 NEW_LINE DEDENT while ( K > 0 ) : NEW_LINE INDENT m2 . append ( K % 10 ) NEW_LINE K //= 10 NEW_LINE DEDENT if ( m1 == m2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT ...
Sum of first N natural numbers which are divisible by 2 and 7 | Function to calculate the sum of numbers divisible by 2 or 7 ; Driver code
def sum ( N ) : NEW_LINE INDENT S1 = ( ( N // 2 ) ) * ( 2 * 2 + ( N // 2 - 1 ) * 2 ) // 2 NEW_LINE S2 = ( ( N // 7 ) ) * ( 2 * 7 + ( N // 7 - 1 ) * 7 ) // 2 NEW_LINE S3 = ( ( N // 14 ) ) * ( 2 * 14 + ( N // 14 - 1 ) * 14 ) // 2 NEW_LINE return S1 + S2 - S3 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDE...
Ways to color a skewed tree such that parent and child have different colors | fast_way is recursive method to calculate power ; Driver Code
def fastPow ( N , K ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT temp = fastPow ( N , int ( K / 2 ) ) ; NEW_LINE if ( K % 2 == 0 ) : NEW_LINE INDENT return temp * temp ; NEW_LINE DEDENT else : NEW_LINE INDENT return N * temp * temp ; NEW_LINE DEDENT DEDENT def countWays ( N , K ) : NEW...
Sum of nth terms of Modified Fibonacci series made by every pair of two arrays | Python3 program to find sum of n - th terms of a Fibonacci like series formed using first two terms of two arrays . ; if sum of first term is required ; if sum of second term is required ; fibonacci series used to find the nth term of ever...
def sumNth ( A , B , m , n ) : NEW_LINE INDENT res = 0 ; NEW_LINE if ( n == 1 ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT res = res + A [ i ] ; NEW_LINE DEDENT DEDENT elif ( n == 2 ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT res = res + B [ i ] * m ; NEW_LINE DEDENT DEDENT else : NEW_LINE ...
Puzzle | Minimum distance for Lizard | Python3 program to find minimum distance to be travelled by lizard ; side of cube ; understand from diagram ; understand from diagram ; minimum distance
import math NEW_LINE if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 5 NEW_LINE AC = a NEW_LINE CE = 2 * a NEW_LINE shortestDistace = math . sqrt ( AC * AC + CE * CE ) NEW_LINE print ( shortestDistace ) NEW_LINE DEDENT
Find Sum of Series 1 ^ 2 | Function to find sum of series ; If n is even ; If n is odd ; return the result ; Driver Code ; Get n ; Find the sum ; Get n ; Find the sum
def sum_of_series ( n ) : NEW_LINE INDENT result = 0 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT result = - ( n * ( n + 1 ) ) // 2 NEW_LINE DEDENT else : NEW_LINE INDENT result = ( n * ( n + 1 ) ) // 2 NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE print ...
Check whether the given numbers are Cousin prime or not | Python program to check Cousin prime ; Function to check whether a number is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Returns true if n1 and n2 are Cousin primes ; Check if they differ by 4 or not ; Ch...
import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if n <= 3 : NEW_LINE INDENT return True NEW_LINE DEDENT if n % 2 == 0 or n % 3 == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 5 , int ( math . sqrt ( n ) + 1 ) , 6 ) : NEW_LINE INDENT ...