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 digits forward ; Print the result ; Driver Code
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 = modPower ( N , K , int ( pow ( 10 , M ) ) ) NEW_LINE firstM = 0 NEW_LINE y = K * log10 ( N * 1.0 ) NEW_LINE y = y - int ( y ) NEW_LINE temp = pow ( 10.0 , y ) NEW_LINE firstM = int ( temp * pow ( 10 , M - 1 ) ) NEW_LINE print ( firstM , lastM ) NEW_LINE DEDENT N = 12 NEW_LINE K = 12 NEW_LINE M = 4 NEW_LINE findFirstAndLastM ( N , K , M ) NEW_LINE
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 make all modulo equal ; Iterating through all possible modulo value ; Iterating through all different modulo obtained so far ; Calculating oprn required to make all modulos equal to x ; Checking the operations that will cost less ; Check operation that will cost less ; Update the minimum number of operations ; Returning the answer ; Function to store different modulos ; Set to store all different modulo ; Map to store count of all different modulo obtained ; Storing all different modulo count ; Insert into the set ; Increment count ; Function call to return value of min oprn required ; Driver Code
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 ) : NEW_LINE INDENT oprn += ( min ( x , k - x ) * count_mod [ w ] ) NEW_LINE DEDENT else : NEW_LINE INDENT oprn += ( min ( abs ( x - w ) , k + x - w ) * count_mod [ w ] ) NEW_LINE DEDENT DEDENT DEDENT if ( oprn < min_oprn ) : NEW_LINE INDENT min_oprn = oprn NEW_LINE DEDENT DEDENT return min_oprn NEW_LINE DEDENT def Cal_min ( arr , n , k ) : NEW_LINE INDENT diff_mod = set ( [ ] ) NEW_LINE count_mod = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT diff_mod . add ( arr [ i ] % k ) NEW_LINE count_mod [ arr [ i ] % k ] += 1 NEW_LINE DEDENT return Find_min ( diff_mod , count_mod , k ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 35 , 48 , 23 , 52 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( Cal_min ( arr , n , k ) ) NEW_LINE DEDENT
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 for each element to reach its sorted position ; Calculate LCM of the array ; Driver Code
def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def 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 return ans NEW_LINE DEDENT def minimumSteps ( arr , n ) : NEW_LINE INDENT dat = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dat [ arr [ i - 1 ] ] = i NEW_LINE DEDENT b = [ 0 ] * ( n + 1 ) NEW_LINE j = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT c = 1 NEW_LINE j = dat [ i ] NEW_LINE while ( j != i ) : NEW_LINE INDENT c += 1 NEW_LINE j = dat [ j ] NEW_LINE DEDENT b [ i ] = c NEW_LINE DEDENT print ( findlcm ( b , n ) ) NEW_LINE DEDENT arr = [ 5 , 1 , 4 , 3 , 2 , 7 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE minimumSteps ( arr , N ) NEW_LINE
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 ; Calculate the ratio ; Update max ratio ; Print the answer ; Driver code
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 = arr [ i ] NEW_LINE for k in range ( i + 1 , j + 1 ) : NEW_LINE INDENT ratio = ratio // arr [ k ] NEW_LINE DEDENT maxRatio = maximum ( maxRatio , ratio ) NEW_LINE DEDENT DEDENT return int ( maxRatio ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 2 , 4 , - 0.2 , - 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSubarrayRatio ( arr , n ) ) NEW_LINE DEDENT
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 it is equal to 2 or 3 ; Check if it can be divided by 2 and 3 then it is not prime number ; Check whether the given number be divide by other prime numbers ; Driver Code
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 ( isPrime ( ( int ) ( pow ( 2 , poww + 1 ) ) - 1 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return bool ( False ) NEW_LINE DEDENT elif ( n == 2 or n == 3 ) : NEW_LINE INDENT return bool ( True ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return bool ( False ) NEW_LINE DEDENT for i in range ( 5 , sqrt ( n + 1 ) + 1 , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return bool ( False ) NEW_LINE DEDENT DEDENT return bool ( True ) NEW_LINE DEDENT DEDENT num = 6 NEW_LINE check ( num ) NEW_LINE
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 ] * ar [ i ] NEW_LINE y = ar [ j ] * ar [ j ] NEW_LINE z = ar [ k ] * ar [ k ] NEW_LINE if ( x == y + z or y == x + z or z == x + y ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 1 , 4 , 6 , 5 ] NEW_LINE ar_size = len ( arr ) NEW_LINE if isTriplet ( arr , ar_size ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT DEDENT
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 print ( i , " , " , ( n + 2 ) // i ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 123 NEW_LINE closestDivisors ( N ) NEW_LINE DEDENT
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 INDENT x = 5 NEW_LINE y = 2 NEW_LINE if ( is_possible ( x , y ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 count ; Driver code
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 divs [ j ] += 1 NEW_LINE DEDENT DEDENT return ( n - phi [ n ] - divs [ n ] + 1 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 42 NEW_LINE print ( count ( N ) ) NEW_LINE DEDENT
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 of the array is reached ; Update sum ; Return the sum ; Driver Code
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 ] ) NEW_LINE i = j NEW_LINE flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if flag == 0 and arr [ i ] < arr [ N - 1 ] : NEW_LINE INDENT sum += ( arr [ N - 1 ] - arr [ i ] ) NEW_LINE break NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT arr = [ 6 , 1 , 2 , 5 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( sum_of_differences ( arr , N ) ) NEW_LINE
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 ; then print the data of node ; now recur on right child ; Method to find the maximum binary tree from two binary trees ; Driver Code ; First Binary Tree 3 / \ 2 6 / 20 ; Second Binary Tree 5 / \ 1 8 \ \ 2 8
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 INDENT if ( node == None ) : NEW_LINE INDENT return ; NEW_LINE DEDENT inorder ( node . left ) ; NEW_LINE print ( node . data , end = ' ▁ ' ) ; NEW_LINE inorder ( node . right ) ; NEW_LINE DEDENT def MaximumBinaryTree ( t1 , t2 ) : NEW_LINE INDENT if ( t1 == None ) : NEW_LINE INDENT return t2 ; NEW_LINE DEDENT if ( t2 == None ) : NEW_LINE INDENT return t1 ; NEW_LINE DEDENT t1 . data = max ( t1 . data , t2 . data ) ; NEW_LINE t1 . left = MaximumBinaryTree ( t1 . left , t2 . left ) ; NEW_LINE t1 . right = MaximumBinaryTree ( t1 . right , t2 . right ) ; NEW_LINE return t1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = newNode ( 3 ) ; NEW_LINE root1 . left = newNode ( 2 ) ; NEW_LINE root1 . right = newNode ( 6 ) ; NEW_LINE root1 . left . left = newNode ( 20 ) ; NEW_LINE root2 = newNode ( 5 ) ; NEW_LINE root2 . left = newNode ( 1 ) ; NEW_LINE root2 . right = newNode ( 8 ) ; NEW_LINE root2 . left . right = newNode ( 2 ) ; NEW_LINE root2 . right . right = newNode ( 8 ) ; NEW_LINE root3 = MaximumBinaryTree ( root1 , root2 ) ; NEW_LINE inorder ( root3 ) ; NEW_LINE DEDENT
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 NEW_LINE DEDENT DEDENT return b + r NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 2 NEW_LINE print ( MinimumString ( X ) ) NEW_LINE DEDENT
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 finds the minimum number of square whose sum is N ; If N is perfect square ; If N is sum of 2 perfect squares ; If N is sum of 3 perfect squares ; Otherwise , N is the sum of 4 perfect squares ; Driver code ; Given number ; Function call
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_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def minSquares ( N ) : NEW_LINE INDENT if ( isPerfectSquare ( N ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if i * i < N : NEW_LINE INDENT break NEW_LINE DEDENT if ( isPerfectSquare ( N - i * i ) ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT DEDENT if ( legendreFunction ( N ) ) : NEW_LINE INDENT return 3 NEW_LINE DEDENT return 4 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 123 NEW_LINE print ( minSquares ( N ) ) NEW_LINE DEDENT
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 K = 3 NEW_LINE if ( is_distinct ( N , K ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 ways of factoring N with all factors greater than 1
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 __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 30 NEW_LINE print ( 1 + getDivisors ( 2 , n ) ) NEW_LINE DEDENT
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 alive ; de represent next person to be deleted or killed ; Last two person to survive ( in any order ) ; Driver code
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 . next = newNode ( i ) NEW_LINE temp = temp . next NEW_LINE DEDENT temp . next = head NEW_LINE temp = head NEW_LINE de = None NEW_LINE while ( total != 2 ) : NEW_LINE INDENT de = temp . next . next NEW_LINE temp . next . next = temp . next . next . next NEW_LINE temp = temp . next NEW_LINE del de NEW_LINE total -= 1 NEW_LINE DEDENT print ( temp . val , temp . next . val ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 NEW_LINE getLastTwoPerson ( n ) NEW_LINE DEDENT
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 ] NEW_LINE print ( findContent ( arr , n ) ) NEW_LINE DEDENT
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 DEDENT DEDENT print ( " YES " ) NEW_LINE DEDENT n = 4 NEW_LINE arr = [ 1 , 4 , 3 , 2 ] NEW_LINE inverseEqual ( arr , n ) 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 Random numbers to be generated ; To store random numbers ; Function Call ; Print the generated random numbers
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 = 5 NEW_LINE m = 7 NEW_LINE a = 3 NEW_LINE c = 3 NEW_LINE noOfRandomNums = 10 NEW_LINE randomNums = [ 0 ] * ( noOfRandomNums ) NEW_LINE linearCongruentialMethod ( Xo , m , a , c , randomNums , noOfRandomNums ) NEW_LINE for i in randomNums : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT
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 numbers to be generated ; To store random numbers ; Function Call ; Print the generated random numbers
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 NEW_LINE m = 15 NEW_LINE a = 7 NEW_LINE noOfRandomNums = 10 NEW_LINE randomNums = [ 0 ] * ( noOfRandomNums ) NEW_LINE multiplicativeCongruentialMethod ( Xo , m , a , randomNums , noOfRandomNums ) NEW_LINE for i in randomNums : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT
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 ; Update the count of divisors ; Driver Code
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_LINE DEDENT return res % m NEW_LINE DEDENT def productOfDivisors ( p , n ) : NEW_LINE INDENT prime = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT prime [ p [ i ] ] += 1 NEW_LINE DEDENT product , d = 1 , 1 NEW_LINE for itr in prime . keys ( ) : NEW_LINE INDENT val = ( power ( itr , ( prime [ itr ] ) * ( prime [ itr ] + 1 ) // 2 , MOD ) ) NEW_LINE product = ( power ( product , prime [ itr ] + 1 , MOD ) * power ( val , d , MOD ) % MOD ) NEW_LINE d = ( d * ( prime [ itr ] + 1 ) ) % ( MOD - 1 ) NEW_LINE DEDENT return product NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 11 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE print ( productOfDivisors ( arr , n ) ) NEW_LINE DEDENT
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 INDENT if b == 0 : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return __gcd ( b , a % b ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE printfractions ( n ) NEW_LINE DEDENT
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 array ; Return the total count of distinct elements ; Driver Code
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 // gcd ( arr [ 0 ] , arr [ 1 ] ) ) NEW_LINE DEDENT k = gcd ( arr [ 0 ] , arr [ 1 ] ) NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT k = gcd ( k , arr [ i ] ) NEW_LINE DEDENT return ( maximum // k ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findDistinct ( arr , n ) ) NEW_LINE DEDENT
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 and local minima ; Condition for local minima ; Condition for local maxima ; Checking whether the last point is local maxima or minima or neither ; Print all the local maxima and local minima indexes stored ; Driver Code ; Given array arr [ ] ; Function Call
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 ] > arr [ i ] < arr [ i + 1 ] ) : NEW_LINE INDENT mn . append ( i ) NEW_LINE DEDENT elif ( arr [ i - 1 ] < arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT mx . append ( i ) NEW_LINE DEDENT DEDENT if ( arr [ - 1 ] > arr [ - 2 ] ) : NEW_LINE INDENT mx . append ( n - 1 ) NEW_LINE DEDENT elif ( arr [ - 1 ] < arr [ - 2 ] ) : NEW_LINE INDENT mn . append ( n - 1 ) NEW_LINE DEDENT if ( len ( mx ) > 0 ) : NEW_LINE INDENT print ( " Points ▁ of ▁ Local ▁ maxima " \ " ▁ are ▁ : ▁ " , end = ' ' ) NEW_LINE print ( * mx ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " There ▁ are ▁ no ▁ points ▁ of " \ " ▁ Local ▁ maxima . " ) NEW_LINE DEDENT if ( len ( mn ) > 0 ) : NEW_LINE INDENT print ( " Points ▁ of ▁ Local ▁ minima " \ " ▁ are ▁ : ▁ " , end = ' ' ) NEW_LINE print ( * mn ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " There ▁ are ▁ no ▁ points " \ " ▁ of ▁ Local ▁ minima . " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 9 NEW_LINE arr = [ 10 , 20 , 15 , 14 , 13 , 25 , 5 , 4 , 3 ] NEW_LINE findLocalMaximaMinima ( N , arr ) NEW_LINE DEDENT
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 discarded. ; If any digit divides the number , return false ; If no digit divides the number , return true ; ; Function to find the smallest number not divisible by any of its digits . ; Get the lower range of n digit number ; Get the high range of n digit number ; check all the N - digit numbers ; If the first number to satify the constraints is found print it , set the flag value and break out of the loop . ; If no such digit found , return - 1 as per problem statement ; Driver code
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 DEDENT def check ( n ) : NEW_LINE INDENT temp = n ; NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT last_digit = temp % 10 ; NEW_LINE if ( last_digit == 0 or last_digit == 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( n % last_digit == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT temp = temp // 10 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def solve ( n ) : NEW_LINE INDENT L = power ( 10 , n - 1 ) ; NEW_LINE R = power ( 10 , n ) - 1 ; NEW_LINE flag = 0 ; NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT answer = check ( i ) ; NEW_LINE if ( answer ) : NEW_LINE INDENT print ( i ) NEW_LINE flag += 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 ; NEW_LINE solve ( N ) ; NEW_LINE DEDENT
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 - 1 ] < arr [ i ] < arr [ i + 1 ] or arr [ i - 1 ] > arr [ i ] > arr [ i + 1 ] occur remove arr [ i ] i . e , temp from sequence ; Insert the element in the set removedElements ; Storing the value of arr [ i ] in temp ; Taking the element not in removedElements ; Adding the value of elements of subsequence ; If we have to remove the element then we need to add the cost associated with the element ; Printing the sum of the subsequence with minimum length possible ; Printing the cost incurred in creating subsequence ; Driver code ; Calling the function
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 ) and ( temp > arr [ i + 1 ] ) ) ) : NEW_LINE INDENT removedElements . add ( temp ) NEW_LINE DEDENT DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE if ( temp not in removedElements ) : NEW_LINE INDENT ans = ans + arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT cost += costArray [ i ] NEW_LINE DEDENT DEDENT print ( ans , end = " , ▁ " ) NEW_LINE print ( cost ) NEW_LINE DEDENT N = 4 NEW_LINE arr = [ 1 , 3 , 4 , 2 ] NEW_LINE costArray = [ 0 , 1 , 0 , 0 ] NEW_LINE costOfSubsequence ( N , arr , costArray ) NEW_LINE
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 INDENT ans = ( arr [ query [ i ] [ 0 ] - 1 ] ^ arr [ query [ i ] [ 1 ] ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT DEDENT def main ( ) : NEW_LINE INDENT arr = [ 3 , 2 , 4 , 5 , 1 , 1 , 5 , 3 ] NEW_LINE N = 8 NEW_LINE Q = 2 NEW_LINE query = [ [ 1 , 4 ] , [ 3 , 7 ] ] NEW_LINE find_Xor ( arr , query , N , Q ) NEW_LINE DEDENT main ( ) NEW_LINE
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 ] as START ; Return starting address of array A ; Driver code
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 ] = END NEW_LINE END -= 1 NEW_LINE DEDENT DEDENT arr [ N ] = START NEW_LINE return arr NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT Str = " IDID " NEW_LINE N = len ( Str ) NEW_LINE ptr = DiStirngMatch ( Str ) NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT print ( ptr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT
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 DEDENT DEDENT c = 0 ; NEW_LINE N = 72 ; NEW_LINE for i in range ( 2 , int ( math . sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( IsPrime ( i ) ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT c = c + 1 NEW_LINE if ( IsPrime ( N / i ) and i != ( N / i ) ) : NEW_LINE INDENT c = c + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( pow ( 2 , c ) - 1 ) NEW_LINE
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 for i in range ( n ) : NEW_LINE INDENT b [ i ] += x NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( b [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE arr = [ - 2 , 1 ] NEW_LINE M = len ( arr ) NEW_LINE find_seq ( arr , M , N ) NEW_LINE DEDENT
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 DEDENT else : NEW_LINE INDENT od_count += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT ev_count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT od_count += 1 NEW_LINE DEDENT if ( ( N // i ) % 2 == 0 ) : NEW_LINE INDENT ev_count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT od_count += 1 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( ev_count == od_count ) : 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
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 a prime ; Stores frequency of primes ; If the frequency of primes is a prime ; Increase count of required numbers ; Return the required count ; Driver Code ; Given Range ; Function Call
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 , R + 1 , p ) : NEW_LINE INDENT prime [ i ] = 1 NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for i in range ( 1 , R + 1 ) : NEW_LINE INDENT countPrime [ i ] = countPrime [ i - 1 ] NEW_LINE if ( not prime [ i ] ) : NEW_LINE INDENT countPrime [ i ] += 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , R + 1 ) : NEW_LINE INDENT freqPrime [ i ] = freqPrime [ i - 1 ] NEW_LINE if ( not prime [ countPrime [ i ] ] ) : NEW_LINE INDENT freqPrime [ i ] += 1 NEW_LINE DEDENT DEDENT return ( freqPrime [ R ] - freqPrime [ L - 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 4 NEW_LINE R = 12 NEW_LINE print ( count_crazy_primes ( L , R ) ) NEW_LINE DEDENT
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_LINE DEDENT for j in range ( zero , ( one + zero ) ) : NEW_LINE INDENT num += ( 1 << j ) NEW_LINE DEDENT print ( num , end = " " ) NEW_LINE i += 1 NEW_LINE if ( N > 0 ) : NEW_LINE INDENT print ( " , ▁ " , end = " " ) NEW_LINE DEDENT N -= 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 8 , 15 , 9 , 10 , 14 ] NEW_LINE N = len ( arr ) NEW_LINE maximizedArray ( arr , N ) NEW_LINE DEDENT
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 ; LCM of two numbers is evaluated as [ ( a * b ) / gcd ( a , b ) ] ; Return LCM ; Function to print the ratio of LCM to GCD of the given array ; Driver Code
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 lcm = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT lcm = int ( ( ( ( arr [ i ] * lcm ) ) / ( math . gcd ( arr [ i ] , lcm ) ) ) ) NEW_LINE DEDENT return lcm NEW_LINE DEDENT def findRatio ( arr , n ) : NEW_LINE INDENT gcd = findGCD ( arr , n ) NEW_LINE lcm = findLCM ( arr , n ) NEW_LINE print ( int ( lcm / gcd ) , " : " , "1" ) NEW_LINE DEDENT arr = [ 6 , 12 , 36 ] NEW_LINE N = len ( arr ) NEW_LINE findRatio ( arr , N ) NEW_LINE
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 divisible by K ; Initialize Map data structure ; Iterate for all the elements of the array ; Calculate the value to be added ; Check if the value equals to 0 then simply continue ; Check if the value to be added is present in the map ; Update the answer ; Print the required result We need to add 1 to maxX because we cant ignore the first move where initially X = 0 and we need to increase it by 1 to make some changes in array ; Driver code
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_LINE DEDENT if ( val in eqVal ) : NEW_LINE INDENT numVal = eqVal [ val ] NEW_LINE maxX = max ( maxX , val + ( K * numVal ) ) NEW_LINE eqVal [ val ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT eqVal [ val ] += 1 NEW_LINE maxX = max ( maxX , val ) NEW_LINE DEDENT DEDENT if maxX == 0 : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( maxX + 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT K = 3 NEW_LINE a = [ 1 , 2 , 2 , 18 ] NEW_LINE N = len ( a ) NEW_LINE compute ( a , N , K ) NEW_LINE DEDENT
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 sum accordingly ; Increment the sum accordingly ; Set count of Y [ i ] ; Reset count of X [ i ] ; Print the sum ; Driver Code ; Function call
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 range ( Q ) : NEW_LINE INDENT x = X [ i ] NEW_LINE y = Y [ i ] NEW_LINE if X [ i ] not in count : NEW_LINE INDENT count [ X [ i ] ] = 0 NEW_LINE DEDENT if Y [ i ] not in count : NEW_LINE INDENT count [ Y [ i ] ] = 0 NEW_LINE DEDENT sum -= ( count [ X [ i ] ] * X [ i ] ) NEW_LINE sum += count [ X [ i ] ] * Y [ i ] NEW_LINE count [ Y [ i ] ] += count [ X [ i ] ] NEW_LINE count [ X [ i ] ] = 0 NEW_LINE print ( sum , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 1 , 3 , 2 , ] NEW_LINE X = [ 2 , 3 , 5 ] NEW_LINE Y = [ 3 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE Q = len ( X ) NEW_LINE sumOfTheArrayForQuery ( arr , N , X , Y , Q ) NEW_LINE
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 ; Driver Code
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_LINE print ( maxOR ( arr , n ) ) NEW_LINE DEDENT
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 element of the array ; Count [ A [ i ] ] denotes how many previous elements are there whose factor is the current element . ; Increment in count array for factors of A [ i ] ; Print the generated array ; Driver code
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 INDENT count [ i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ i ] += 1 NEW_LINE count [ val // i ] += 1 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def generateArr ( A , n ) : NEW_LINE INDENT B = [ 0 ] * n NEW_LINE maxi = max ( A ) NEW_LINE count = [ 0 ] * ( maxi + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT B [ i ] = count [ A [ i ] ] NEW_LINE IncrementFactors ( count , A [ i ] ) NEW_LINE DEDENT printArr ( B , n ) NEW_LINE DEDENT arr = [ 8 , 1 , 28 , 4 , 2 , 6 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE generateArr ( arr , n ) 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 of the given array ; Extract the index which has the next greater prime ; Store the difference between the prime and the array element ; Driver code
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 DEDENT p += 1 NEW_LINE DEDENT primes = [ ] NEW_LINE for p in range ( 2 , ( 2 * n ) + 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT primes . append ( p ) NEW_LINE DEDENT DEDENT return primes NEW_LINE DEDENT def minChanges ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE ans = 0 NEW_LINE maxi = max ( arr ) NEW_LINE primes = SieveOfEratosthenes ( maxi ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = - 1 NEW_LINE for j in range ( len ( primes ) ) : NEW_LINE INDENT if ( arr [ i ] == primes [ j ] ) : NEW_LINE INDENT x = j NEW_LINE break NEW_LINE DEDENT elif ( arr [ i ] < primes [ j ] ) : NEW_LINE INDENT x = j NEW_LINE break NEW_LINE DEDENT DEDENT minm = abs ( primes [ x ] - arr [ i ] ) NEW_LINE if ( x > 1 ) : NEW_LINE INDENT minm = min ( minm , abs ( primes [ x - 1 ] - arr [ i ] ) ) NEW_LINE DEDENT ans += minm NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 4 , 25 , 13 , 6 , 20 ] NEW_LINE print ( minChanges ( arr ) ) NEW_LINE
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 call
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 ] ) - calcSum ( a [ i ] , ( L - 1 ) // a [ i ] ) ) NEW_LINE DEDENT else : NEW_LINE INDENT sum += ( calcSum ( a [ i ] , R // a [ i ] ) - calcSum ( a [ i ] , L // a [ i ] ) ) NEW_LINE DEDENT DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 7 , 3 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE L = 7 NEW_LINE R = 20 NEW_LINE print ( findSum ( arr , N , L , R ) ) NEW_LINE DEDENT
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 prime or not ; Initialise Prime array arr [ ] ; Since 0 and 1 are not prime numbers we mark them as '0 ; Using Sieve Of Eratosthenes ; If the number is prime ; Mark all the multiples of i starting from square of i with '0' ie . composite ; '0' represents not prime ; Initialise a sum variable as 0 ; Check if the number is prime ; A temporary variable to store the number ; Loop to calculate the sum of digits ; Check if the sum of prime number is prime ; If prime mark 1 ; If not prime mark 0 ; Computing prefix array ; Function to count the prime numbers in the range [ L , R ] ; Function call to find primes ; Print the result ; Driver Code ; Input range ; Function call
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 : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT for j in range ( i * i , maxN , i ) : NEW_LINE INDENT arr [ j ] = 0 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT sum = 0 NEW_LINE prefix [ 0 ] = 0 NEW_LINE for i in range ( 1 , maxN + 1 ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT temp = i NEW_LINE sum = 0 NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT x = temp % 10 NEW_LINE sum += x NEW_LINE temp = temp // 10 NEW_LINE if ( arr [ sum ] == 1 ) : NEW_LINE INDENT prefix [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT prefix [ i ] = 0 NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( 1 , maxN + 1 ) : NEW_LINE INDENT prefix [ i ] += prefix [ i - 1 ] NEW_LINE DEDENT DEDENT def countNumbersInRange ( l , r ) : NEW_LINE INDENT findPrimes ( ) NEW_LINE result = ( prefix [ r ] - prefix [ l - 1 ] ) NEW_LINE print ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 5 NEW_LINE r = 20 NEW_LINE countNumbersInRange ( l , r ) NEW_LINE DEDENT
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 and set is empty , then answer is false ; Fill the subset table in bottom up manner ; Function to store divisors of N in a vector ; Find all divisors which divides 'num ; If ' i ' is divisor of 'n ; If both divisors are same then store it once else store both divisors ; Returns true if num is Practical ; Vector to store all divisors of N ; To check all numbers from 1 to < N ; Driver code
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 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , Sum + 1 ) : NEW_LINE INDENT if ( j < Set [ i - 1 ] ) : NEW_LINE INDENT subset [ i ] [ j ] = subset [ i - 1 ] [ j ] NEW_LINE DEDENT if ( j >= Set [ i - 1 ] ) : NEW_LINE INDENT subset [ i ] [ j ] = ( subset [ i - 1 ] [ j ] or subset [ i - 1 ] [ j - Set [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT return subset [ n ] [ Sum ] NEW_LINE DEDENT def storeDivisors ( n , div ) : NEW_LINE ' NEW_LINE INDENT for i in range ( 1 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE DEDENT ' NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( i == int ( n / i ) ) : NEW_LINE INDENT div . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT div . append ( i ) NEW_LINE div . append ( int ( n / i ) ) NEW_LINE DEDENT DEDENT DEDENT def isPractical ( N ) : NEW_LINE INDENT div = [ ] NEW_LINE storeDivisors ( N , div ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( not isSubsetSum ( div , len ( div ) , i ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT N = 18 NEW_LINE if ( isPractical ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 . ; Function to check if a number is a super - niven number ; To store digits of N ; Driver code
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 != 0 ) and ( num % sum != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def isSuperNivenNum ( n ) : NEW_LINE INDENT temp = n NEW_LINE digits = [ ] NEW_LINE while ( n > 1 ) : NEW_LINE INDENT digit = int ( n ) % 10 NEW_LINE digits . append ( digit ) NEW_LINE n = n / 10 NEW_LINE DEDENT return isDivBySubsetSums ( digits , temp ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 500 NEW_LINE if isSuperNivenNum ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 prime divisor for n and pi are their respective power in factorization ; Function to check if a number is a highly composite number ; Count number of factors of N ; Loop to count number of factors of every number less than N ; If any number less than N has more factors than N , then return false ; Given Number N ; Function Call
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 = 1 NEW_LINE for P in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( bool ( Hash [ P ] ) ) : NEW_LINE INDENT count = 0 NEW_LINE if ( n % P == 0 ) : NEW_LINE INDENT while ( n % P == 0 ) : NEW_LINE INDENT n = n // P NEW_LINE count += 1 NEW_LINE DEDENT total = total * ( count + 1 ) NEW_LINE DEDENT DEDENT DEDENT return total NEW_LINE DEDENT def isHighlyCompositeNumber ( N ) : NEW_LINE INDENT NdivCount = divCount ( N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT idivCount = divCount ( i ) NEW_LINE if ( idivCount >= NdivCount ) : NEW_LINE INDENT return bool ( False ) NEW_LINE DEDENT DEDENT return bool ( True ) NEW_LINE DEDENT N = 12 NEW_LINE if ( bool ( isHighlyCompositeNumber ( N ) ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 False NEW_LINE DEDENT N = 60 NEW_LINE if isSaintExuperyNum ( N ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 if ( isRepdigit ( num , base ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 that can optimally handle other prime factors . ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Function to check if a number is is an enlightened number ; Number should not be prime ; Converting N to string ; Function call ; Driver code
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 NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return False NEW_LINE DEDENT def concatenatePrimeFactors ( n ) : NEW_LINE INDENT concatenate = " " NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT concatenate += "2" NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = int ( n / 2 ) NEW_LINE DEDENT DEDENT i = 3 NEW_LINE while ( i <= int ( math . sqrt ( n ) ) ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT concatenate += str ( i ) NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n = int ( n / i ) NEW_LINE DEDENT DEDENT i = i + 2 NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT concatenate += str ( n ) NEW_LINE DEDENT return concatenate NEW_LINE DEDENT def isEnlightened ( N ) : NEW_LINE INDENT if ( not isComposite ( N ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT num = str ( N ) NEW_LINE prefixConc = concatenatePrimeFactors ( N ) NEW_LINE return int ( prefixConc ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 250 NEW_LINE if ( isEnlightened ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 = 10 NEW_LINE if ( isIdoneal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 N has all distinct digits ; Create an array of size 10 and initialize all elements as false . This array is used to check if a digit is already seen or not . ; Traverse through all digits of given number ; Find the last digit ; If digit is already seen , return false ; Mark this digit as seen ; Remove the last digit from number ; Function to check Lynch - Bell numbers ; Driver Code ; Given number N ; Function call
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 ) == False ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT temp = temp / 10 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def isAllDigitsDistinct ( n ) : NEW_LINE INDENT arr = [ 0 ] * 10 NEW_LINE while ( n >= 1 ) : NEW_LINE INDENT digit = int ( n % 10 ) NEW_LINE if ( arr [ digit ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT arr [ digit ] = 1 NEW_LINE n = int ( n / 10 ) NEW_LINE DEDENT return 1 NEW_LINE DEDENT def isLynchBell ( n ) : NEW_LINE INDENT return ( isAllDigitsDivide ( n ) and isAllDigitsDistinct ( n ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE if isLynchBell ( N ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 ; taking inputs ; function to check
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 DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 31 ; NEW_LINE base = 2 ; NEW_LINE if ( isRepunitNum ( n , base ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
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 ) + lastDigit ( n ) NEW_LINE return ( n % concatenation ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 108 NEW_LINE if ( isGapful ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 , we reduce MAX to half ; Main logic of Sundaram . Mark all numbers which do not generate prime number by doing 2 * i + 1 ; Since 2 is a prime number ; Prother primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Function to check if a number is a Economical number ; Count digits in original number ; Count all digits in prime factors of n pDigit is going to hold this value . ; Count powers of p in n ; If primes [ i ] is a prime factor , ; Count the power of prime factors ; Add its digits to pDigit . ; Add digits of power of prime factors to pDigit . ; If n != 1 then one prime factor still to be summed up ; If digits in prime factors is less than digits in original number then return true . Else return false . ; Finding all prime numbers before limit . These numbers are used to find prime factors .
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 [ j ] = True NEW_LINE j = j + 2 * i + 1 NEW_LINE DEDENT DEDENT primes . append ( 2 ) NEW_LINE for i in range ( 1 , MAX // 2 + 1 ) : NEW_LINE INDENT if ( marked [ i ] == False ) : NEW_LINE INDENT primes . append ( 2 * i + 1 ) NEW_LINE DEDENT DEDENT DEDENT def isEconomical ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT original_no = n NEW_LINE sumDigits = 0 NEW_LINE while ( original_no > 0 ) : NEW_LINE INDENT sumDigits += 1 NEW_LINE original_no = original_no // 10 NEW_LINE DEDENT pDigit = 0 NEW_LINE count_exp = 0 NEW_LINE i = 0 NEW_LINE p = 0 NEW_LINE while ( primes [ i ] <= n // 2 ) : NEW_LINE INDENT while ( n % primes [ i ] == 0 ) : NEW_LINE INDENT p = primes [ i ] NEW_LINE n = n // p NEW_LINE count_exp += 1 NEW_LINE DEDENT i += 1 NEW_LINE while ( p > 0 ) : NEW_LINE INDENT pDigit += 1 NEW_LINE p = p // 10 NEW_LINE DEDENT while ( count_exp > 1 ) : NEW_LINE INDENT pDigit += 1 NEW_LINE count_exp = count_exp // 10 NEW_LINE DEDENT DEDENT if ( n != 1 ) : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT pDigit += 1 NEW_LINE n = n // 10 NEW_LINE DEDENT DEDENT if ( pDigit < sumDigits ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT sieveSundaram ( ) NEW_LINE for i in range ( 1 , 200 ) : NEW_LINE INDENT if ( isEconomical ( i ) ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT
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 fully and add remaining to an extra shelf ; Find number of shelves needed for items of type - B ; Fill B / L shelves fully by the items of type - B ; Fill B / L shelves fully and add remaining to an an extra shelf ; Total shelves needed ; If required shelves exceed N ; Driver Code
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 // L + 1 NEW_LINE DEDENT total = needa + needb NEW_LINE if ( total > N ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A , B , N = 3 , 3 , 3 NEW_LINE K , M = 4 , 2 NEW_LINE if ( isPossible ( A , B , N , K , M ) ) : NEW_LINE INDENT print ( ' YES ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' NO ' ) NEW_LINE DEDENT DEDENT
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 for N ; Prefix array which contains the count of factors from 1 to N ; Function to count total factors from 1 to N ; Store total factors of i ; Stores total factors from 1 to i ; Function to search lowest X such that the given condition is satisfied ; Find mid ; Search in the right half ; Search in the left half ; Return the position after Binary Search ; Function to find the required sum ; Precompute smallest prime factor of each value ; Calculate count of total factors from 1 to N ; Binary search to find minimum N ; Driver code ; Given Sum ; Function Call
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_LINE INDENT if ( spf [ i ] == i ) NEW_LINE INDENT j = i * i NEW_LINE while ( j <= MAX ) : NEW_LINE INDENT if ( spf [ j ] == j ) : NEW_LINE INDENT spf [ j ] = i ; NEW_LINE DEDENT j += i NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT tfactor = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE pre = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE def CountTotalfactors ( ) : NEW_LINE INDENT tfactor [ 1 ] = pre [ 1 ] = 1 ; NEW_LINE for i in range ( 2 , MAX + 1 ) : NEW_LINE INDENT mspf = spf [ i ] ; NEW_LINE prim = mspf ; NEW_LINE temp = i ; NEW_LINE cnt = 0 ; NEW_LINE while ( temp % mspf == 0 ) : NEW_LINE INDENT temp //= mspf ; NEW_LINE cnt += 1 ; NEW_LINE prim = prim * mspf ; NEW_LINE DEDENT tfactor [ i ] = ( cnt + 1 ) * NEW_LINE INDENT tfactor [ temp ] ; NEW_LINE DEDENT pre [ i ] = pre [ i - 1 ] + NEW_LINE INDENT tfactor [ i ] ; NEW_LINE DEDENT DEDENT DEDENT def BinarySearch ( X ) : NEW_LINE INDENT start = 1 ; NEW_LINE end = MAX - 1 ; NEW_LINE while ( start < end ) : NEW_LINE INDENT mid = ( start + end ) // 2 ; NEW_LINE if ( pre [ mid ] == X ) : NEW_LINE INDENT return mid ; NEW_LINE DEDENT elif ( pre [ mid ] < X ) : NEW_LINE INDENT start = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT end = mid ; NEW_LINE DEDENT DEDENT return start ; NEW_LINE DEDENT def findSumOfCount ( X ) : NEW_LINE INDENT calculate_SPF ( ) ; NEW_LINE CountTotalfactors ( ) ; NEW_LINE print ( BinarySearch ( X ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 10 ; NEW_LINE findSumOfCount ( X ) ; NEW_LINE DEDENT
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 prime ; If index is prime ; Driver code ; Check for both conditions
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 , sum + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def getSum ( a ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT for j in range ( 5 ) : NEW_LINE INDENT s += a [ i ] [ j ] NEW_LINE DEDENT DEDENT return s NEW_LINE DEDENT def checkIndex ( n , m , a ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( prime [ i + j ] and not prime [ a [ i ] [ j ] ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE m = 5 NEW_LINE a = [ [ 1 , 2 , 3 , 2 , 2 ] , [ 2 , 2 , 7 , 7 , 7 ] , [ 7 , 7 , 21 , 7 , 10 ] , [ 2 , 2 , 3 , 6 , 7 ] ] NEW_LINE sum = getSum ( a ) NEW_LINE buildSieve ( sum ) NEW_LINE if ( prime [ sum ] and checkIndex ( n , m , a ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
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 > 31 , move to April April = 4 th Month ; Otherwise , stay on March March = 3 rd Month ; Driver Code
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 = ( 2 * B + 4 * C + 6 * D + N ) % 7 NEW_LINE days = ( 22 + D + E ) NEW_LINE if ( ( D == 29 ) and ( E == 6 ) ) : NEW_LINE INDENT print ( Y , " - 04-19" ) NEW_LINE return NEW_LINE DEDENT elif ( ( D == 28 ) and ( E == 6 ) ) : NEW_LINE INDENT print ( Y , " - 04-18" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT if ( days > 31 ) : NEW_LINE INDENT print ( Y , " - 04 - " , ( days - 31 ) ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT print ( Y , " - 03 - " , days ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT Y = 2020 NEW_LINE gaussEaster ( Y ) NEW_LINE
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 count if different ; Generate all N digit primes ; For every prime number i check if an edge can be made . ; For every prime number i check if an edge can be made from i to j . ; If edge is possible then insert in the adjacency list ; Function to count distance ; If unvisited push onto queue and mark visited as 1 and add the distance of curr + 1. ; Driver code ; Call bfs traversal with root as node A ; Indicates not possible
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 return False NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def valid ( a , b ) : NEW_LINE INDENT c = 0 NEW_LINE while ( a ) : NEW_LINE INDENT if ( ( a % 10 ) != ( b % 10 ) ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT a = int ( a / 10 ) NEW_LINE b = int ( b / 10 ) NEW_LINE DEDENT if ( c == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def makePrimes ( N ) : NEW_LINE INDENT global primes NEW_LINE global lis NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE L = pow ( 10 , N - 1 ) NEW_LINE R = pow ( 10 , N ) - 1 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( isPrime ( i ) ) : NEW_LINE INDENT primes . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( len ( primes ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( primes ) ) : NEW_LINE INDENT a = primes [ i ] NEW_LINE b = primes [ j ] NEW_LINE if ( valid ( a , b ) ) : NEW_LINE INDENT lis [ a ] . append ( b ) NEW_LINE lis [ b ] . append ( a ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def bfs ( src ) : NEW_LINE INDENT global vis NEW_LINE global dis NEW_LINE q = [ ] NEW_LINE q . append ( src ) NEW_LINE vis [ src ] = 1 NEW_LINE dis [ src ] = 0 NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT curr = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE for x in lis [ curr ] : NEW_LINE INDENT if ( vis [ x ] == 0 ) : NEW_LINE INDENT vis [ x ] = 1 NEW_LINE q . append ( x ) NEW_LINE dis [ x ] = dis [ curr ] + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT N = 4 NEW_LINE makePrimes ( N ) NEW_LINE A = 1033 NEW_LINE B = 8179 NEW_LINE bfs ( A ) NEW_LINE if ( dis [ B ] == - 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( dis [ B ] ) NEW_LINE DEDENT
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 DEDENT D = 5 NEW_LINE N = 85932 NEW_LINE print ( placeValue ( N , D ) ) 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_LINE divisors . append ( int ( n / i ) ) NEW_LINE DEDENT DEDENT DEDENT return sorted ( divisors ) NEW_LINE DEDENT def isSuperdNum ( n ) : NEW_LINE INDENT d = findDivisors ( n ) NEW_LINE for i in d : NEW_LINE INDENT x = ( 2 ** i - 2 ) / i NEW_LINE if int ( x ) != x : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 341 NEW_LINE if isSuperdNum ( n ) == True : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT n = 20 ; NEW_LINE if ( isSelfNum ( n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT
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 else : NEW_LINE INDENT C [ i ] [ j ] = ( C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return C [ n ] [ k ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE k = n NEW_LINE n = 2 * n NEW_LINE print ( binomialCoeff ( n , k ) ) NEW_LINE DEDENT
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 // i ) ; NEW_LINE DEDENT DEDENT DEDENT return sum1 ; NEW_LINE DEDENT def MultiplyPerfectNumber ( n ) : NEW_LINE INDENT if ( getSum ( n ) % n == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT n = 28 ; NEW_LINE if ( MultiplyPerfectNumber ( n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT
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 - most one such prime factor ) ; Function to check if the number is a perfect totient number ; Store original value of n ; Loop to calculate sum of iterated totients ; Condition for Perfect Totient Number ; Driver Code
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 INDENT result -= result // n NEW_LINE DEDENT return result NEW_LINE DEDENT def isPerfectTotientNum ( n ) : NEW_LINE INDENT temp = n NEW_LINE sum = 0 NEW_LINE while ( n > 1 ) : NEW_LINE INDENT sum = sum + phi ( n ) NEW_LINE n = phi ( n ) NEW_LINE DEDENT if ( sum == temp ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 9 NEW_LINE if ( isPerfectTotientNum ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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_LINE DEDENT return False NEW_LINE DEDENT def isCunningham ( n ) : NEW_LINE INDENT return isPower ( n - 1 ) or isPower ( n + 1 ) NEW_LINE DEDENT n = 126 NEW_LINE if ( isCunningham ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 ; Function call
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 ( nCr ( m + n , m ) - nCr ( x + y , x ) * nCr ( m + n - x - y , m - x ) ) NEW_LINE DEDENT m = 5 NEW_LINE n = 4 NEW_LINE x = 3 NEW_LINE y = 2 NEW_LINE print ( countWays ( m , n , x , y ) ) NEW_LINE
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 > K is present previously and current digit is less than K ; If current digit is greater than K ; If an extra digit needs to be added ; Print the number ; Driver Code
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 DEDENT def getNumber ( n , k ) : NEW_LINE INDENT count = CountGreater ( n , k ) NEW_LINE if ( count == 0 ) : NEW_LINE INDENT print ( n ) NEW_LINE return NEW_LINE DEDENT ans = [ ] NEW_LINE changed = False NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit = n % 10 NEW_LINE if ( changed == True ) : NEW_LINE INDENT ans . insert ( 0 , digit ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( count == 0 and digit < k ) : NEW_LINE INDENT ans . insert ( 0 , digit + 1 ) NEW_LINE changed = True NEW_LINE DEDENT else : NEW_LINE INDENT ans . insert ( 0 , 1 ) NEW_LINE if ( digit > k ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT DEDENT DEDENT n = n // 10 NEW_LINE DEDENT if ( changed == False ) : NEW_LINE INDENT ans . insert ( 0 , 1 ) NEW_LINE DEDENT PrintList ( ans ) NEW_LINE return NEW_LINE DEDENT N = 51234 NEW_LINE K = 4 NEW_LINE getNumber ( N , K ) NEW_LINE
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 , matches , notout ) ; NEW_LINE if ( avg == - 1 ) : NEW_LINE INDENT print ( " NA " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( avg ) ; NEW_LINE DEDENT
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 and return the Sum upto Nth term ; Recursive Function ; Driver code
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 seriesSum ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT prevSum = 0 ; NEW_LINE multi = 1 ; NEW_LINE add = 1 ; NEW_LINE return seriesSumUtil ( 2 , n , prevSum , multi , add ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE print ( seriesSum ( N ) ) ; NEW_LINE DEDENT
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 odd elements whether sufficient even numbers are present or not ; Count of even numbers required ; If required even numbers are present in the array ; Driver Program
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 INDENT return True NEW_LINE DEDENT flag = False NEW_LINE for i in range ( 1 , K , 2 ) : NEW_LINE INDENT needed = K - i NEW_LINE if ( needed <= len ( Even ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return flag NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT K = 5 NEW_LINE A = [ 12 , 1 , 7 , 7 , 26 , 18 ] NEW_LINE N = 3 NEW_LINE if ( oddSum ( A , N , K ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
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 element + 1 ; Marking the multiples as false ; To store the final count ; Traverse boolean array ; Check if i is not divisible by any other array elements and appears in the array only once ; Return the final Count ; Driver Code ; Given array ; Function Call
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 [ i ] ] == False ) : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( 2 * a [ i ] , len + 1 , a [ i ] ) : NEW_LINE INDENT v [ j ] = False NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for i in range ( 1 , len + 1 ) : NEW_LINE INDENT if ( v [ i ] == True and ( i in hmap ) and hmap [ i ] == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 86 , 45 , 18 , 4 , 8 , 28 , 19 , 33 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countEle ( arr , n ) ) NEW_LINE DEDENT
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 smallestNumber ( N ) NEW_LINE DEDENT
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 ; Initialise maxValue ; Find number having maximum product of prime factor <= N ; Find the maximum value ; Given number ; Function call
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 DEDENT maxValue = 1 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( arr [ i ] > maxValue ) : NEW_LINE INDENT maxValue = i NEW_LINE DEDENT DEDENT return maxValue NEW_LINE DEDENT N = 20 ; NEW_LINE print ( maxPrimefactorNum ( N ) ) NEW_LINE
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 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 ; Given Number N ; Function Call
def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def getSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT sum = sum + n % 10 NEW_LINE n = n / 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def isAdditivePrime ( n ) : NEW_LINE INDENT if ( not isPrime ( n ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT return isPrime ( getSum ( n ) ) NEW_LINE DEDENT N = 23 NEW_LINE if ( isAdditivePrime ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT N = 135 ; NEW_LINE if ( isStraighLineNum ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT
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 DEDENT def isOddEvenForm ( 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 != 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( i % 2 == 1 and int ( s [ i ] ) % 2 != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isAlternating ( n ) : NEW_LINE INDENT s = str ( n ) NEW_LINE return ( isEvenOddForm ( s ) or isOddEvenForm ( s ) ) NEW_LINE DEDENT N = 129 NEW_LINE if ( isAlternating ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 frequency of the current digit ; Remove the last digit ; Function that returns true if a and b are anagrams of each other ; To store the frequencies of the digits in a and b ; Update the frequency of the digits in a ; Update the frequency of the digits in b ; Match the frequencies of the common digits ; If frequency differs for any digit then the numbers are not anagrams of each other ; Returns true if n1 and n2 are Ormiston primes ; Driver code
def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return True NEW_LINE DEDENT TEN = 10 NEW_LINE def updateFreq ( n , freq ) : NEW_LINE INDENT while ( n ) : NEW_LINE INDENT digit = n % TEN NEW_LINE freq [ digit ] += 1 NEW_LINE n = n // TEN NEW_LINE DEDENT DEDENT def areAnagrams ( a , b ) : NEW_LINE INDENT freqA = [ 0 ] * TEN NEW_LINE freqB = [ 0 ] * TEN NEW_LINE updateFreq ( a , freqA ) NEW_LINE updateFreq ( b , freqB ) NEW_LINE for i in range ( TEN ) : NEW_LINE INDENT if ( freqA [ i ] != freqB [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def OrmistonPrime ( n1 , n2 ) : NEW_LINE INDENT return ( isPrime ( n1 ) and isPrime ( n2 ) and areAnagrams ( n1 , n2 ) ) NEW_LINE DEDENT n1 , n2 = 1913 , 1931 NEW_LINE if ( OrmistonPrime ( n1 , n2 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
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 DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 1122 ; NEW_LINE if iszygodromeNum ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 NEW_LINE DEDENT N = 19 NEW_LINE if ( isLoeschian ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 ) ; NEW_LINE DEDENT
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 valid pairs
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 _ _ " : NEW_LINE INDENT C = 13 ; NEW_LINE ans = Pairs ( C ) ; NEW_LINE if ( len ( ans ) == 0 ) : NEW_LINE INDENT print ( " No ▁ valid ▁ pair ▁ exist " ) NEW_LINE exit ( ) NEW_LINE DEDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT print ( " ( " + str ( ans [ i ] [ 0 ] ) + " , ▁ " + str ( ans [ i ] [ 1 ] ) + " ) " ) NEW_LINE DEDENT DEDENT
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 . ; Function to check if any such number exists ; Driver Code
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 while ( N % i == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE N = N // i NEW_LINE DEDENT cnt = cnt + count NEW_LINE DEDENT if ( N > 2 ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE DEDENT return cnt NEW_LINE DEDENT def ifNumberExists ( X , Y ) : NEW_LINE INDENT C = X - Y - 1 NEW_LINE dsum = factorize ( X ) NEW_LINE if ( dsum >= C ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 6 NEW_LINE Y = 4 NEW_LINE ifNumberExists ( X , Y ) NEW_LINE DEDENT
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 multiples of i greater than or equal to the square of it numbers which are multiple of i and are less than i ^ 2 are already been marked . ; Function to find nearest prime number for all elements ; Compute and store all prime numbers up to maxm ; Store the indices of all primes ; If no primes are present in the array ; Store the current prime ; If the no further primes exist in the array ; For all indices less than that of the current prime ; If the current prime is nearer ; If the next prime is nearer ; Make the next prime as the current ; Driver code
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 ( i * i , maxm + 1 , i ) : NEW_LINE INDENT prime [ j ] = True NEW_LINE DEDENT DEDENT DEDENT DEDENT def print_nearest_prime ( arr , N ) : NEW_LINE INDENT maxm = max ( arr ) NEW_LINE SieveOfEratosthenes ( maxm ) NEW_LINE primes = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( not prime [ arr [ i ] ] ) : NEW_LINE INDENT primes . append ( i ) NEW_LINE DEDENT DEDENT if len ( primes ) == 0 : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( - 1 , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT curr = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( curr == len ( primes ) - 1 or i <= primes [ curr ] ) : NEW_LINE INDENT print ( arr [ primes [ curr ] ] , end = " ▁ " ) NEW_LINE continue NEW_LINE DEDENT if ( abs ( primes [ curr ] - i ) < abs ( primes [ curr + 1 ] - i ) ) : NEW_LINE INDENT print ( arr [ primes [ curr ] ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT curr += 1 NEW_LINE print ( arr [ primes [ curr ] ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE arr = [ 8 , 7 , 12 , 15 , 3 , 11 ] NEW_LINE print_nearest_prime ( arr , N ) NEW_LINE DEDENT
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 Call
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_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 777 NEW_LINE findPosition ( N ) NEW_LINE DEDENT