text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Find the first and last M digits from K | Python3 program to implement the above approach ; Function to find a ^ b modulo M ; Function to find the first and last M digits from N ^ K ; Calculate Last M digits ; Calculate First M digits ; Extract the number after decimal ; Find 10 ^ y ; Move the Decimal Point M - 1 digit... | from math import * NEW_LINE def modPower ( a , b , M ) : NEW_LINE INDENT res = 1 NEW_LINE while ( b ) : NEW_LINE INDENT if ( b & 1 ) : NEW_LINE INDENT res = res * a % M NEW_LINE DEDENT a = a * a % M NEW_LINE b >>= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def findFirstAndLastM ( N , K , M ) : NEW_LINE INDENT lastM =... |
Minimize increment / decrement of Array elements to make each modulo K equal | Python3 program for the above approach ; Function to find the minimum operations required to make the modulo of each element of the array equal to each other ; Variable to store minimum operation required ; To store operation required to mak... | import sys NEW_LINE from collections import defaultdict NEW_LINE def Find_min ( diff_mod , count_mod , k ) : NEW_LINE INDENT min_oprn = sys . maxsize NEW_LINE oprn = 0 NEW_LINE for x in range ( k ) : NEW_LINE INDENT oprn = 0 NEW_LINE for w in diff_mod : NEW_LINE INDENT if ( w != x ) : NEW_LINE INDENT if ( w == 0 ) : NE... |
Minimize Steps required to obtain Sorted Order of an Array | Function to find GCD of two numbers ; Function to calculate the LCM of array elements ; Initialize result ; Function to find minimum steps required to obtain sorted sequence ; Inititalize dat [ ] array for Direct Address Table . ; Calculating steps required f... | 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 = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = ( ( arr [ i ] * ans ) // ( gcd ( arr [ i ] , ans ) ) ) NEW_LINE DEDENT ret... |
Largest Ratio Contiguous subarray | Python3 program for the above approach ; Function to return maximum of two double values ; Check if a is greater than b then return a ; Function that returns the Ratio of max Ratio subarray ; Variable to store the maximum ratio ; Compute the product while traversing for subarrays ; C... | import sys NEW_LINE def maximum ( a , b ) : NEW_LINE INDENT if ( a > b ) : NEW_LINE INDENT return a NEW_LINE DEDENT return b NEW_LINE DEDENT def maxSubarrayRatio ( arr , n ) : NEW_LINE INDENT maxRatio = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT ratio ... |
Even Perfect Number | Python3 program for the above approach ; Function to check for perfect number ; Find a number close to 2 ^ q - 1 ; Calculate q - 1 ; Condition of perfect number ; Check whether q is prime or not ; Check whether 2 ^ q - 1 is a prime number or not ; Function to check for prime number ; Check whether... | import math NEW_LINE def check ( num ) : NEW_LINE INDENT root = ( int ) ( math . sqrt ( num ) ) NEW_LINE poww = ( int ) ( math . log ( root ) / math . log ( 2 ) ) NEW_LINE if ( num == ( int ) ( pow ( 2 , poww ) * ( pow ( 2 , poww + 1 ) - 1 ) ) ) : NEW_LINE INDENT if ( isPrime ( poww + 1 ) ) : NEW_LINE INDENT if ( isPri... |
Twin Pythagorean triplets in an array | Function to check if there exist a twin pythagorean triplet in the given array ; Loop to check if there is a Pythagorean triplet in the array ; Check if there is consecutive triple ; Calculate square of array elements ; Driver Code ; Given array arr [ ] ; Function call | def isTriplet ( ar , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( abs ( ar [ i ] - ar [ j ] ) == 1 or abs ( ar [ j ] - ar [ k ] ) == 1 or abs ( ar [ i ] - ar [ k ] ) == 1 ) : NEW_LINE INDENT x = ar [ i ] *... |
Pair with min absolute difference and whose product is N + 1 or N + 2 | Python3 program for the above approach ; Function to prpair ( a , b ) such that a * b = N + 1 or N + 2 ; Loop to iterate over the desired possible values ; Check for condition 1 ; Check for condition 2 ; Driver Code ; Given Number ; Function Call | from math import sqrt , ceil , floor NEW_LINE def closestDivisors ( n ) : NEW_LINE INDENT for i in range ( ceil ( sqrt ( n + 2 ) ) , - 1 , - 1 ) : NEW_LINE INDENT if ( ( n + 1 ) % i == 0 ) : NEW_LINE INDENT print ( i , " , " , ( n + 1 ) // i ) NEW_LINE break NEW_LINE DEDENT if ( ( n + 2 ) % i == 0 ) : NEW_LINE INDENT p... |
Is it possible to reach N and M from 1 and 0 respectively as per given condition | Function that find given x and y is possible or not ; Check if x is less than 2 and y is not equal to 0 ; Perform subtraction ; Check if y is divisible by 2 and greater than equal to 0 ; Driver Code ; Given X and Y ; Function Call | def is_possible ( x , y ) : NEW_LINE INDENT if ( x < 2 and y != 0 ) : NEW_LINE INDENT return false NEW_LINE DEDENT y = y - x + 1 NEW_LINE if ( y % 2 == 0 and y >= 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDEN... |
Count of integers up to N which are non divisors and non coprime with N | Function to return the count of integers less than N satisfying given conditions ; Stores Euler counts ; Store Divisor counts ; Based on Sieve of Eratosthenes ; Update phi values of all multiples of i ; Update count of divisors ; Return the final... | def count ( n ) : NEW_LINE INDENT phi = [ 0 ] * ( n + 1 ) NEW_LINE divs = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT phi [ i ] += i NEW_LINE for j in range ( i * 2 , n + 1 , i ) : NEW_LINE INDENT phi [ j ] -= phi [ i ] ; NEW_LINE DEDENT for j in range ( i , n + 1 , i ) : NEW_LINE INDENT d... |
Sum of all differences between Maximum and Minimum of increasing Subarrays | Function to calculate and return the sum of differences of maximum and minimum of strictly increasing subarrays ; Stores the sum ; Traverse the array ; If last element of the increasing sub - array is found ; Update sum ; If the last element o... | def sum_of_differences ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE i = 0 NEW_LINE while ( i < N - 1 ) : NEW_LINE INDENT if arr [ i ] < arr [ i + 1 ] : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( i + 1 , N - 1 ) : NEW_LINE INDENT if arr [ j ] >= arr [ j + 1 ] : NEW_LINE INDENT sum += ( arr [ j ] - arr [ i ] ) ... |
Construct a Maximum Binary Tree from two given Binary Trees | A binary tree node has data , pointer to left child and a pointer to right child ; Helper method that allocates a new node with the given data and None left and right pointers . ; Given a binary tree , print its nodes in inorder ; first recur on left child ;... | class Node : NEW_LINE INDENT def __init__ ( self , data , left , right ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT return Node ( data , None , None ) ; NEW_LINE DEDENT def inorder ( node ) : NEW_LINE INDEN... |
Minimum size binary string required such that probability of deleting two 1 's at random is 1/X | Python3 implementation of the above approach ; Function returns the minimum size of the string ; From formula ; Left limit of r ; Right limit of r ; Smallest integer in the valid range ; Driver Code | from math import sqrt NEW_LINE def MinimumString ( x ) : NEW_LINE INDENT b = 1 NEW_LINE left_lim = sqrt ( x ) + 1.0 NEW_LINE right_lim = sqrt ( x ) + 2.0 NEW_LINE for i in range ( int ( left_lim ) , int ( right_lim ) + 1 ) : NEW_LINE INDENT if ( i > left_lim and i < right_lim ) : NEW_LINE INDENT r = i NEW_LINE break NE... |
Minimum number of squares whose sum equals to a given number N | Set | Python3 program for the above approach ; Function that returns True if N is a perfect square ; Function that returns True check if N is sum of three squares ; Factor out the powers of 4 ; N is NOT of the form 4 ^ a * ( 8 b + 7 ) ; Function that find... | from math import sqrt , floor , ceil NEW_LINE def isPerfectSquare ( N ) : NEW_LINE INDENT floorSqrt = floor ( sqrt ( N ) ) NEW_LINE return ( N == floorSqrt * floorSqrt ) NEW_LINE DEDENT def legendreFunction ( N ) : NEW_LINE INDENT while ( N % 4 == 0 ) : NEW_LINE INDENT N //= 4 NEW_LINE DEDENT if ( N % 8 != 7 ) : NEW_LI... |
Check if N leaves only distinct remainders on division by all values up to K | Function to check and return if all remainders are distinct ; Stores the remainder ; Calculate the remainder ; If remainder already occurred ; Insert into the set ; Driver Code | def is_distinct ( n , k ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT tmp = n % i NEW_LINE if ( tmp in s ) : NEW_LINE INDENT return False NEW_LINE DEDENT s . add ( tmp ) NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE... |
Count of multiplicative partitions of N | Function to return number of ways of factoring N with all factors greater than 1 ; Variable to store number of ways of factoring n with all factors greater than 1 ; Driver code ; 2 is the minimum factor of number other than 1. So calling recursive function to find number of way... | def getDivisors ( min , n ) : NEW_LINE INDENT total = 0 NEW_LINE for i in range ( min , n ) : NEW_LINE INDENT if ( n % i == 0 and n // i >= i ) : NEW_LINE INDENT total += 1 NEW_LINE if ( n // i > i ) : NEW_LINE INDENT total += getDivisors ( i , n // i ) NEW_LINE DEDENT DEDENT DEDENT return total NEW_LINE DEDENT if __na... |
Find last 2 survivors in N persons standing in a circle after killing next to immediate neighbour | Node for a Linked List ; Function to find the last 2 survivors ; Total is the count of alive people ; Initiating the list of n people ; Total != 2 is terminating condition because at last only two - person will remain al... | class newNode : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . val = val NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def getLastTwoPerson ( n ) : NEW_LINE INDENT total = n NEW_LINE head = newNode ( 1 ) NEW_LINE temp = head NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT temp . n... |
Philaland Coin | TCS Mockvita 2020 | Python3 implementation to find the minimum number of denominations required for any number ; Function to find the minimum number of denomminations required ; Driver Code ; Function call | from math import log2 , floor NEW_LINE def findMinDenomin ( n ) : NEW_LINE INDENT return log2 ( n ) + 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE print ( floor ( findMinDenomin ( n ) ) ) NEW_LINE DEDENT |
Content of a Polynomial | Python3 implementation to find the content of the polynomial ; Function to find the content of the polynomial ; Loop to iterate over the elements of the array ; __gcd ( a , b ) is a inbuilt function for Greatest Common Divisor ; Driver Code ; Function call | from math import gcd NEW_LINE def findContent ( arr , n ) : NEW_LINE INDENT content = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT content = gcd ( content , arr [ i ] ) NEW_LINE DEDENT return content NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE arr = [ 9 , 6 , 12 ] N... |
Check if the given array is same as its inverse permutation | Function to check if the inverse permutation of the given array is same as the original array ; Stores the inverse permutation ; Generate the inverse permutation ; Check if the inverse permutation is same as the given array ; Driver code | def inverseEqual ( arr , n ) : NEW_LINE INDENT brr = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT present_index = arr [ i ] - 1 NEW_LINE brr [ present_index ] = i + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] != brr [ i ] : NEW_LINE INDENT print ( " NO " ) NEW_LINE return NEW_LINE... |
Linear Congruence method for generating Pseudo Random Numbers | Function to generate random numbers ; Initialize the seed state ; Traverse to generate required numbers of random numbers ; Follow the linear congruential method ; Driver Code ; Seed value ; Modulus parameter ; Multiplier term ; Increment term ; Number of ... | def linearCongruentialMethod ( Xo , m , a , c , randomNums , noOfRandomNums ) : NEW_LINE INDENT randomNums [ 0 ] = Xo NEW_LINE for i in range ( 1 , noOfRandomNums ) : NEW_LINE INDENT randomNums [ i ] = ( ( randomNums [ i - 1 ] * a ) + c ) % m NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Xo =... |
Multiplicative Congruence method for generating Pseudo Random Numbers | Function to generate random numbers ; Initialize the seed state ; Traverse to generate required numbers of random numbers ; Follow the linear congruential method ; Driver Code ; Seed value ; Modulus parameter ; Multiplier term ; Number of Random nu... | def multiplicativeCongruentialMethod ( Xo , m , a , randomNums , noOfRandomNums ) : NEW_LINE INDENT randomNums [ 0 ] = Xo NEW_LINE for i in range ( 1 , noOfRandomNums ) : NEW_LINE INDENT randomNums [ i ] = ( randomNums [ i - 1 ] * a ) % m NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Xo = 3 N... |
Product of divisors of a number from a given list of its prime factors | Python3 program to implement the above approach ; Function to calculate ( a ^ b ) % m ; Function to calculate and return the product of divisors ; Stores the frequencies of prime divisors ; Iterate over the prime divisors ; Update the product ; Up... | from collections import defaultdict NEW_LINE MOD = 1000000007 NEW_LINE def power ( a , b , m ) : NEW_LINE INDENT a %= m NEW_LINE res = 1 NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( b & 1 ) : NEW_LINE INDENT res = ( ( res % m ) * ( a % m ) ) % m NEW_LINE DEDENT a = ( ( a % m ) * ( a % m ) ) % m NEW_LINE b >>= 1 NEW_... |
Print all proper fractions with denominators less than equal to N | Function to print all proper functions ; If the numerator and denominator are coprime ; Driver code | def printfractions ( n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n + 1 ) : NEW_LINE if __gcd ( i , j ) == 1 : NEW_LINE INDENT a = str ( i ) NEW_LINE b = str ( j ) NEW_LINE print ( a + ' / ' + b , end = " , β " ) NEW_LINE DEDENT DEDENT DEDENT def __gcd ( a , b ) : NEW_LINE I... |
Maximum number of objects that can be created as per given conditions | Function for finding the maximum number of objects from N type - 1 and M type - 2 items ; Storing minimum of N and M ; Storing maximum number of objects from given items ; Driver Code | def numberOfObjects ( N , M ) : NEW_LINE INDENT initial = min ( N , M ) NEW_LINE final = ( N + M ) // 3 NEW_LINE return min ( initial , final ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE M = 7 NEW_LINE print ( numberOfObjects ( N , M ) ) NEW_LINE DEDENT |
Square root of a number by Repeated Subtraction method | Function to return the square root of the given number ; Subtract n - th odd number ; Return the result ; Driver Code | def SquareRoot ( num ) : NEW_LINE INDENT count = 0 NEW_LINE for n in range ( 1 , num + 1 , 2 ) : NEW_LINE INDENT num = num - n NEW_LINE count = count + 1 NEW_LINE if ( num == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT N = 81 NEW_LINE print ( SquareRoot ( N ) ) NEW_LINE |
Maximize count of distinct elements possible in an Array from the given operation | Function to find the gcd of two numbers ; Function to calculate and return the count of maximum possible distinct elements in the array ; Find the maximum element ; Base Case ; Finding the gcd of first two element ; Calculate Gcd of the... | def gcd ( x , y ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT return y NEW_LINE DEDENT return gcd ( y % x , x ) NEW_LINE DEDENT def findDistinct ( arr , n ) : NEW_LINE INDENT maximum = max ( arr ) NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return ( maximum //... |
Find indices of all local maxima and local minima in an Array | Function to find all the local maxima and minima in the given array arr [ ] ; Empty lists to store points of local maxima and minima ; Checking whether the first point is local maxima or minima or neither ; Iterating over all points to check local maxima a... | def findLocalMaximaMinima ( n , arr ) : NEW_LINE INDENT mx = [ ] NEW_LINE mn = [ ] NEW_LINE if ( arr [ 0 ] > arr [ 1 ] ) : NEW_LINE INDENT mx . append ( 0 ) NEW_LINE DEDENT elif ( arr [ 0 ] < arr [ 1 ] ) : NEW_LINE INDENT mn . append ( 0 ) NEW_LINE DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ... |
Smallest N digit number with none of its digits as its divisor | Function to calculate power ; Function to check if the N - digit number satisfies the given condition or not ; Getting the last digit ; Every number is divisible by 1 and dividing a number by 0 isn 't possible. Thus numbers with 0 as a digit must be dis... | def power ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( b == 1 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT tmp = power ( a , b // 2 ) ; NEW_LINE result = tmp * tmp ; NEW_LINE if ( b % 2 == 1 ) : NEW_LINE INDENT result *= a ; NEW_LINE DEDENT return result ; NEW_LINE DEDEN... |
Cost of creating smallest subsequence with sum of difference between adjacent elements maximum | ; Initializing cost = 0 ; To store the removed element ; This will store the sum of the subsequence ; Checking all the element of the vector ; Storing the value of arr [ i ] in temp variable ; If the situation like arr [ i... | def costOfSubsequence ( N , arr , costArray ) : NEW_LINE INDENT i , temp , cost = 0 , 0 , 0 NEW_LINE removedElements = { ' ' } NEW_LINE ans = 0 NEW_LINE for i in range ( 1 , N - 1 ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE if ( ( ( arr [ i - 1 ] < temp ) and ( temp < arr [ i + 1 ] ) ) or ( ( arr [ i - 1 ] > temp ) a... |
XOR of a subarray ( range of elements ) | Set 2 | Function to find XOR in a range from L to R ; Compute xor from arr [ 0 ] to arr [ i ] ; Process every query in constant time ; If L == 0 ; Driver code ; query [ ] | def find_Xor ( arr , query , N , Q ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT arr [ i ] = arr [ i ] ^ arr [ i - 1 ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( Q ) : NEW_LINE INDENT if query [ i ] [ 0 ] == 0 : NEW_LINE INDENT ans = arr [ query [ i ] [ 1 ] ] NEW_LINE DEDENT else : NEW_LINE INDE... |
Generate an alternate increasing and decreasing Array | Function that returns generated array ; Dynamically allocate array ; START , END = 0 , N ; Iterate over array ; If Str [ i ] = = ' I ' assign arr [ i ] as START and increment START ; If str [ i ] = = ' D ' assign arr [ i ] as END and decrement END ; Assign A [ N ]... | def DiStirngMatch ( Str ) : NEW_LINE INDENT N = len ( Str ) NEW_LINE arr = ( N + 1 ) * [ 0 ] NEW_LINE START , END = 0 , N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( Str [ i ] == ' I ' ) : NEW_LINE INDENT arr [ i ] = START NEW_LINE START += 1 NEW_LINE DEDENT if ( Str [ i ] == ' D ' ) : NEW_LINE INDENT arr [ i ... |
Count of square free divisors of a given number | Python3 program to find the square free divisors of a given number ; The function to check if a number is prime or not ; If the number is even then its not prime ; Stores the count of distinct prime factors ; Print the number of square - free divisors | import math NEW_LINE def IsPrime ( i ) : NEW_LINE INDENT if ( i % 2 == 0 and i != 2 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT for j in range ( 3 , int ( math . sqrt ( i ) + 1 ) , 2 ) : NEW_LINE INDENT if ( i % j == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT return 1 ; NEW_LINE D... |
Generate Array whose difference of each element with its left yields the given Array | Function to find the sequence ; Initializing 1 st element ; Creating sequence in terms of x ; Finding min element ; Finding value of x ; Creating original sequence ; Output original sequence ; Driver code | def find_seq ( arr , m , n ) : NEW_LINE INDENT b = [ ] NEW_LINE x = 0 NEW_LINE b . append ( x ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT b . append ( x + arr [ i ] + b [ i ] ) NEW_LINE DEDENT mn = n NEW_LINE for i in range ( n ) : NEW_LINE INDENT mn = min ( mn , b [ i ] ) NEW_LINE DEDENT x = 1 - mn NEW_LINE ... |
Check whether count of odd and even factors of a number are equal | Python3 code for the naive approach ; Function to check condition ; Initialize even_count and od_count ; loop runs till square root ; Driver Code | import math NEW_LINE def isEqualFactors ( N ) : NEW_LINE INDENT ev_count = 0 NEW_LINE od_count = 0 NEW_LINE for i in range ( 1 , ( int ) ( math . sqrt ( N ) ) + 2 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( i == N // i ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT ev_count += 1 NEW_LINE DEDEN... |
Check whether count of odd and even factors of a number are equal | Function to check condition ; Driver Code | def isEqualFactors ( N ) : NEW_LINE INDENT if ( ( N % 2 == 0 ) and ( N % 4 != 0 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT N = 10 NEW_LINE isEqualFactors ( N ) NEW_LINE N = 125 ; NEW_LINE isEqualFactors ( N ) NEW_LINE |
Count of all values of N in [ L , R ] such that count of primes upto N is also prime | Function to count the number of crazy primes in the given range [ L , R ] ; Stores all primes ; Stores count of primes ; Stores if frequency of primes is a prime or not upto each index ; Sieve of Eratosthenes ; Count primes ; If i is... | def count_crazy_primes ( L , R ) : NEW_LINE INDENT prime = [ 0 ] * ( R + 1 ) NEW_LINE countPrime = [ 0 ] * ( R + 1 ) NEW_LINE freqPrime = [ 0 ] * ( R + 1 ) NEW_LINE prime [ 0 ] = prime [ 1 ] = 1 NEW_LINE p = 2 NEW_LINE while p * p <= R : NEW_LINE INDENT if ( prime [ p ] == 0 ) : NEW_LINE INDENT for i in range ( p * p ,... |
Largest N digit number in Base B | Function to print the largest N - digit numbers of base b ; Find the largest N digit number in base b using the formula B ^ N - 1 ; Print the largest number ; Given number and base ; Function Call | def findNumbers ( n , b ) : NEW_LINE INDENT largest = pow ( b , n ) - 1 NEW_LINE print ( largest ) NEW_LINE DEDENT N , B = 2 , 5 NEW_LINE findNumbers ( N , B ) NEW_LINE |
Generate an Array such with elements maximized through swapping bits | Function to generate the maximized array elements ; Traverse the array ; Iterate to count set and unset bits ; Count of unset bits ; Count of set bits ; Bitwise right shift ; Shifting all 1 ' s β to β MSB β β and β 0' s to LSB ; Driver Code | def maximizedArray ( arr , N ) : NEW_LINE INDENT i = 0 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT num = arr [ i ] NEW_LINE one = 0 NEW_LINE zero = 0 NEW_LINE while ( num ) : NEW_LINE INDENT if ( num % 2 == 0 ) : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT else : NEW_LINE INDENT one += 1 NEW_LINE DEDENT num = num >> 1 NEW... |
Find the ratio of LCM to GCD of a given Array | Python3 program to implement above approach ; Function to calculate and return GCD of the given array ; Initialise GCD ; Once GCD is 1 , it will always be 1 with all other elements ; Return GCD ; Function to calculate and return LCM of the given array ; Initialise LCM ; L... | import math NEW_LINE def findGCD ( arr , n ) : NEW_LINE INDENT gcd = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT gcd = int ( math . gcd ( arr [ i ] , gcd ) ) NEW_LINE if ( gcd == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return gcd NEW_LINE DEDENT def findLCM ( arr , n ) : NEW_LINE INDENT ... |
Minimum operations required to make all Array elements divisible by K | Python3 implementation to find the Minimum number of moves required to update the array such that each of its element is divisible by K ; Function to find the Minimum number of moves required to update the array such that each of its element is div... | from collections import defaultdict NEW_LINE def compute ( a , N , K ) : NEW_LINE INDENT eqVal = defaultdict ( int ) NEW_LINE maxX = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT val = a [ i ] % K NEW_LINE if ( val != 0 ) : NEW_LINE INDENT val = K - val NEW_LINE DEDENT if ( val == 0 ) : NEW_LINE INDENT continue NEW... |
Array sum after replacing all occurrences of X by Y for Q queries | Function that print the sum of the array for Q queries ; Stores the frequencies of array elements ; Calculate the sum of the initial array and store the frequency of each element in map ; Iterate for all the queries ; Store query values ; Decrement the... | def sumOfTheArrayForQuery ( A , N , X , Y , Q ) : NEW_LINE INDENT sum = 0 NEW_LINE count = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE if A [ i ] in count : NEW_LINE INDENT count [ A [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ A [ i ] ] = 1 NEW_LINE DEDENT DEDENT for i in... |
Maximum OR value of a pair in an Array | Set 2 | Function to return the maximum bitwise OR for any pair of the given array in O ( n ) time complexity . ; Find the maximum element in ; Stores the maximum OR value the array ; Traverse the array and perform Bitwise OR between every array element with the maximum element ;... | def maxOR ( arr , n ) : NEW_LINE INDENT max_value = max ( arr ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = max ( ans , ( max_value arr [ i ] ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 6 , 8 , 16 ] NEW_LINE n = len ( arr ) NEW_... |
Count of elements on the left which are divisible by current element | Set 2 | Utility function to prthe elements of the array ; Function to increment the count for each factor of given val ; Function to generate and print the required array ; Find max element of arr ; Create count array of maxi size ; For every elemen... | def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def IncrementFactors ( count , val ) : NEW_LINE INDENT i = 1 NEW_LINE while ( i * i <= val ) : NEW_LINE INDENT if ( val % i == 0 ) : NEW_LINE INDENT if ( i == val // i ) : NEW_LINE ... |
Minimum changes required to make all Array elements Prime | Function to generate all primes ; If p is a prime ; Mark all its multiples as non - prime ; Store all prime numbers ; Return the list of primes ; Function to calculate the minimum increments to convert every array elements to a prime ; Extract maximum element ... | def SieveOfEratosthenes ( n ) : NEW_LINE INDENT prime = [ True for i in range ( 2 * n + 1 ) ] NEW_LINE p = 2 NEW_LINE while ( p * p <= 2 * n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT i = p * p NEW_LINE while ( i <= n * 2 ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE i += p NEW_LINE DEDENT DEDE... |
Sum of multiples of Array elements within a given range [ L , R ] | Function to find the sum of all multiples of N up to K ; Calculate the sum ; Return the sum ; Function to find the total sum ; If L is divisible by a [ i ] ; Otherwise ; Return the final sum ; Driver code ; Given array arr [ ] ; Given range ; Function ... | def calcSum ( k , n ) : NEW_LINE INDENT value = ( k * n * ( n + 1 ) ) // 2 NEW_LINE return value NEW_LINE DEDENT def findSum ( a , n , L , R ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( L % a [ i ] == 0 and L != 0 ) : NEW_LINE INDENT sum += ( calcSum ( a [ i ] , R // a [ i ] ) - calc... |
Count all prime numbers in a given range whose sum of digits is also prime | Python3 program for the above approach ; Create an array for storing primes ; Create a prefix array that will contain whether sum is prime or not ; Function to find primes in the range and check whether the sum of digits of a prime number is p... | maxN = 1000000 NEW_LINE arr = [ 0 ] * ( 1000001 ) NEW_LINE prefix = [ 0 ] * ( 1000001 ) NEW_LINE def findPrimes ( ) : NEW_LINE INDENT for i in range ( 1 , maxN + 1 ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT arr [ 0 ] = 0 NEW_LINE arr [ 1 ] = 0 NEW_LINE i = 2 NEW_LINE while i * i <= maxN ... |
Find the concentration of a solution using given Mass and Volume | Function to calculate concentration from the given mass of solute and volume of a solution ; Driver code | def get_concentration ( mass , volume ) : NEW_LINE INDENT if ( volume == 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( mass / volume ) * 1000 ; NEW_LINE DEDENT DEDENT mass = 100.00 ; NEW_LINE volume = 500.00 ; NEW_LINE print ( get_concentration ( mass , volume ) ) NEW_LINE |
Practical Numbers | Python3 program to check if a number is Practical or not . ; Returns true if there is a subset of set [ ] with sun equal to given sum ; The value of subset [ i ] [ j ] will be true if there is a subset of set [ 0. . j - 1 ] with sum equal to i ; If sum is 0 , then answer is true ; If sum is not 0 an... | import math NEW_LINE def isSubsetSum ( Set , n , Sum ) : NEW_LINE INDENT subset = [ [ False for i in range ( Sum + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT subset [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , Sum + 1 ) : NEW_LINE INDENT subset [ 0 ] [ i ] = False NE... |
Super Niven Numbers | Checks if sums of all subsets of digits array divides the number N ; To calculate length of array arr ; There are totoal 2 ^ n subsets ; Consider all numbers from 0 to 2 ^ n - 1 ; Consider binary representation of current i to decide which elements to pick . ; Check sum of picked elements . ; Func... | def isDivBySubsetSums ( arr , num ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE total = 1 << n NEW_LINE i = 0 NEW_LINE while i < total : NEW_LINE INDENT sum = 0 NEW_LINE j = 0 NEW_LINE while j < n : NEW_LINE INDENT if ( i & ( 1 << j ) ) : NEW_LINE INDENT sum += arr [ j ] NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( sum !... |
Highly Composite Numbers | Function to count the number of divisors of the N ; Sieve method for prime calculation ; Traversing through all prime numbers ; Calculate number of divisor with formula total div = ( p1 + 1 ) * ( p2 + 1 ) * ... . . * ( pn + 1 ) where n = ( a1 ^ p1 ) * ( a2 ^ p2 ) . ... * ( an ^ pn ) ai being ... | def divCount ( n ) : NEW_LINE INDENT Hash = [ True for i in range ( n + 1 ) ] NEW_LINE p = 2 NEW_LINE while ( ( p * p ) < n ) : NEW_LINE INDENT if bool ( Hash [ p ] ) : NEW_LINE INDENT i = p * 2 NEW_LINE while i < n : NEW_LINE INDENT Hash [ i ] = False NEW_LINE i += p NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT total... |
Pentacontahenagon Number | Function to find the N - th Pentacontahenagon Number ; Driver Code ; Function Call | def PentacontahenagonNum ( N ) : NEW_LINE INDENT return ( 49 * N * N - 47 * N ) // 2 ; NEW_LINE DEDENT N = 3 ; NEW_LINE print ( "3rd β Pentacontahenagon β Number β is " , PentacontahenagonNum ( N ) ) ; NEW_LINE |
Saint | Function to check if a number is a Saint - Exupery number ; Considering triplets in sorted order . The value of first element in sorted triplet can be at - most n / 3. ; The value of second element must be less than equal to n / 2 ; Given Number N ; Function Call | def isSaintExuperyNum ( n ) : NEW_LINE INDENT for i in range ( 1 , ( n // 3 ) + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , ( n // 2 ) + 1 ) : NEW_LINE INDENT k = n / i / j NEW_LINE if i * i + j * j == k * k : NEW_LINE INDENT if i * j * k == n : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT DEDENT return... |
Repdigit Numbers | Function to check if a number is a Repdigit number ; To store previous digit ( Assigning initial value which is less than any digit ) ; Traverse all digits from right to left and check if any digit is smaller than previous . ; Driver code | def isRepdigit ( num , b ) : NEW_LINE INDENT prev = - 1 NEW_LINE while ( num ) : NEW_LINE INDENT digit = num % b NEW_LINE num //= b NEW_LINE if ( prev != - 1 and digit != prev ) : NEW_LINE INDENT return False NEW_LINE DEDENT prev = digit NEW_LINE DEDENT return True NEW_LINE DEDENT num = 2000 NEW_LINE base = 7 NEW_LINE ... |
Enlightened Numbers | Python3 implementation of the above approach ; Function to check if N is a Composite Number ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to return concatenation of distinct prime factors of a given number n ; Handle prime factor 2 explicitly so ... | import math NEW_LINE def isComposite ( n ) : NEW_LINE INDENT 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 ... |
Second Pentagonal numbers | Function to find N - th term in the series ; Driver code | def findNthTerm ( n ) : NEW_LINE INDENT print ( n * ( 3 * n + 1 ) // 2 , end = " β " ) ; NEW_LINE DEDENT N = 4 ; NEW_LINE findNthTerm ( N ) ; NEW_LINE |
Idoneal Numbers | Function to check if number is an Idoneal numbers ; Iterate for all triples pairs ( a , b , c ) ; If the condition is satisfied ; Driver Code ; Function call | def isIdoneal ( n ) : NEW_LINE INDENT for a in range ( 1 , n + 1 ) : NEW_LINE INDENT for b in range ( a + 1 , n + 1 ) : NEW_LINE INDENT for c in range ( b + 1 , n + 1 ) : NEW_LINE INDENT if ( a * b + b * c + c * a == n ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT DEDENT return True NEW_LINE DEDENT N =... |
Lynch | Python3 implementation for the above approach ; Function to check the divisibility of the number by its digit . ; If the digit divides the number then return true else return false . ; Function to check if all digits of n divide it or not ; Taking the digit of the number into digit var . ; Function to check if ... | import math NEW_LINE def checkDivisibility ( n , digit ) : NEW_LINE INDENT return ( ( digit != 0 ) and ( ( n % digit ) == 0 ) ) NEW_LINE DEDENT def isAllDigitsDivide ( n ) : NEW_LINE INDENT temp = n NEW_LINE while ( temp >= 1 ) : NEW_LINE INDENT digit = int ( temp % 10 ) NEW_LINE if ( checkDivisibility ( n , digit ) ==... |
Repunit numbers | Function to check if a number contains all the digits 0 , 1 , . . , ( b - 1 ) an equal number of times ; to store number of digits of n in base B ; to count frequency of digit 1 ; condition to check three or more 1 's and number of ones is equal to number of digits of n in base B ; Driver Code ; tak... | def isRepunitNum ( n , b ) : NEW_LINE INDENT length = 0 ; NEW_LINE countOne = 0 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT r = n % b ; NEW_LINE length += 1 ; NEW_LINE if ( r == 1 ) : NEW_LINE INDENT countOne += 1 ; NEW_LINE DEDENT n = n // b ; NEW_LINE DEDENT return countOne >= 3 and countOne == length ; NEW_LINE DE... |
Gapful Numbers | Python3 program for the above approach ; Find the first digit ; Find total number of digits - 1 ; Find first digit ; Return first digit ; Find the last digit ; return the last digit ; A function to check Gapful numbers ; Return true if n is gapful number ; Driver Code ; Given Number ; Function Call | import math NEW_LINE def firstDigit ( n ) : NEW_LINE INDENT digits = math . log10 ( n ) NEW_LINE n = ( n / math . pow ( 10 , digits ) ) NEW_LINE return n NEW_LINE DEDENT def lastDigit ( n ) : NEW_LINE INDENT return ( n % 10 ) NEW_LINE DEDENT def isGapful ( n ) : NEW_LINE INDENT concatenation = ( firstDigit ( n ) * 10 )... |
Economical Numbers | Python3 implementation to find Economical Numbers till n ; Array to store all prime less than and equal to MAX . ; Utility function for sieve of sundaram ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than MAX ,... | import math NEW_LINE MAX = 10000 NEW_LINE primes = [ ] NEW_LINE def sieveSundaram ( ) : NEW_LINE INDENT marked = [ 0 ] * ( MAX // 2 + 1 ) NEW_LINE for i in range ( 1 , ( int ( math . sqrt ( MAX ) ) - 1 ) // 2 + 1 ) : NEW_LINE INDENT j = ( i * ( i + 1 ) ) << 1 NEW_LINE while ( j <= MAX // 2 ) : NEW_LINE INDENT marked [ ... |
Check if all objects of type A and B can be placed on N shelves | Function to return if allocation is possible or not ; Stores the shelves needed for items of type - A and type - B ; Find number of shelves needed for items of type - A ; Fill A / K shelves fully by the items of type - A ; Otherwise ; Fill A / L shelves ... | def isPossible ( A , B , N , K , L ) : NEW_LINE INDENT needa = 0 NEW_LINE needb = 0 NEW_LINE if ( A % K == 0 ) : NEW_LINE INDENT needa = A // K ; NEW_LINE DEDENT else : NEW_LINE INDENT needa = A // K + 1 NEW_LINE DEDENT if ( B % L == 0 ) : NEW_LINE INDENT needb = B // L NEW_LINE DEDENT else : NEW_LINE INDENT needb = B ... |
Minimise N such that sum of count of all factors upto N is greater than or equal to X | Python3 program for the above approach ; Array to store smallest prime factors of each no . ; Function to calculate smallest prime factor of N . ; Marking spf [ j ] if it is not previously marked ; Array to store the count of factor... | MAX = 1000050 NEW_LINE spf = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE def calculate_SPF ( ) : NEW_LINE INDENT for i in range ( MAX + 1 ) : NEW_LINE INDENT spf [ i ] = i ; NEW_LINE DEDENT for i in range ( 4 , MAX + 1 , 2 ) : NEW_LINE INDENT spf [ i ] = 2 ; NEW_LINE DEDENT i = 3 NEW_LINE while ( i * i <= MAX ) : NEW_LIN... |
Check if the Matrix follows the given constraints or not | Stores true at prime indices ; Function to generate the prime numbers using Sieve of Eratosthenes ; If p is still true ; Mark all multiples of p ; Function returns sum of all elements of matrix ; Function to check if for all prime ( i + j ) , a [ i ] [ j ] is p... | prime = [ ] NEW_LINE def buildSieve ( sum ) : NEW_LINE INDENT global prime NEW_LINE prime = [ True for i in range ( sum + 1 ) ] NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while ( p * p < ( sum + 1 ) ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , ... |
How to calculate the Easter date for a given year using Gauss ' Algorithm | Python3 program for the above approach ; Function calculates and prints easter date for given year Y ; All calculations done on the basis of Gauss Easter Algorithm ; A corner case , when D is 29 ; Another corner case , when D is 28 ; If days > ... | import math NEW_LINE def gaussEaster ( Y ) : NEW_LINE INDENT A = Y % 19 NEW_LINE B = Y % 4 NEW_LINE C = Y % 7 NEW_LINE P = math . floor ( Y / 100 ) NEW_LINE Q = math . floor ( ( 13 + 8 * P ) / 25 ) NEW_LINE M = ( 15 - Q + P - P // 4 ) % 30 NEW_LINE N = ( 4 + P - P // 4 ) % 7 NEW_LINE D = ( 19 * A + M ) % 30 NEW_LINE E ... |
Min steps to convert N | Python3 program for the above problem ; Adjacency list for numbers till 100001 ; Visited array ; To store distance of every vertex from A ; Function to check if number is a prime ; Function to check if numbers differ by only a single - digit ; Check the last digit of both numbers and increase c... | mod = 1000000007 NEW_LINE lis = [ [ ] for i in range ( 100001 ) ] NEW_LINE primes = [ ] NEW_LINE vis = [ 0 for i in range ( 100001 ) ] NEW_LINE dis = [ 0 for i in range ( 100001 ) ] NEW_LINE def isPrime ( n ) : NEW_LINE INDENT i = 2 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT ret... |
Place Value of a given digit in a number | Function to find place value ; Digit , which we want to find place value . ; Number from where we want to find place value . | def placeValue ( N , num ) : NEW_LINE INDENT total = 1 NEW_LINE value = 0 NEW_LINE rem = 0 NEW_LINE while ( True ) : NEW_LINE INDENT rem = N % 10 NEW_LINE N = N // 10 NEW_LINE if ( rem == num ) : NEW_LINE INDENT value = total * rem NEW_LINE break NEW_LINE DEDENT total = total * 10 NEW_LINE DEDENT return value NEW_LINE ... |
Super | Python3 implementation to check if N is a super Poulet number ; Function to find the divisors ; Loop to iterate over the square root of the N ; Check if divisors are equal ; Function to check if N is a super Poulet number ; Loop to check that every divisor divides 2 ^ D - 2 ; Driver Code | import math NEW_LINE def findDivisors ( n ) : NEW_LINE INDENT divisors = [ ] NEW_LINE for i in range ( 1 , int ( math . sqrt ( n ) + 1 ) ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n / i == i ) : NEW_LINE INDENT divisors . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT divisors . append ( i ) NEW_... |
Beatty sequence | Python3 implementation of the above approach ; Function to print the first N terms of the Beatty sequence ; Driver code | import math NEW_LINE def BeattySequence ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = math . floor ( i * math . sqrt ( 2 ) ) NEW_LINE print ( ans , end = ' , β ' ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE BeattySequence ( n ) NEW_LINE |
Sum of the first N Pronic Numbers | Function to calculate the sum ; Driver code | def calculateSum ( N ) : NEW_LINE INDENT return ( N * ( N - 1 ) // 2 + N * ( N - 1 ) * ( 2 * N - 1 ) // 6 ) ; NEW_LINE DEDENT N = 3 ; NEW_LINE print ( calculateSum ( N ) ) ; NEW_LINE |
Self Numbers | Function to find the sum of digits of a number N ; Function to check for Self number ; Driver code | def getSum ( n ) : NEW_LINE INDENT sum1 = 0 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT sum1 = sum1 + n % 10 ; NEW_LINE n = n // 10 ; NEW_LINE DEDENT return sum1 ; NEW_LINE DEDENT def isSelfNum ( n ) : NEW_LINE INDENT for m in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( m + getSum ( m ) == n ) : NEW_LINE INDENT return... |
Central binomial coefficient | Function to find the value of Nth Central Binomial Coefficient ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Driver code | def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ [ 0 for j in range ( k + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE i = 0 NEW_LINE j = 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 DEDENT e... |
Multiply perfect number | Python3 implementation of the above approach ; Function to find the sum of divisors ; Note that this loop runs till square root of N ; If divisors are equal , take only one of them ; Otherwise take both ; Function to check Multiply - perfect number ; Driver code | import math NEW_LINE def getSum ( n ) : NEW_LINE INDENT sum1 = 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 sum1 = sum1 + i ; NEW_LINE DEDENT else : NEW_LINE INDENT sum1 = sum1 + i ; NEW_LINE sum1 = sum1 + ( n //... |
Perfect totient number | Function to find the Totient number of the given value ; Initialize result as n ; Consider all prime factors of n and subtract their multiples from result ; Check if p is a prime factor . ; If yes , then update N and result ; If n has a prime factor greater than sqrt ( n ) ( There can be at - m... | def phi ( n ) : NEW_LINE INDENT result = n NEW_LINE for p in range ( 2 , n ) : NEW_LINE INDENT if p * p > n : NEW_LINE INDENT break NEW_LINE DEDENT if ( n % p == 0 ) : NEW_LINE INDENT while ( n % p == 0 ) : NEW_LINE INDENT n //= p NEW_LINE DEDENT result -= result // p NEW_LINE DEDENT DEDENT if ( n > 1 ) : NEW_LINE INDE... |
Cunningham Numbers | Python3 implementation for the above approach ; Function to check if a number can be expressed as a ^ b . ; Function to check if N is a Cunningham number ; Given Number ; Function Call | import math NEW_LINE def isPower ( a ) : NEW_LINE INDENT if ( a == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT i = 2 NEW_LINE while ( i * i <= a ) : NEW_LINE INDENT val = math . log ( a ) / math . log ( i ) NEW_LINE if ( ( val - int ( val ) ) < 0.00000001 ) : NEW_LINE INDENT return True NEW_LINE DEDENT i += 1 NEW... |
Product of all Subarrays of an Array | Set 2 | Function to find the product of elements of all subarray ; Initialize the result ; Computing the product of subarray using formula ; Return the product of all elements of each subarray ; Given array arr [ ] ; Function Call | def SubArrayProdct ( arr , n ) : NEW_LINE INDENT result = 1 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT result *= pow ( arr [ i ] , ( i + 1 ) * ( n - i ) ) ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT arr = [ 2 , 4 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( SubArrayProdct ( arr , N ) ) NEW_LINE |
Number of ways to reach ( M , N ) in a matrix starting from the origin without visiting ( X , Y ) | Function for computing nCr ; Function to find factorial of a number ; Function for counting the number of ways to reach ( m , n ) without visiting ( x , y ) ; Given dimensions of Matrix ; Cell not to be visited ; Functio... | def nCr ( n , r ) : NEW_LINE INDENT return ( fact ( n ) // ( fact ( r ) * fact ( n - r ) ) ) NEW_LINE DEDENT def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def countWays ( m , n , x , y ) : NEW_LINE INDENT return ... |
Smallest number greater than or equal to N using only digits 1 to K | Function to count the digits greater than K ; Function to print the list ; Function to find the number greater than or equal to n , which is only made of first k digits ; If the number itself satisfy the conditions ; Check digit from back ; If digit ... | def CountGreater ( n , k ) : NEW_LINE INDENT a = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( ( n % 10 ) > k ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT n = n // 10 NEW_LINE DEDENT return a NEW_LINE DEDENT def PrintList ( ans ) : NEW_LINE INDENT for i in ans : NEW_LINE INDENT print ( i , end = ' ' ) NEW_LINE DEDENT... |
Find the Batting Average of a batsman | Function to find the average of a batsman ; Calculate number of dismissals ; check for 0 times out ; Calculate batting average ; Driver Program | def averageRuns ( runs , matches , notout ) : NEW_LINE INDENT out = matches - notout ; NEW_LINE if ( out == 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT avg = runs // out ; NEW_LINE return avg ; NEW_LINE DEDENT runs = 10000 ; NEW_LINE matches = 250 ; NEW_LINE notout = 50 ; NEW_LINE avg = averageRuns ( runs , matc... |
Sum of series formed by difference between product and sum of N natural numbers | Recursive Function to calculate the sum upto Nth term ; If N - th term is calculated ; Update multi to store product upto K ; Update add to store sum upto K ; Update prevSum to store sum upto K ; Proceed to next K ; Function to calculate ... | def seriesSumUtil ( k , n , prevSum , multi , add ) : NEW_LINE INDENT if ( k == n + 1 ) : NEW_LINE INDENT return prevSum ; NEW_LINE DEDENT multi = multi * k ; NEW_LINE add = add + k ; NEW_LINE prevSum = prevSum + multi - add ; NEW_LINE return seriesSumUtil ( k + 1 , n , prevSum , multi , add ) ; NEW_LINE DEDENT def ser... |
Count of total bits toggled / flipped in binary representation of 0 to N | Function to count and pr the required number of toggles ; Store the count of toggles ; Add the contribution of the current LSB ; Update N ; Print the result ; Driver code | def solve ( N ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( N != 0 ) : NEW_LINE INDENT ans += N NEW_LINE N //= 2 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT N = 5 NEW_LINE solve ( N ) NEW_LINE |
Maximum Bitwise AND pair ( X , Y ) from given range such that X and Y can be same | Function to return the maximum bitwise AND ; Driver code | def maximumAND ( L , R ) : NEW_LINE INDENT return R NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l = 3 NEW_LINE r = 7 NEW_LINE print ( maximumAND ( l , r ) ) NEW_LINE DEDENT |
Check if K distinct array elements form an odd sum | Function to return if odd sum is possible or not ; Stores distinct odd elements ; Stores distinct even elements ; Iterating through given array ; If element is even ; If element is odd ; If atleast K elements in the array are odd ; Check for all odd frequencies of od... | def oddSum ( A , N , K ) : NEW_LINE INDENT Odd = set ( [ ] ) NEW_LINE Even = set ( [ ] ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] % 2 == 0 ) : NEW_LINE INDENT Even . add ( A [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT Odd . add ( A [ i ] ) NEW_LINE DEDENT DEDENT if ( len ( Odd ) >= K ) : 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 of same array ; Length for boolean array ; Hash map for storing the element and it 's frequency ; Update the maximum element ; Boolean array of size of the max ... | def countEle ( a , n ) : NEW_LINE INDENT len = 0 NEW_LINE hmap = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT len = max ( len , a [ i ] ) NEW_LINE hmap [ a [ i ] ] = hmap . get ( a [ i ] , 0 ) + 1 NEW_LINE DEDENT v = [ True for i in range ( len + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( v [ a [... |
Smallest N digit number divisible by N | Function to find the smallest N - digit number divisible by N ; Find largest n digit number ; Find smallest n digit number ; If i is divisible by N , then print i and return ; ; Driver Code ; Given number ; Function call | def smallestNumber ( N ) : NEW_LINE INDENT L = pow ( 10 , N ) - 1 ; NEW_LINE S = pow ( 10 , N - 1 ) ; NEW_LINE for i in range ( S , L ) : NEW_LINE INDENT if ( i % N == 0 ) : NEW_LINE INDENT print ( i ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 ; NEW_LINE s... |
Number less than equals to N with maximum product of prime factors | Function to find the smallest number having a maximum product of prime factors ; Declare the list arr ; Initialise list with 1 ; Iterate from [ 2 , N ] ; If value at index i is 1 , then i is prime and make update list at index for all multiples of i ;... | def maxPrimefactorNum ( N ) : NEW_LINE INDENT arr = [ ] NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT arr . append ( 1 ) NEW_LINE DEDENT for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT for j in range ( i , N + 1 , i ) : NEW_LINE INDENT arr [ j ] *= i NEW_LINE DEDENT DEDENT D... |
Zuckerman Numbers | Function to get product of digits ; Function to check if N is an Zuckerman number ; Driver code | def getProduct ( n ) : NEW_LINE INDENT product = 1 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT product = product * ( n % 10 ) NEW_LINE n = n // 10 NEW_LINE DEDENT return product NEW_LINE DEDENT def isZuckerman ( n ) : NEW_LINE INDENT return n % getProduct ( n ) == 0 NEW_LINE DEDENT N = 115 NEW_LINE if ( isZuckerman ( N ... |
Additive Prime Number | Check if N is prime or not ; Corner Cases ; This is checked to skip middle five numbers ; Function to get sum of digits ; Return the sum of digits ; Function to check whether the given number is Additive Prime number or not ; If number is not prime ; Check if sum of digits is prime or not ; Give... | 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... |
Straight | Function to check if N is a Straight Line number or not ; N must be > 99 ; Difference between consecutive digits must be same ; Given Number N ; Function Call | def isStraighLineNum ( N ) : NEW_LINE INDENT if ( N <= 99 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT str1 = str ( N ) ; NEW_LINE d = int ( str1 [ 1 ] ) - int ( str1 [ 0 ] ) ; NEW_LINE for i in range ( 2 , len ( str1 ) ) : NEW_LINE INDENT if ( int ( str1 [ i ] ) - int ( str1 [ i - 1 ] ) != d ) : NEW_LINE INDENT ... |
Second | Function to find N - th term in the series ; Driver Code | def findNthTerm ( n ) : NEW_LINE INDENT print ( pow ( 2 , n ) - 2 * n ) ; NEW_LINE DEDENT N = 4 ; NEW_LINE findNthTerm ( N ) ; NEW_LINE |
Alternating Numbers | Function to check if a string is of the form even odd even odd ... ; Function to check if a string is of the form odd even odd even ... ; Function to check if n is an alternating number ; Given Number N ; Function Call | def isEvenOddForm ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 and int ( s [ i ] ) % 2 != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( i % 2 == 1 and int ( s [ i ] ) % 2 != 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE ... |
Ormiston prime Pairs | Function to check if the number is a prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to update the frequency array such that freq [ i ] stores the frequency of digit i in n ; While there are digits left to process ; Update the frequen... | 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... |
Decakismyriagon Number | Function to find the N - th Decakismyriagon Number ; Given Number N ; Function Call | def DecakismyriagonNum ( N ) : NEW_LINE INDENT return ( 99998 * N * N - 99996 * N ) // 2 ; NEW_LINE DEDENT N = 3 ; NEW_LINE print ( DecakismyriagonNum ( N ) ) ; NEW_LINE |
Zygodrome Number | Function to check if N is an zygodrome number ; Convert N to string ; Adding a space at the beginning and end of the string ; Traverse the string ; If any character is not same as prev and next then return false ; Driver code | def iszygodromeNum ( N ) : NEW_LINE INDENT s = str ( N ) ; NEW_LINE s = ' β ' + s + ' β ' ; NEW_LINE i = 1 NEW_LINE while i < len ( s ) - 1 : NEW_LINE INDENT if ( ( s [ i ] != s [ i - 1 ] ) and ( s [ i ] != s [ i + 1 ] ) ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return True ; NEW_LINE DE... |
Loeschian Number | Python3 program for the above approach ; Function to check if N is a Loeschian Number ; Iterate [ 0 , sqrt ( N ) ] for x ; Iterate [ 0 , sqrt ( N ) ] for y ; Check the given criteria ; If no such pair found then return false ; Given Number N ; Function Call | import math NEW_LINE def isLoeschian ( n ) : NEW_LINE INDENT for x in range ( 1 , ( int ) ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT for y in range ( 1 , ( int ) ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( x * x + x * y + y * y == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NE... |
Program to print the series 2 , 15 , 41 , 80 , 132 , 197 β¦ till N terms | Function to print the series ; Generate the ith term and ; Driver Code | def printSeries ( N ) : NEW_LINE INDENT ith_term = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT ith_term = ( 13 * i * ( i - 1 ) ) / 2 + 2 ; NEW_LINE print ( int ( ith_term ) , " , β " , end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 ; NEW_LINE printSeries ( N... |
Possible pairs forming a Pythagorean Triple with a given value | Function to generate all possible pairs ; Vector to store all the possible pairs ; Checking all the possible pair in the range of [ 1 , c ) ; If the pair satisfies the condition push it in the vector ; Driver code ; If no valid pair exist ; Print all vali... | def Pairs ( C ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in range ( C ) : NEW_LINE INDENT for j in range ( i + 1 , C ) : NEW_LINE INDENT if ( ( i * i ) + ( j * j ) == ( C * C ) ) : NEW_LINE INDENT ans . append ( [ i , j ] ) NEW_LINE DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : N... |
How to calculate strike rate of a batsman | function to calculate strike rate of a batsman ; Driver Code | def strikerate ( bowls , runs ) : NEW_LINE INDENT z = ( float ( runs ) / bowls ) * 100 ; NEW_LINE return z ; NEW_LINE DEDENT A = 264 ; NEW_LINE B = 173 ; NEW_LINE print ( strikerate ( B , A ) ) ; NEW_LINE |
Check if a number exists with X divisors out of which Y are composite | Python3 program to check if a number exists having exactly X positive divisors out of which Y are composite divisors ; Count the number of times 2 divides N ; Check for all possible numbers that can divide it ; If N at the end is a prime number . ;... | import math NEW_LINE def factorize ( N ) : NEW_LINE INDENT count = 0 NEW_LINE cnt = 0 NEW_LINE while ( ( N % 2 ) == 0 ) : NEW_LINE INDENT N = N // 2 NEW_LINE count += 1 NEW_LINE DEDENT cnt = cnt + count NEW_LINE sq = int ( math . sqrt ( N ) ) NEW_LINE for i in range ( 3 , sq , 2 ) : NEW_LINE INDENT count = 0 NEW_LINE w... |
Nearest prime number in the array of every array element | Python3 program to find nearest prime number in the array for all array elements ; Create a boolean array and set all entries it as false . A value in prime [ i ] will be true if i is not a prime , else false ; Sieve of Eratosthenes function ; Update all multip... | maxi = 10000000 NEW_LINE prime = [ False ] * ( maxi ) NEW_LINE def SieveOfEratosthenes ( maxm ) : NEW_LINE INDENT prime [ 0 ] = prime [ 1 ] = True NEW_LINE for i in range ( 2 , maxm + 1 ) : NEW_LINE INDENT if i * i > maxm : NEW_LINE INDENT break NEW_LINE DEDENT if ( not prime [ i ] ) : NEW_LINE INDENT for j in range ( ... |
Find position of given term in a series formed with only digits 4 and 7 allowed | Function to find the position of the number N ; To store the position of N ; Iterate through all digit of N ; If current digit is 7 ; If current digit is 4 ; Print the final position ; Driver Code ; Given number of the series ; Function C... | def findPosition ( n ) : NEW_LINE INDENT i = 0 NEW_LINE pos = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( n % 10 == 7 ) : NEW_LINE INDENT pos = pos + pow ( 2 , i + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT pos = pos + pow ( 2 , i ) NEW_LINE DEDENT i += 1 NEW_LINE n = n // 10 NEW_LINE DEDENT print ( pos ) NEW_LIN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.