text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Program to compute division upto n decimal places | Python3 program to compute division upto n decimal places . ; Base cases ; Since n <= 0 , don 't compute after the decimal ; Handling negative numbers ; Integral division ; Now one by print digits after dot using school division method . ; Driver Code | def precisionCompute ( x , y , n ) : NEW_LINE INDENT if y == 0 : NEW_LINE INDENT print ( " Infinite " ) ; NEW_LINE return ; NEW_LINE DEDENT if x == 0 : NEW_LINE INDENT print ( 0 ) ; NEW_LINE return ; NEW_LINE DEDENT if n <= 0 : NEW_LINE INDENT print ( x / y ) ; NEW_LINE return ; NEW_LINE DEDENT if ( ( ( x > 0 ) and ( y < 0 ) ) or ( ( x < 0 ) and ( y > 0 ) ) ) : NEW_LINE INDENT print ( " - " , end = " " ) ; NEW_LINE if x < 0 : NEW_LINE INDENT x = - x ; NEW_LINE DEDENT if y < 0 : NEW_LINE INDENT y = - y ; NEW_LINE DEDENT DEDENT d = x / y ; NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT print ( d ) ; NEW_LINE x = x - ( y * d ) ; NEW_LINE if x == 0 : NEW_LINE INDENT break ; NEW_LINE DEDENT x = x * 10 ; NEW_LINE d = x / y ; NEW_LINE if ( i == 0 ) : NEW_LINE INDENT print ( " . " , end = " " ) ; NEW_LINE DEDENT DEDENT DEDENT x = 22 ; NEW_LINE y = 7 ; NEW_LINE n = 15 ; NEW_LINE precisionCompute ( x , y , n ) ; NEW_LINE |
Program to determine the quadrant of the cartesian plane | Function to check quadrant ; Driver code ; Function Calling | def quadrant ( x , y ) : NEW_LINE INDENT if ( x > 0 and y > 0 ) : NEW_LINE INDENT print ( " lies β in β First β quadrant " ) NEW_LINE DEDENT elif ( x < 0 and y > 0 ) : NEW_LINE INDENT print ( " lies β in β Second β quadrant " ) NEW_LINE DEDENT elif ( x < 0 and y < 0 ) : NEW_LINE INDENT print ( " lies β in β Third β quadrant " ) NEW_LINE DEDENT elif ( x > 0 and y < 0 ) : NEW_LINE INDENT print ( " lies β in β Fourth β quadrant " ) NEW_LINE DEDENT elif ( x == 0 and y > 0 ) : NEW_LINE INDENT print ( " lies β at β positive β y β axis " ) NEW_LINE DEDENT elif ( x == 0 and y < 0 ) : NEW_LINE INDENT print ( " lies β at β negative β y β axis " ) NEW_LINE DEDENT elif ( y == 0 and x < 0 ) : NEW_LINE INDENT print ( " lies β at β negative β x β axis " ) NEW_LINE DEDENT elif ( y == 0 and x > 0 ) : NEW_LINE INDENT print ( " lies β at β positive β x β axis " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " lies β at β origin " ) NEW_LINE DEDENT DEDENT x = 1 NEW_LINE y = 1 NEW_LINE quadrant ( x , y ) NEW_LINE |
Check if a number is Full Prime | function to check digits ; check all digits are prime or not ; check if digits are prime or not ; To check if n is prime or not ; check for all factors ; To check if n is Full Prime ; The order is important here for efficiency . ; Driver code | def checkDigits ( n ) : NEW_LINE INDENT while ( n ) : NEW_LINE INDENT dig = n % 10 NEW_LINE if ( dig != 2 and dig != 3 and dig != 5 and dig != 7 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT n = n / 10 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def prime ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i = 2 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def isFullPrime ( n ) : NEW_LINE INDENT return ( checkDigits ( n ) and prime ( n ) ) NEW_LINE DEDENT n = 53 NEW_LINE if ( isFullPrime ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Narcissistic number | Python program for checking of Narcissistic number ; Traversing through the string ; Converting character to int ; Converting string to integer ; Comparing number and sum ; Driver Code taking input as string | def getResult ( st ) : NEW_LINE INDENT sum = 0 NEW_LINE length = len ( st ) NEW_LINE for i in st : NEW_LINE INDENT sum = sum + int ( i ) ** length NEW_LINE DEDENT number = int ( st ) NEW_LINE if ( number == sum ) : NEW_LINE INDENT return " true " NEW_LINE DEDENT else : NEW_LINE INDENT return " false " NEW_LINE DEDENT DEDENT st = "153" NEW_LINE print ( getResult ( st ) ) NEW_LINE |
SchrΓ ΒΆ derΓ’ β¬β Hipparchus number | A memoization based optimized Python3 program to find n - th SchrAderaHipparchus number ; Driven Program | def nthSHN ( n , dp ) : NEW_LINE INDENT if ( n == 1 or n == 2 ) : NEW_LINE INDENT dp [ n ] = 1 NEW_LINE return dp [ n ] NEW_LINE DEDENT if ( dp [ n ] != - 1 ) : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT dp [ n ] = ( ( 6 * n - 9 ) * nthSHN ( n - 1 , dp ) - ( n - 3 ) * nthSHN ( n - 2 , dp ) ) / n NEW_LINE return dp [ n ] NEW_LINE DEDENT n = 6 ; NEW_LINE dp = [ - 1 for i in range ( 500 ) ] NEW_LINE print ( nthSHN ( n , dp ) ) NEW_LINE |
Sum of first n even numbers | function to find sum of first n even numbers ; sum of first n even numbers ; next even number ; required sum ; Driver Code | def evensum ( n ) : NEW_LINE INDENT curr = 2 NEW_LINE sum = 0 NEW_LINE i = 1 NEW_LINE while i <= n : NEW_LINE INDENT sum += curr NEW_LINE curr += 2 NEW_LINE i = i + 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 20 NEW_LINE print ( " sum β of β first β " , n , " even β number β is : β " , evensum ( n ) ) NEW_LINE |
Sum of first n even numbers | function to find sum of first n even numbers ; required sum ; Driver Code | def evensum ( n ) : NEW_LINE INDENT return n * ( n + 1 ) NEW_LINE DEDENT n = 20 NEW_LINE print ( " sum β of β first " , n , " even β number β is : β " , evensum ( n ) ) NEW_LINE |
Program to Convert Km / hr to miles / hr and vice versa | Function to convert kmph to mph ; Function to convert mph to kmph ; | def kmphTOmph ( kmph ) : NEW_LINE INDENT mph = 0.6214 * kmph NEW_LINE return mph NEW_LINE DEDENT def mphTOkmph ( mph ) : NEW_LINE INDENT kmph = ( float ) ( mph * 1.60934 ) NEW_LINE return kmph NEW_LINE DEDENT / * Driver code to check the above function * / NEW_LINE kmph = 150 NEW_LINE mph = 100 NEW_LINE print " speed β in β miles β / β hr β is β " , kmphTOmph ( kmph ) NEW_LINE print " speed β in β km β / β hr β is β " , mphTOkmph ( mph ) NEW_LINE |
Number of GP ( Geometric Progression ) subsequences of size 3 | Python3 program to count GP subsequences of size 3. ; Returns count of G . P . subsequences with length 3 and common ratio r ; hashing to maintain left and right array elements to the main count ; stores the answer ; traverse through the elements ; traverse through all elements and find out the number of elements as k1 * k2 ; keep the count of left and right elements left is a [ i ] / r and right a [ i ] * r ; if the current element is divisible by k , count elements in left hash . ; decrease the count in right hash ; number of right elements ; calculate the answer ; left count of a [ i ] ; Returns answer ; Driver Code | from collections import defaultdict NEW_LINE def subsequences ( a , n , r ) : NEW_LINE INDENT left = defaultdict ( lambda : 0 ) NEW_LINE right = defaultdict ( lambda : 0 ) NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT c1 , c2 = 0 , 0 NEW_LINE if a [ i ] % r == 0 : NEW_LINE INDENT c1 = left [ a [ i ] // r ] NEW_LINE DEDENT right [ a [ i ] ] -= 1 NEW_LINE c2 = right [ a [ i ] * r ] NEW_LINE ans += c1 * c2 NEW_LINE left [ a [ i ] ] += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 6 , 2 , 3 , 6 , 9 , 18 , 3 , 9 ] NEW_LINE n = len ( a ) NEW_LINE r = 3 NEW_LINE print ( subsequences ( a , n , r ) ) NEW_LINE DEDENT |
Find element in array that divides all array elements | Returns GCD of two numbers ; Function to return the desired number if exists ; Find GCD of array ; Check if GCD is present in array ; Driver Code | def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def findNumber ( arr , n ) : NEW_LINE INDENT ans = arr [ 0 ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT ans = gcd ( ans , arr [ i ] ) NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] == ans ) : NEW_LINE INDENT return ans NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 2 , 4 ] ; NEW_LINE n = len ( arr ) NEW_LINE print ( findNumber ( arr , n ) ) NEW_LINE |
Special prime numbers | Python3 program to check whether there exist at least k or not in range [ 2. . n ] ; Generating all the prime numbers from 2 to n . ; If a prime number is Special prime number , then we increments the value of k . ; If at least k Special prime numbers are present , then we return 1. else we return 0 from outside of the outer loop . ; Driver Code | primes = [ ] ; NEW_LINE def SieveofEratosthenes ( n ) : NEW_LINE INDENT visited = [ False ] * ( n + 2 ) ; NEW_LINE for i in range ( 2 , n + 2 ) : NEW_LINE INDENT if ( visited [ i ] == False ) : NEW_LINE INDENT for j in range ( i * i , n + 2 , i ) : NEW_LINE INDENT visited [ j ] = True ; NEW_LINE DEDENT primes . append ( i ) ; NEW_LINE DEDENT DEDENT DEDENT def specialPrimeNumbers ( n , k ) : NEW_LINE INDENT SieveofEratosthenes ( n ) ; NEW_LINE count = 0 ; NEW_LINE for i in range ( len ( primes ) ) : NEW_LINE INDENT for j in range ( i - 1 ) : NEW_LINE INDENT if ( primes [ j ] + primes [ j + 1 ] + 1 == primes [ i ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( count == k ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT n = 27 ; NEW_LINE k = 2 ; NEW_LINE if ( specialPrimeNumbers ( n , k ) ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE DEDENT |
Prime factors of a big number | Python3 program to print prime factors and their powers . ; Function to calculate all the prime factors and count of every prime factor ; count the number of times 2 divides ; equivalent to n = n / 2 ; ; if 2 divides it ; check for all the possible numbers that can divide it ; if n at the end is a prime number . ; Driver Code | import math NEW_LINE def factorize ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( ( n % 2 > 0 ) == False ) : NEW_LINE INDENT n >>= 1 ; NEW_LINE count += 1 ; NEW_LINE DEDENT if ( count > 0 ) : NEW_LINE INDENT print ( 2 , count ) ; NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE n = int ( n / i ) ; NEW_LINE DEDENT if ( count > 0 ) : NEW_LINE INDENT print ( i , count ) ; NEW_LINE DEDENT i += 2 ; NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT print ( n , 1 ) ; NEW_LINE DEDENT DEDENT n = 1000000000000000000 ; NEW_LINE factorize ( n ) ; NEW_LINE |
Minimum gcd operations to make all array elements one | __gcd function ; Function to count number of moves . ; Counting Number of ones . ; If there is a one ; Find smallest subarray with GCD equals to one . ; to calculate GCD ; Not Possible ; Final answer ; Driver program | def __gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return __gcd ( b % a , a ) NEW_LINE DEDENT def minimumMoves ( A , N ) : NEW_LINE INDENT one = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] == 1 ) : NEW_LINE INDENT one += 1 NEW_LINE DEDENT DEDENT if ( one != 0 ) : NEW_LINE INDENT return N - one NEW_LINE DEDENT minimum = + 2147483647 NEW_LINE for i in range ( N ) : NEW_LINE INDENT g = A [ i ] NEW_LINE for j in range ( i + 1 , N ) : NEW_LINE INDENT g = __gcd ( A [ j ] , g ) NEW_LINE if ( g == 1 ) : NEW_LINE INDENT minimum = min ( minimum , j - i ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( minimum == + 2147483647 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return N + minimum - 1 ; NEW_LINE DEDENT DEDENT A = [ 2 , 4 , 3 , 9 ] NEW_LINE N = len ( A ) NEW_LINE print ( minimumMoves ( A , N ) ) NEW_LINE |
Given N and Standard Deviation , find N elements | Python program to find n elements ; function to print series of n elements ; if S . D . is 0 then print all elements as 0. ; print n 0 's ; if S . D . is even ; print - SD , + SD , - SD , + SD ; if odd ; if odd convert n to a float integer ; print one element to be 0 ; print ( n - 1 ) elements as xi derived from the formula ; driver code to test the above function | import math NEW_LINE def series ( n , d ) : NEW_LINE INDENT if d == 0 : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( "0" , end = ' β ' ) NEW_LINE DEDENT return 1 NEW_LINE DEDENT if n % 2 == 0 : NEW_LINE INDENT i = 1 NEW_LINE while i <= n : NEW_LINE INDENT print ( " % .5f " % ( ( math . pow ( - 1 , i ) * d ) ) , end = ' β ' ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT m = n NEW_LINE r = ( m / ( m - 1 ) ) NEW_LINE g = ( float ) ( d * float ( math . sqrt ( r ) ) ) NEW_LINE print ( "0 β " , end = ' β ' ) NEW_LINE i = 1 NEW_LINE while i < n : NEW_LINE INDENT print ( " % .5f " % ( math . pow ( - 1 , i ) * g ) , end = ' β ' ) NEW_LINE i = i + 1 NEW_LINE DEDENT DEDENT print ( " " ) NEW_LINE DEDENT n = 3 NEW_LINE d = 3 NEW_LINE series ( n , d ) NEW_LINE |
Total no of 1 's in numbers | Python3 code to count the frequency of 1 in numbers less than or equal to the given number . ; Driver Code | def countDigitOne ( n ) : NEW_LINE INDENT countr = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT str1 = str ( i ) ; NEW_LINE countr += str1 . count ( "1" ) ; NEW_LINE DEDENT return countr ; NEW_LINE DEDENT n = 13 ; NEW_LINE print ( countDigitOne ( n ) ) ; NEW_LINE n = 131 ; NEW_LINE print ( countDigitOne ( n ) ) ; NEW_LINE n = 159 ; NEW_LINE print ( countDigitOne ( n ) ) ; NEW_LINE |
Exponential Squaring ( Fast Modulo Multiplication ) | prime modulo value ; for cases where exponent is not an even value ; Driver Code | N = 1000000007 ; NEW_LINE def exponentiation ( bas , exp ) : NEW_LINE INDENT t = 1 ; NEW_LINE while ( exp > 0 ) : NEW_LINE INDENT if ( exp % 2 != 0 ) : NEW_LINE INDENT t = ( t * bas ) % N ; NEW_LINE DEDENT bas = ( bas * bas ) % N ; NEW_LINE exp = int ( exp / 2 ) ; NEW_LINE DEDENT return t % N ; NEW_LINE DEDENT bas = 5 ; NEW_LINE exp = 100000 ; NEW_LINE modulo = exponentiation ( bas , exp ) ; NEW_LINE print ( modulo ) ; NEW_LINE |
GCD of factorials of two numbers | Python code to find GCD of factorials of two numbers . ; Driver code | import math NEW_LINE def gcdOfFactorial ( m , n ) : NEW_LINE INDENT return math . factorial ( min ( m , n ) ) NEW_LINE DEDENT m = 5 NEW_LINE n = 9 NEW_LINE print ( gcdOfFactorial ( m , n ) ) NEW_LINE |
Recursive sum of digits of a number is prime or not | Function for recursive digit sum ; function to check if prime or not the single digit ; calls function which returns sum till single digit ; checking prime ; driver code | def recDigSum ( n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT if n % 9 == 0 : NEW_LINE INDENT return 9 NEW_LINE DEDENT else : NEW_LINE INDENT return n % 9 NEW_LINE DEDENT DEDENT DEDENT def check ( n ) : NEW_LINE INDENT n = recDigSum ( n ) NEW_LINE if n == 2 or n == 3 or n == 5 or n == 7 : NEW_LINE INDENT print " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT print " No " NEW_LINE DEDENT DEDENT n = 5602 NEW_LINE check ( n ) NEW_LINE |
Find n | Python program to find the value at n - th place in the given sequence ; Definition of findNumber function ; Finding x from equation n = x ( x + 1 ) / 2 + 1 ; Base of current block ; Value of n - th element ; Driver code | import math NEW_LINE def findNumber ( n ) : NEW_LINE INDENT x = int ( math . floor ( ( - 1 + math . sqrt ( 1 + 8 * n - 8 ) ) / 2 ) ) NEW_LINE base = ( x * ( x + 1 ) ) / 2 + 1 NEW_LINE return n - base + 1 NEW_LINE DEDENT n = 55 NEW_LINE print ( findNumber ( n ) ) NEW_LINE |
Program for weighted mean of natural numbers . | Returns weighted mean assuming for numbers 1 , 2 , . . n and weights 1 , 2 , . . n ; Driver program to test the function . | def weightedMean ( n ) : NEW_LINE INDENT return ( 2 * n + 1 ) / 3 NEW_LINE DEDENT n = 10 NEW_LINE print ( int ( weightedMean ( n ) ) ) NEW_LINE |
Divide every element of one array by other array elements | Python3 program to find quotient of arrayelements ; Function to calculate the quotient of every element of the array ; Calculate the product of all elements ; To calculate the quotient of every array element ; Driver code | import math NEW_LINE def calculate ( a , b , n , m ) : NEW_LINE INDENT mul = 1 NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( b [ i ] != 0 ) : NEW_LINE INDENT mul = mul * b [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT x = math . floor ( a [ i ] / mul ) NEW_LINE print ( x , end = " β " ) NEW_LINE DEDENT DEDENT a = [ 5 , 100 , 8 ] NEW_LINE b = [ 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE calculate ( a , b , n , m ) NEW_LINE |
Largest power of k in n ! ( factorial ) where k may not be prime | Python3 program to find the largest power of k that divides n ! ; To find the power of a prime p in factorial N ; calculating floor ( n / r ) and adding to the count ; increasing the power of p from 1 to 2 to 3 and so on ; returns all the prime factors of k ; vector to store all the prime factors along with their number of occurrence in factorization of k ; Returns largest power of k that divides n ! ; calculating minimum power of all the prime factors of k ; Driver code | import sys NEW_LINE def findPowerOfP ( n , p ) : NEW_LINE INDENT count = 0 NEW_LINE r = p NEW_LINE while ( r <= n ) : NEW_LINE INDENT count += ( n // r ) NEW_LINE r = r * p NEW_LINE DEDENT return count NEW_LINE DEDENT def primeFactorsofK ( k ) : NEW_LINE INDENT ans = [ ] NEW_LINE i = 2 NEW_LINE while k != 1 : NEW_LINE INDENT if k % i == 0 : NEW_LINE INDENT count = 0 NEW_LINE while k % i == 0 : NEW_LINE INDENT k = k // i NEW_LINE count += 1 NEW_LINE DEDENT ans . append ( [ i , count ] ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def largestPowerOfK ( n , k ) : NEW_LINE INDENT vec = primeFactorsofK ( k ) NEW_LINE ans = sys . maxsize NEW_LINE for i in range ( len ( vec ) ) : NEW_LINE INDENT ans = min ( ans , findPowerOfP ( n , vec [ i ] [ 0 ] ) // vec [ i ] [ 1 ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT print ( largestPowerOfK ( 7 , 2 ) ) NEW_LINE print ( largestPowerOfK ( 10 , 9 ) ) NEW_LINE |
Minimum number of bombs | function to print where to shoot ; no . of bombs required ; bomb all the even positions ; bomb all the odd positions ; bomb all the even positions again ; Driver Code | def bomb_required ( n ) : NEW_LINE INDENT print ( n + n // 2 ) NEW_LINE for i in range ( 2 , n + 1 , 2 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT for i in range ( 1 , n + 1 , 2 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT for i in range ( 2 , n , 2 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT bomb_required ( 3 ) NEW_LINE |
LCM of digits of a given number | define lcm function ; If at any point LCM become 0. return it ; Driver code | def lcm_fun ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT return lcm_fun ( b , a % b ) ; NEW_LINE DEDENT def digitLCM ( n ) : NEW_LINE INDENT lcm = 1 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT lcm = int ( ( n % 10 * lcm ) / lcm_fun ( n % 10 , lcm ) ) ; NEW_LINE if ( lcm == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT n = int ( n / 10 ) ; NEW_LINE DEDENT return lcm ; NEW_LINE DEDENT n = 397 ; NEW_LINE print ( digitLCM ( n ) ) ; NEW_LINE |
Secretary Problem ( A Optimal Stopping Problem ) | Python3 Program to test 1 / e law for Secretary Problem ; To find closest integer of num . ; Finds best candidate using n / e rule . candidate [ ] represents talents of n candidates . ; Calculating sample size for benchmarking . ; Finding best candidate in sample size ; Finding the first best candidate that is better than benchmark set . ; Driver code ; n = 8 candidates and candidate array contains talents of n candidate where the largest number means highest talented candidate . ; generating random numbers between 1 to 8 for talent of candidate | import random NEW_LINE import math NEW_LINE e = 2.71828 ; NEW_LINE def roundNo ( num ) : NEW_LINE INDENT if ( num < 0 ) : NEW_LINE INDENT return ( num - 0.5 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( num + 0.5 ) ; NEW_LINE DEDENT DEDENT def printBestCandidate ( candidate , n ) : NEW_LINE INDENT sample_size = roundNo ( n / e ) ; NEW_LINE print ( " Sample size is " , math . floor ( sample_size ) ) ; NEW_LINE best = 0 ; NEW_LINE for i in range ( 1 , int ( sample_size ) ) : NEW_LINE INDENT if ( candidate [ i ] > candidate [ best ] ) : NEW_LINE INDENT best = i ; NEW_LINE DEDENT DEDENT for i in range ( int ( sample_size ) , n ) : NEW_LINE INDENT if ( candidate [ i ] >= candidate [ best ] ) : NEW_LINE INDENT best = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( best >= int ( sample_size ) ) : NEW_LINE INDENT print ( " Best candidate found is " , math . floor ( best + 1 ) , " with β talent " , math . floor ( candidate [ best ] ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Couldn ' t β find β a β best β candidate " ) ; NEW_LINE DEDENT DEDENT n = 8 ; NEW_LINE candidate = [ 0 ] * ( n ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT candidate [ i ] = 1 + random . randint ( 1 , 8 ) ; NEW_LINE DEDENT print ( " Candidate β : β " , end = " " ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( ( i + 1 ) , end = " β " ) ; NEW_LINE DEDENT print ( " Talents : " , β end β = β " " ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( candidate [ i ] , end = " β " ) ; NEW_LINE DEDENT printBestCandidate ( candidate , n ) ; NEW_LINE |
Happy Numbers | Returns sum of squares of digits of a number n . For example for n = 12 it returns 1 + 4 = 5 ; Returns true if n is Happy number else returns false . ; Keep replacing n with sum of squares of digits until we either reach 1 or we end up in a cycle ; Number is Happy if we reach 1 ; Replace n with sum of squares of digits ; Number is not Happy if we reach 4 ; Driver code | def sumDigitSquare ( n ) : NEW_LINE INDENT sq = 0 NEW_LINE while ( n ) : NEW_LINE INDENT digit = n % 10 NEW_LINE sq = sq + digit * digit NEW_LINE n = n // 10 NEW_LINE DEDENT return sq NEW_LINE DEDENT def isHappy ( n ) : NEW_LINE INDENT while ( 1 ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT n = sumDigitSquare ( n ) NEW_LINE if ( n == 4 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT n = 23 NEW_LINE if ( isHappy ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Sum of all subsets of a set formed by first n natural numbers | Python program to find sum of all subsets of a set . ; sum of subsets is ( n * ( n + 1 ) / 2 ) * pow ( 2 , n - 1 ) ; Driver code | def findSumSubsets ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) / 2 ) * ( 1 << ( n - 1 ) ) NEW_LINE DEDENT n = 3 NEW_LINE print ( findSumSubsets ( n ) ) NEW_LINE |
Minimum element whose n | Python3 program to find minimum element whose n - th power is greater than product of an array of size n ; function to find the minimum element ; loop to traverse and store the sum of log ; calculates the elements according to formula . ; returns the minimal element ; initialised array ; computes the size of array ; prints out the minimal element | import math as m NEW_LINE def findMin ( a , n ) : NEW_LINE INDENT _sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE x = m . exp ( _sum / n ) NEW_LINE return int ( x + 1 ) NEW_LINE DEDENT a = [ 3 , 2 , 1 , 4 ] NEW_LINE n = len ( a ) NEW_LINE print ( findMin ( a , n ) ) NEW_LINE |
Generate all cyclic permutations of a number | Python3 Program to generate all cyclic permutations of number ; Function to count the total number of digits in a number . ; Function to generate all cyclic permutations of a number ; Following three lines generates a circular permutation of a number . ; If all the permutations are checked and we obtain original number exit from loop . ; Driver Code | import math NEW_LINE def countdigits ( N ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( N ) : NEW_LINE INDENT count = count + 1 ; NEW_LINE N = int ( math . floor ( N / 10 ) ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def cyclic ( N ) : NEW_LINE INDENT num = N ; NEW_LINE n = countdigits ( N ) ; NEW_LINE while ( 1 ) : NEW_LINE INDENT print ( int ( num ) ) ; NEW_LINE rem = num % 10 ; NEW_LINE div = math . floor ( num / 10 ) ; NEW_LINE num = ( ( math . pow ( 10 , n - 1 ) ) * rem + div ) ; NEW_LINE if ( num == N ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT N = 5674 ; NEW_LINE cyclic ( N ) ; NEW_LINE |
Check whether a number is circular prime or not | Python Program to check if a number is circular prime or not . ; Function to check if a number is prime or not . ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to check if the number is circular prime or not . ; Count digits . ; Following three lines generate the next circular permutation of a number . We move last digit to first position . ; If all the permutations are checked and we obtain original number exit from loop . ; Driver Program | import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT 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 checkCircular ( N ) : NEW_LINE INDENT count = 0 NEW_LINE temp = N NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE temp = temp / 10 NEW_LINE DEDENT num = N ; NEW_LINE while ( isPrime ( num ) ) : NEW_LINE INDENT rem = num % 10 NEW_LINE div = num / 10 NEW_LINE num = ( int ) ( ( math . pow ( 10 , count - 1 ) ) * rem ) + div NEW_LINE if ( num == N ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT N = 1193 ; NEW_LINE if ( checkCircular ( N ) ) : NEW_LINE INDENT print " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT print " No " NEW_LINE DEDENT |
Find if two people ever meet after same number of jumps | function to find if any one of them can overtake the other ; Since starting points are always different , they will meet if following conditions are met . ( 1 ) Speeds are not same ( 2 ) Difference between speeds divide the total distance between initial points . ; driver program | def sackRace ( p1 , s1 , p2 , s2 ) : NEW_LINE INDENT return ( ( s1 > s2 and ( p2 - p1 ) % ( s1 - s2 ) == 0 ) or ( s2 > s1 and ( p1 - p2 ) % ( s2 - s1 ) == 0 ) ) NEW_LINE DEDENT p1 = 4 NEW_LINE s1 = 4 NEW_LINE p2 = 8 NEW_LINE s2 = 2 NEW_LINE if ( sackRace ( p1 , s1 , p2 , s2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Largest proper fraction with sum of numerator and denominator equal to a given number | Python3 program to find the largest fraction a / b such that a + b is equal to given number and a < b . ; Calculate N / 2 ; ; Check if N is odd or even ; If N is odd answer will be ceil ( n / 2 ) - 1 and floor ( n / 2 ) + 1 ; If N is even check if N / 2 i . e a is even or odd ; If N / 2 is even apply the previous formula ; If N / 2 is odd answer will be ceil ( N / 2 ) - 2 and floor ( N / 2 ) + 2 ; Driver Code | import math NEW_LINE def solve ( n ) : NEW_LINE INDENT a = float ( n / 2 ) ; NEW_LINE if ( n % 2 != 0 ) : NEW_LINE INDENT print ( ( math . ceil ( a ) - 1 ) , ( math . floor ( a ) + 1 ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( a % 2 == 0 ) : NEW_LINE INDENT print ( ( math . ceil ( a ) - 1 ) , ( math . floor ( a ) + 1 ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( ( math . ceil ( a ) - 2 ) , ( math . floor ( a ) + 2 ) ) ; NEW_LINE DEDENT DEDENT DEDENT n = 34 ; NEW_LINE solve ( n ) ; NEW_LINE |
Program to find simple interest | We can change values here for different inputs ; Calculates simple interest ; Print the resultant value of SI | P = 1 NEW_LINE R = 1 NEW_LINE T = 1 NEW_LINE SI = ( P * R * T ) / 100 NEW_LINE print ( " simple β interest β is " , SI ) NEW_LINE |
Number of digits in the product of two numbers | function to count number of digits in the product of two numbers ; absolute value of the product of two numbers ; if product is 0 ; count number of digits in the product 'p ; required count of digits ; Driver program to test above | def countDigits ( a , b ) : NEW_LINE INDENT count = 0 NEW_LINE p = abs ( a * b ) NEW_LINE if ( p == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT while ( p > 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE p = p // 10 NEW_LINE DEDENT return count NEW_LINE DEDENT a = 33 NEW_LINE b = - 24 NEW_LINE print ( " Number β of β digits β = β " , countDigits ( a , b ) ) NEW_LINE |
Find multiple of x closest to or a ^ b ( a raised to power b ) | Python3 Program to find closest multiple of x to a ^ b ; function to find closest multiple of x to a ^ b ; calculate a ^ b / x ; Answer is either ( ans * x ) or ( ans + 1 ) * x ; Printing nearest answer ; Driver Code | import math NEW_LINE def multiple ( a , b , x ) : NEW_LINE INDENT if ( b < 0 ) : NEW_LINE INDENT if ( a == 1 and x == 1 ) : NEW_LINE INDENT print ( "1" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( "0" ) ; NEW_LINE DEDENT DEDENT mul = int ( pow ( a , b ) ) ; NEW_LINE ans = int ( mul / x ) ; NEW_LINE ans1 = x * ans ; NEW_LINE ans2 = x * ( ans + 1 ) ; NEW_LINE if ( ( mul - ans1 ) <= ( ans2 - mul ) ) : NEW_LINE INDENT print ( ans1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans2 ) ; NEW_LINE DEDENT DEDENT a = 349 ; NEW_LINE b = 1 ; NEW_LINE x = 4 ; NEW_LINE multiple ( a , b , x ) ; NEW_LINE |
Maximum sum of difference of adjacent elements | To find max sum of permutation ; Base case ; Otherwise max sum will be ( n * ( n - 1 ) / 2 ) - 1 + n / 2 ; Driver program to test maxSum ( ) | def maxSum ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return int ( ( n * ( n - 1 ) / 2 ) - 1 + n / 2 ) NEW_LINE DEDENT DEDENT n = 3 NEW_LINE print ( maxSum ( n ) ) NEW_LINE |
Compute average of two numbers without overflow | Python 3 code to compute average of two numbers ; Function to compute average of two numbers ; Driver code ; Assigning maximum integer value ; Average of two equal numbers is the same number ; Function to get the average of 2 numbers | import sys NEW_LINE from math import floor NEW_LINE INT_MAX = 2147483647 NEW_LINE def compute_average ( a , b ) : NEW_LINE INDENT return floor ( ( a + b ) / 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = INT_MAX NEW_LINE b = - INT_MAX - 1 NEW_LINE print ( " Actual β average β : β " , INT_MAX ) NEW_LINE print ( " Computed β average β : β " , compute_average ( a , b ) ) NEW_LINE DEDENT |
Add minimum number to an array so that the sum becomes even | Function to find out minimum number ; Count odd number of terms in array ; Driver code | def minNum ( arr , n ) : NEW_LINE INDENT odd = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 ) : NEW_LINE INDENT odd = not odd NEW_LINE DEDENT DEDENT if ( odd ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 2 NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print minNum ( arr , n ) NEW_LINE |
Check if a number is jumbled or not | Function to check if a number is jumbled or not ; Single digit number ; Checking every digit through a loop ; All digits were checked ; Digit at index i ; Digit at index i - 1 ; If difference is greater than 1 ; Number checked ; - 1234 to be checked ; - 1247 to be checked | def checkJumbled ( num ) : NEW_LINE INDENT if ( num / 10 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT while ( num != 0 ) : NEW_LINE INDENT if ( num / 10 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT digit1 = num % 10 NEW_LINE digit2 = ( num / 10 ) % 10 NEW_LINE if ( abs ( digit2 - digit1 ) > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT num = num / 10 NEW_LINE DEDENT return True NEW_LINE DEDENT num = - 1234 NEW_LINE if ( checkJumbled ( abs ( num ) ) ) : NEW_LINE INDENT print " True β " NEW_LINE DEDENT else : NEW_LINE INDENT print " False " NEW_LINE DEDENT num = - 1247 NEW_LINE if ( checkJumbled ( abs ( num ) ) ) : NEW_LINE INDENT print " True β " NEW_LINE DEDENT else : NEW_LINE INDENT print " False " NEW_LINE DEDENT |
Josephus Problem Using Bit Magic | Function to find the position of the Most Significant Bit ; keeps shifting bits to the right until we are left with 0 ; Function to return at which place Josephus should sit to avoid being killed ; Getting the position of the Most Significant Bit ( MSB ) . The leftmost '1' . If the number is '41' then its binary is '101001' . So msbPos ( 41 ) = 6 ; ' j ' stores the number with which to XOR the number ' n ' . Since we need '100000' We will do 1 << 6 - 1 to get '100000 ; Toggling the Most Significant Bit . Changing the leftmost '1' to '0' . 101001 ^ 100000 = 001001 ( 9 ) ; Left - shifting once to add an extra '0' to the right end of the binary number 001001 = 010010 ( 18 ) ; Toggling the '0' at the end to '1' which is essentially the same as putting the MSB at the rightmost place . 010010 | 1 = 010011 ( 19 ) ; Driver Code | def msbPos ( n ) : NEW_LINE INDENT pos = 0 NEW_LINE while n != 0 : NEW_LINE INDENT pos += 1 NEW_LINE n = n >> 1 NEW_LINE DEDENT return pos NEW_LINE DEDENT def josephify ( n ) : NEW_LINE INDENT position = msbPos ( n ) NEW_LINE DEDENT ' NEW_LINE INDENT j = 1 << ( position - 1 ) NEW_LINE n = n ^ j NEW_LINE n = n << 1 NEW_LINE n = n | 1 NEW_LINE return n NEW_LINE DEDENT n = 41 NEW_LINE print ( josephify ( n ) ) NEW_LINE |
Count pairs with Odd XOR | A function will return number of pair whose XOR is odd ; To store count of XOR pair ; If XOR is odd increase count ; Return count ; Driver Code | def countXorPair ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( ( arr [ i ] ^ arr [ j ] ) % 2 == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countXorPair ( arr , n ) ) NEW_LINE DEDENT |
Discrete logarithm ( Find an integer k such that a ^ k is congruent modulo b ) | Python3 program to calculate discrete logarithm ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to calculate k for given a , b , m ; Store all values of a ^ ( n * i ) of LHS ; Calculate ( a ^ j ) * b and check for collision ; If collision occurs i . e . , LHS = RHS ; Check whether ans lies below m or not ; Driver code | import math ; NEW_LINE def powmod ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p ; NEW_LINE DEDENT x = ( x * x ) % p ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def discreteLogarithm ( a , b , m ) : NEW_LINE INDENT n = int ( math . sqrt ( m ) + 1 ) ; NEW_LINE value = [ 0 ] * m ; NEW_LINE for i in range ( n , 0 , - 1 ) : NEW_LINE INDENT value [ powmod ( a , i * n , m ) ] = i ; NEW_LINE DEDENT for j in range ( n ) : NEW_LINE INDENT cur = ( powmod ( a , j , m ) * b ) % m ; NEW_LINE if ( value [ cur ] ) : NEW_LINE INDENT ans = value [ cur ] * n - j ; NEW_LINE if ( ans < m ) : NEW_LINE INDENT return ans ; NEW_LINE DEDENT DEDENT DEDENT return - 1 ; NEW_LINE DEDENT a = 2 ; NEW_LINE b = 3 ; NEW_LINE m = 5 ; NEW_LINE print ( discreteLogarithm ( a , b , m ) ) ; NEW_LINE a = 3 ; NEW_LINE b = 7 ; NEW_LINE m = 11 ; NEW_LINE print ( discreteLogarithm ( a , b , m ) ) ; NEW_LINE |
Discrete logarithm ( Find an integer k such that a ^ k is congruent modulo b ) | Python3 program to calculate discrete logarithm ; Calculate a ^ n ; Store all values of a ^ ( n * i ) of LHS ; Calculate ( a ^ j ) * b and check for collision ; Driver code | import math ; NEW_LINE def discreteLogarithm ( a , b , m ) : NEW_LINE INDENT n = int ( math . sqrt ( m ) + 1 ) ; NEW_LINE an = 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT an = ( an * a ) % m ; NEW_LINE DEDENT value = [ 0 ] * m ; NEW_LINE cur = an ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( value [ cur ] == 0 ) : NEW_LINE INDENT value [ cur ] = i ; NEW_LINE DEDENT cur = ( cur * an ) % m ; NEW_LINE DEDENT cur = b ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( value [ cur ] > 0 ) : NEW_LINE INDENT ans = value [ cur ] * n - i ; NEW_LINE if ( ans < m ) : NEW_LINE INDENT return ans ; NEW_LINE DEDENT DEDENT cur = ( cur * a ) % m ; NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT a = 2 ; NEW_LINE b = 3 ; NEW_LINE m = 5 ; NEW_LINE print ( discreteLogarithm ( a , b , m ) ) ; NEW_LINE a = 3 ; NEW_LINE b = 7 ; NEW_LINE m = 11 ; NEW_LINE print ( discreteLogarithm ( a , b , m ) ) ; NEW_LINE |
Finding n | Python3 program to find n - th number with prime digits 2 , 3 and 7 ; remainder for check element position ; if number is 1 st position in tree ; if number is 2 nd position in tree ; if number is 3 rd position in tree ; if number is 4 th position in tree ; Driver code | def nthprimedigitsnumber ( number ) : NEW_LINE INDENT num = " " ; NEW_LINE while ( number > 0 ) : NEW_LINE INDENT rem = number % 4 ; NEW_LINE if ( rem == 1 ) : NEW_LINE INDENT num += '2' ; NEW_LINE DEDENT if ( rem == 2 ) : NEW_LINE INDENT num += '3' ; NEW_LINE DEDENT if ( rem == 3 ) : NEW_LINE INDENT num += '5' ; NEW_LINE DEDENT if ( rem == 0 ) : NEW_LINE INDENT num += '7' ; NEW_LINE DEDENT if ( number % 4 == 0 ) : NEW_LINE INDENT number = number - 1 NEW_LINE DEDENT number = number // 4 ; NEW_LINE DEDENT return num [ : : - 1 ] ; NEW_LINE DEDENT number = 21 ; NEW_LINE print ( nthprimedigitsnumber ( 10 ) ) ; NEW_LINE print ( nthprimedigitsnumber ( number ) ) ; NEW_LINE |
Count pairs ( a , b ) whose sum of cubes is N ( a ^ 3 + b ^ 3 = N ) | Python 3 program to count pairs whose sum cubes is N ; Function to count the pairs satisfying a ^ 3 + b ^ 3 = N ; Check for each number 1 to cbrt ( N ) ; Store cube of a number ; Subtract the cube from given N ; Check if the difference is also a perfect cube ; If yes , then increment count ; Return count ; Loop to Count no . of pairs satisfying a ^ 3 + b ^ 3 = i for N = 1 to 10 | import math NEW_LINE def countPairs ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , int ( math . pow ( N , 1 / 3 ) + 1 ) ) : NEW_LINE INDENT cb = i * i * i NEW_LINE diff = N - cb NEW_LINE cbrtDiff = int ( math . pow ( diff , 1 / 3 ) ) NEW_LINE if ( cbrtDiff * cbrtDiff * cbrtDiff == diff ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT for i in range ( 1 , 11 ) : NEW_LINE INDENT print ( ' For β n β = β ' , i , ' , β ' , countPairs ( i ) , ' β pair β exists ' ) NEW_LINE DEDENT |
Smallest number S such that N is a factor of S factorial or S ! | Calculate prime factors for a given number ; Container for prime factors ; Iterate from 2 to i ^ 2 finding all factors ; If we still have a remainder it is also a prime factor ; Calculate occurrence of an element in factorial of a number ; Iterate through prime factors ; Check if factorial contains less occurrences of prime factor ; Function to binary search 1 to N ; Prime factors are not in the factorial Increase the lowerbound ; We have reached smallest occurrence ; Smaller factorial satisfying requirements may exist , decrease upperbound ; Calculate prime factors and search ; Driver function | def primeFactors ( num ) : NEW_LINE INDENT ans = dict ( ) NEW_LINE i = 2 NEW_LINE while ( i * i <= num ) : NEW_LINE INDENT while ( num % i == 0 ) : NEW_LINE INDENT num //= i ; NEW_LINE if i not in ans : NEW_LINE ans [ i ] = 0 NEW_LINE ans [ i ] += 1 NEW_LINE DEDENT DEDENT if ( num > 1 ) : NEW_LINE if num not in ans : NEW_LINE INDENT ans [ num ] = 0 NEW_LINE DEDENT ans [ num ] += 1 NEW_LINE return ans ; NEW_LINE DEDENT def legendre ( factor , num ) : NEW_LINE INDENT count = 0 NEW_LINE fac2 = factor ; NEW_LINE while ( num >= factor ) : NEW_LINE INDENT count += num // factor ; NEW_LINE factor *= fac2 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def possible ( factors , num ) : NEW_LINE INDENT for it in factors . keys ( ) : NEW_LINE INDENT if ( legendre ( it , num ) < factors [ it ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def search ( start , end , factors ) : NEW_LINE INDENT mid = ( start + end ) // 2 ; NEW_LINE if ( not possible ( factors , mid ) ) : NEW_LINE INDENT return search ( mid + 1 , end , factors ) ; NEW_LINE DEDENT if ( start == mid ) : NEW_LINE INDENT return mid ; NEW_LINE DEDENT return search ( start , mid , factors ) ; NEW_LINE DEDENT def findFact ( num ) : NEW_LINE INDENT factors = primeFactors ( num ) ; NEW_LINE return search ( 1 , num , factors ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( findFact ( 6 ) ) NEW_LINE print ( findFact ( 997587429953 ) ) NEW_LINE DEDENT |
Finding ' k ' such that its modulus with each array element is same | Prints all k such that arr [ i ] % k is same for all i ; sort the numbers ; max difference will be the difference between first and last element of sorted array ; Case when all the array elements are same ; Find all divisors of d and store in a vector v [ ] ; check for each v [ i ] if its modulus with each array element is same or not ; checking for each array element if its modulus with k is equal to k or not ; if check is true print v [ i ] ; Driver Code | def printEqualModNumbers ( arr , n ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE d = arr [ n - 1 ] - arr [ 0 ] ; NEW_LINE if ( d == 0 ) : NEW_LINE INDENT print ( " Infinite β solution " ) NEW_LINE return NEW_LINE DEDENT v = [ ] ; NEW_LINE i = 1 ; NEW_LINE while ( i * i <= d ) : NEW_LINE INDENT if ( d % i == 0 ) : NEW_LINE INDENT v . append ( i ) ; NEW_LINE if ( i != d / i ) : NEW_LINE INDENT v . append ( d / i ) ; NEW_LINE DEDENT DEDENT i += 1 ; NEW_LINE DEDENT for i in range ( len ( v ) ) : NEW_LINE INDENT temp = arr [ 0 ] % v [ i ] ; NEW_LINE j = 1 ; NEW_LINE while ( j < n ) : NEW_LINE INDENT if ( arr [ j ] % v [ i ] != temp ) : NEW_LINE INDENT break ; NEW_LINE DEDENT j += 1 ; NEW_LINE DEDENT if ( j == n ) : NEW_LINE INDENT print ( v [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT DEDENT arr = [ 38 , 6 , 34 ] ; NEW_LINE printEqualModNumbers ( arr , len ( arr ) ) ; NEW_LINE |
First digit in product of an array of numbers | Python implementation of finding first digit of product of n numbers ; Returns the first digit of product of elements of arr [ ] ; stores the logarithm of product of elements of arr [ ] ; fractional ( s ) = s - floor ( s ) ; ans = 10 ^ fract_s ; Driver function | import math NEW_LINE def FirstDigit ( arr , n ) : NEW_LINE INDENT S = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT S = S + math . log10 ( arr [ i ] * 1.0 ) NEW_LINE DEDENT fract_S = S - math . floor ( S ) NEW_LINE ans = math . pow ( 10 , fract_S ) NEW_LINE return ans NEW_LINE DEDENT arr = [ 5 , 8 , 3 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( ( int ) ( FirstDigit ( arr , n ) ) ) NEW_LINE |
Find count of digits in a number that divide the number | Return the number of digits that divides the number . ; Fetching each digit of the number ; Checking if digit is greater than 0 and can divides n . ; Driven Code | def countDigit ( n ) : NEW_LINE INDENT temp = n NEW_LINE count = 0 NEW_LINE while temp != 0 : NEW_LINE INDENT d = temp % 10 NEW_LINE temp //= 10 NEW_LINE if d > 0 and n % d == 0 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT n = 1012 NEW_LINE print ( countDigit ( n ) ) NEW_LINE |
Minimum positive integer to divide a number such that the result is an odd | Function to find the value ; Return 1 if already odd ; Check how many times it is divided by 2 ; Driver code | def makeOdd ( n ) : NEW_LINE INDENT if ( n % 2 != 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT resul = 1 ; NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = n / 2 ; NEW_LINE resul = resul * 2 ; NEW_LINE DEDENT return resul ; NEW_LINE DEDENT n = 36 ; NEW_LINE print ( makeOdd ( n ) ) ; NEW_LINE |
Multiple of x closest to n | Function to calculate the smallest multiple ; Driver Code | def closestMultiple ( n , x ) : NEW_LINE INDENT if x > n : NEW_LINE INDENT return x ; NEW_LINE DEDENT z = ( int ) ( x / 2 ) ; NEW_LINE n = n + z ; NEW_LINE n = n - ( n % x ) ; NEW_LINE return n ; NEW_LINE DEDENT n = 56287 ; NEW_LINE x = 27 ; NEW_LINE print ( closestMultiple ( n , x ) ) ; NEW_LINE |
Perfect cubes in a range | Python3 code for Efficient method to print cubes between a and b ; An efficient solution to print perfect cubes between a and b ; Find cube root of both a and b ; Print cubes between acrt and bcrt ; Driver code | def cbrt ( n ) : NEW_LINE INDENT return ( int ) ( n ** ( 1. / 3 ) ) NEW_LINE DEDENT def printCubes ( a , b ) : NEW_LINE INDENT acrt = cbrt ( a ) NEW_LINE bcrt = cbrt ( b ) NEW_LINE for i in range ( acrt , bcrt + 1 ) : NEW_LINE INDENT if ( i * i * i >= a and i * i * i <= b ) : NEW_LINE INDENT print ( i * i * i , " β " , end = " " ) NEW_LINE DEDENT DEDENT DEDENT a = 24 NEW_LINE b = 576 NEW_LINE print ( " Perfect β cubes β in β given β range : " ) NEW_LINE printCubes ( a , b ) NEW_LINE |
Number of occurrences of 2 as a digit in numbers from 0 to n | Counts the number of '2' digits in a single number ; Counts the number of '2' digits between 0 and n ; Initialize result ; Count 2 's in every number from 2 to n ; Driver code | def number0f2s ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( n % 10 == 2 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT n = n // 10 NEW_LINE DEDENT return count NEW_LINE DEDENT def numberOf2sinRange ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT count = count + number0f2s ( i ) NEW_LINE DEDENT return count NEW_LINE DEDENT print ( numberOf2sinRange ( 22 ) ) NEW_LINE print ( numberOf2sinRange ( 100 ) ) NEW_LINE |
Minimum toggles to partition a binary array so that it has first 0 s then 1 s | Function to calculate minimum toggling required by using Dynamic programming ; Fill entries in zero [ ] such that zero [ i ] stores count of zeroes to the left of i ( exl ; If zero found update zero [ ] array ; Finding the minimum toggle required from every index ( 0 to n - 1 ) ; Driver Program | def minToggle ( arr , n ) : NEW_LINE INDENT zero = [ 0 for i in range ( n + 1 + 1 ) ] NEW_LINE zero [ 0 ] = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] == 0 ) : NEW_LINE INDENT zero [ i ] = zero [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT zero [ i ] = zero [ i - 1 ] NEW_LINE DEDENT DEDENT ans = n NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = min ( ans , i - zero [ i ] + zero [ n ] - zero [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 0 , 1 , 1 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minToggle ( arr , n ) ) NEW_LINE |
Check if a large number is divisible by 6 or not | Function to find that number is divisible by 6 or not ; Return false if number is not divisible by 2. ; Compute sum of digits ; Check if sum of digits is divisible by 3 ; Driver code | def check ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE if ( ( ( int ) ( st [ n - 1 ] ) % 2 ) != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT digitSum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT digitSum = digitSum + ( int ) ( st [ i ] ) NEW_LINE DEDENT return ( digitSum % 3 == 0 ) NEW_LINE DEDENT st = "1332" NEW_LINE if ( check ( st ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No β " ) NEW_LINE DEDENT |
Find ways an Integer can be expressed as sum of n | Python 3 program to find number of ways to express a number as sum of n - th powers of numbers . ; Wrapper over checkRecursive ( ) ; Driver Code | def checkRecursive ( num , rem_num , next_int , n , ans = 0 ) : NEW_LINE INDENT if ( rem_num == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT r = int ( num ** ( 1 / n ) ) NEW_LINE for i in range ( next_int + 1 , r + 1 ) : NEW_LINE INDENT a = rem_num - int ( i ** n ) NEW_LINE if a >= 0 : NEW_LINE INDENT ans += checkRecursive ( num , rem_num - int ( i ** n ) , i , n , 0 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def check ( x , n ) : NEW_LINE INDENT return checkRecursive ( x , x , 0 , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( check ( 10 , 2 ) ) NEW_LINE DEDENT |
N 'th palindrome of K digits | A naive approach of Python3 program of finding nth palindrome of k digit ; Utility function to reverse the number n ; Boolean Function to check for palindromic number ; Function for finding nth palindrome of k digits ; Get the smallest k digit number ; check the number is palindrom or not ; if n 'th palindrome found break the loop ; Increment number for checking next palindrome ; Driver code | import math ; NEW_LINE def reverseNum ( n ) : NEW_LINE INDENT rev = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT rem = n % 10 ; NEW_LINE rev = ( rev * 10 ) + rem ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE DEDENT return rev ; NEW_LINE DEDENT def isPalindrom ( num ) : NEW_LINE INDENT return num == reverseNum ( num ) ; NEW_LINE DEDENT def nthPalindrome ( n , k ) : NEW_LINE INDENT num = math . pow ( 10 , k - 1 ) ; NEW_LINE while ( True ) : NEW_LINE INDENT if ( isPalindrom ( num ) ) : NEW_LINE INDENT n -= 1 ; NEW_LINE DEDENT if ( not n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT num += 1 ; NEW_LINE DEDENT return int ( num ) ; NEW_LINE DEDENT n = 6 ; NEW_LINE k = 5 ; NEW_LINE print ( n , " th β palindrome β of " , k , " digit β = " , nthPalindrome ( n , k ) ) ; NEW_LINE n = 10 ; NEW_LINE k = 6 ; NEW_LINE print ( n , " th β palindrome β of " , k , " digit β = " , nthPalindrome ( n , k ) ) ; NEW_LINE |
N 'th palindrome of K digits | Python3 program of finding nth palindrome of k digit ; Determine the first half digits ; Print the first half digits of palindrome ; If k is odd , truncate the last digit ; print the last half digits of palindrome ; Driver code | def nthPalindrome ( n , k ) : NEW_LINE INDENT if ( k & 1 ) : NEW_LINE INDENT temp = k // 2 NEW_LINE DEDENT else : NEW_LINE INDENT temp = k // 2 - 1 NEW_LINE DEDENT palindrome = 10 ** temp NEW_LINE palindrome = palindrome + n - 1 NEW_LINE print ( palindrome , end = " " ) NEW_LINE if ( k & 1 ) : NEW_LINE INDENT palindrome = palindrome // 10 NEW_LINE DEDENT while ( palindrome ) : NEW_LINE INDENT print ( palindrome % 10 , end = " " ) NEW_LINE palindrome = palindrome // 10 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE k = 5 NEW_LINE print ( n , " th β palindrome β of " , k , " β digit β = β " , end = " β " ) NEW_LINE nthPalindrome ( n , k ) NEW_LINE print ( ) NEW_LINE n = 10 NEW_LINE k = 6 NEW_LINE print ( n , " th β palindrome β of " , k , " digit β = β " , end = " β " ) NEW_LINE nthPalindrome ( n , k ) NEW_LINE DEDENT |
Maximum value in an array after m range increment operations | Python3 progrma of simple approach to find maximum value after m range increments . ; Function to find the maximum element after m operations ; Start performing m operations ; Store lower and upper index i . e . range ; Add ' k [ i ] ' value at this operation to whole range ; Find maximum value after all operations and return ; Driver code ; Number of values ; Value of k to be added at each operation | import sys NEW_LINE def findMax ( n , a , b , k , m ) : NEW_LINE INDENT arr = [ 0 ] * n NEW_LINE for i in range ( m ) : NEW_LINE INDENT lowerbound = a [ i ] NEW_LINE upperbound = b [ i ] NEW_LINE for j in range ( lowerbound , upperbound + 1 ) : NEW_LINE arr [ j ] += k [ i ] NEW_LINE res = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT res = max ( res , arr [ i ] ) NEW_LINE return res NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE a = [ 0 , 1 , 2 ] NEW_LINE b = [ 1 , 4 , 3 ] NEW_LINE k = [ 100 , 100 , 100 ] NEW_LINE m = len ( a ) NEW_LINE print ( " Maximum β value β after β ' m ' β operations β is β " , findMax ( n , a , b , k , m ) ) NEW_LINE DEDENT |
Summation of GCD of all the pairs up to N | Python approach of finding sum of GCD of all pairs ; phi [ i ] stores euler totient function for i result [ j ] stores result for value j ; Precomputation of phi [ ] numbers . Refer below link for details : https : goo . gl / LUqdtY ; Refer https : goo . gl / LUqdtY ; Precomputes result for all numbers till MAX ; Precompute all phi value ; Iterate throght all the divisors of i . ; Add summation of previous calculated sum ; Function to calculate sum of all the GCD pairs | MAX = 100001 NEW_LINE phi = [ 0 ] * MAX NEW_LINE result = [ 0 ] * MAX NEW_LINE def computeTotient ( ) : NEW_LINE INDENT phi [ 1 ] = 1 NEW_LINE for i in range ( 2 , MAX ) : NEW_LINE INDENT if not phi [ i ] : NEW_LINE INDENT phi [ i ] = i - 1 NEW_LINE for j in range ( i << 1 , MAX , i ) : NEW_LINE INDENT if not phi [ j ] : NEW_LINE INDENT phi [ j ] = j NEW_LINE DEDENT phi [ j ] = ( ( phi [ j ] // i ) * ( i - 1 ) ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def sumOfGcdPairs ( ) : NEW_LINE INDENT computeTotient ( ) NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT for j in range ( 2 , MAX ) : NEW_LINE INDENT if i * j >= MAX : NEW_LINE INDENT break NEW_LINE DEDENT result [ i * j ] += i * phi [ j ] NEW_LINE DEDENT DEDENT for i in range ( 2 , MAX ) : NEW_LINE INDENT result [ i ] += result [ i - 1 ] NEW_LINE DEDENT DEDENT sumOfGcdPairs ( ) NEW_LINE N = 4 NEW_LINE print ( " Summation β of " , N , " = " , result [ N ] ) NEW_LINE N = 12 NEW_LINE print ( " Summation β of " , N , " = " , result [ N ] ) NEW_LINE N = 5000 NEW_LINE print ( " Summation β of " , N , " = " , result [ N ] ) NEW_LINE |
Find coordinates of the triangle given midpoint of each side | Python3 program to find coordinate of the triangle given midpoint of each side ; Return after solving the equations and finding the vertices coordinate . ; Finding sum of all three coordinate . ; Solving the equation . ; Finds vertices of a triangles from given middle vertices . ; Find X coordinates of vertices . ; Find Y coordinates of vertices . ; Output the solution . ; Driver code | N = 3 NEW_LINE def solve ( v ) : NEW_LINE INDENT res = [ ] NEW_LINE all3 = v [ 0 ] + v [ 1 ] + v [ 2 ] NEW_LINE res . append ( all3 - v [ 1 ] * 2 ) NEW_LINE res . append ( all3 - v [ 2 ] * 2 ) NEW_LINE res . append ( all3 - v [ 0 ] * 2 ) NEW_LINE return res NEW_LINE DEDENT def findVertex ( xmid , ymid ) : NEW_LINE INDENT V1 = solve ( xmid ) NEW_LINE V2 = solve ( ymid ) NEW_LINE for i in range ( 0 , 3 ) : NEW_LINE INDENT print ( V1 [ i ] , end = " β " ) NEW_LINE print ( V2 [ i ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT xmid = [ 5 , 4 , 5 ] NEW_LINE ymid = [ 3 , 4 , 5 ] NEW_LINE findVertex ( xmid , ymid ) NEW_LINE DEDENT |
N | Return the n - th number in the sorted list of multiples of two numbers . ; Generating first n multiple of a . ; Sorting the sequence . ; Generating and storing first n multiple of b and storing if not present in the sequence . ; If not present in the sequence ; Storing in the sequence . ; Driver Code | def nthElement ( a , b , n ) : NEW_LINE INDENT seq = [ ] ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT seq . append ( a * i ) ; NEW_LINE DEDENT seq . sort ( ) ; NEW_LINE i = 1 ; NEW_LINE k = n ; NEW_LINE while ( i <= n and k > 0 ) : NEW_LINE INDENT try : NEW_LINE INDENT z = seq . index ( b * i ) ; NEW_LINE DEDENT except ValueError : NEW_LINE INDENT seq . append ( b * i ) ; NEW_LINE seq . sort ( ) ; NEW_LINE k -= 1 ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT return seq [ n - 1 ] ; NEW_LINE DEDENT a = 3 ; NEW_LINE b = 5 ; NEW_LINE n = 5 ; NEW_LINE print ( nthElement ( a , b , n ) ) ; NEW_LINE |
Count pairs of natural numbers with GCD equal to given number | Return the GCD of two numbers . ; Return the count of pairs having GCD equal to g . ; Setting the value of L , R . ; For each possible pair check if GCD is 1. ; Driver code | def gcd ( a , b ) : NEW_LINE INDENT return gcd ( b , a % b ) if b > 0 else a NEW_LINE DEDENT def countGCD ( L , R , g ) : NEW_LINE INDENT L = ( L + g - 1 ) // g NEW_LINE R = R // g NEW_LINE ans = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT for j in range ( L , R + 1 ) : NEW_LINE INDENT if ( gcd ( i , j ) == 1 ) : NEW_LINE INDENT ans = ans + 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT L = 1 NEW_LINE R = 11 NEW_LINE g = 5 NEW_LINE print ( countGCD ( L , R , g ) ) NEW_LINE |
Last non | Initialize values of last non - zero digit of numbers from 0 to 9 ; Check whether tens ( or second last ) digit is odd or even If n = 375 , So n / 10 = 37 and ( n / 10 ) % 10 = 7 Applying formula for even and odd cases . ; driver code | dig = [ 1 , 1 , 2 , 6 , 4 , 2 , 2 , 4 , 2 , 8 ] NEW_LINE def lastNon0Digit ( n ) : NEW_LINE INDENT if ( n < 10 ) : NEW_LINE INDENT return dig [ n ] NEW_LINE DEDENT if ( ( ( n // 10 ) % 10 ) % 2 == 0 ) : NEW_LINE INDENT return ( 6 * lastNon0Digit ( n // 5 ) * dig [ n % 10 ] ) % 10 NEW_LINE DEDENT else : NEW_LINE INDENT return ( 4 * lastNon0Digit ( n // 5 ) * dig [ n % 10 ] ) % 10 NEW_LINE DEDENT return 0 NEW_LINE DEDENT n = 14 NEW_LINE print ( lastNon0Digit ( n ) ) NEW_LINE |
Find the first natural number whose factorial is divisible by x | GCD function to compute the greatest divisor among a and b ; Returns first number whose factorial divides x . ; i = 1 Result ; Remove common factors ; We found first i . ; Driver code | def gcd ( a , b ) : NEW_LINE INDENT if ( ( a % b ) == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def firstFactorialDivisibleNumber ( x ) : NEW_LINE INDENT new_x = x NEW_LINE for i in range ( 1 , x ) : NEW_LINE INDENT new_x /= gcd ( i , new_x ) NEW_LINE if ( new_x == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return i NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT x = 16 NEW_LINE print ( firstFactorialDivisibleNumber ( x ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Find the highest occurring digit in prime numbers in a range | Sieve of Eratosthenes ; Returns maximum occurring digits in primes from l to r . ; Finding the prime number up to R . ; Initialise frequency of all digit to 0. ; For all number between L to R , check if prime or not . If prime , incrementing the frequency of digits present in the prime number . ; p = i If i is prime ; Finding digit with highest frequency . ; Driver Code | def sieve ( prime , n ) : NEW_LINE INDENT p = 2 NEW_LINE while p * p <= n : NEW_LINE INDENT if ( prime [ p ] == False ) : NEW_LINE INDENT for i in range ( p * 2 , n , p ) : NEW_LINE INDENT prime [ i ] = True NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def maxDigitInPrimes ( L , R ) : NEW_LINE INDENT prime = [ 0 ] * ( R + 1 ) NEW_LINE sieve ( prime , R ) NEW_LINE freq = [ 0 ] * 10 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( not prime [ i ] ) : NEW_LINE INDENT while ( p ) : NEW_LINE INDENT freq [ p % 10 ] += 1 NEW_LINE p //= 10 NEW_LINE DEDENT DEDENT DEDENT max = freq [ 0 ] NEW_LINE ans = 0 NEW_LINE for j in range ( 1 , 10 ) : NEW_LINE INDENT if ( max <= freq [ j ] ) : NEW_LINE INDENT max = freq [ j ] NEW_LINE ans = j NEW_LINE DEDENT DEDENT if max == 0 NEW_LINE return - 1 NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 1 NEW_LINE R = 20 NEW_LINE print ( maxDigitInPrimes ( L , R ) ) NEW_LINE DEDENT |
Sphenic Number | Create a global array of size 1001 ; ; This functions finds all primes smaller than ' limit ' using simple sieve of eratosthenes . ; Initialize all entries of it as True . A value in mark [ p ] will finally be False if ' p ' is Not a prime , else True . ; One by one traverse all numbers so that their multiples can be marked as composite . ; If p is not changed , then it is a prime ; Update all multiples of p ; To store the 8 divisors ; To count the number of divisor ; Finally check if there re 8 divisor and all the numbers are distinct prime no return 1 else return 0 ) ; ; Driver code | arr = [ True ] * ( 1001 ) NEW_LINE def simpleSieve ( ) : NEW_LINE INDENT k = 0 NEW_LINE for p in range ( 2 , 1001 ) : NEW_LINE INDENT if ( p * p > 1001 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( arr [ p ] ) : NEW_LINE INDENT for k in range ( p , 1001 , k + p ) : NEW_LINE INDENT arr [ k ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def find_sphene ( N ) : NEW_LINE INDENT arr1 = [ 0 ] * ( 8 ) NEW_LINE count = 0 NEW_LINE j = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( N % i == 0 and count < 8 ) : NEW_LINE INDENT count += 1 NEW_LINE arr1 [ j ] = i NEW_LINE j += 1 NEW_LINE DEDENT DEDENT if ( count == 8 and ( arr [ arr1 [ 1 ] ] and arr [ arr1 [ 2 ] ] and arr [ arr1 [ 3 ] ] ) ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 60 NEW_LINE simpleSieve ( ) NEW_LINE ans = find_sphene ( n ) NEW_LINE if ( ans == 1 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Common Divisors of Two Numbers | Python implementation of program ; Function to calculate gcd of two numbers ; Function to calculate all common divisors of two given numbers a , b -- > input integer numbers ; find GCD of a , b ; Count divisors of n ; if i is a factor of n ; check if divisors are equal ; Driver program to run the case | from math import sqrt NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if a == 0 : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def commDiv ( a , b ) : NEW_LINE INDENT n = gcd ( a , b ) NEW_LINE result = 0 NEW_LINE for i in range ( 1 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT if n / i == i : NEW_LINE INDENT result += 1 NEW_LINE DEDENT else : NEW_LINE INDENT result += 2 NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 12 NEW_LINE b = 24 ; NEW_LINE print ( commDiv ( a , b ) ) NEW_LINE DEDENT |
Count ways to spell a number with repeated digits | Function to calculate all possible spells of a number with repeated digits num -- > string which is favourite number ; final count of total possible spells ; iterate through complete number ; count contiguous frequency of particular digit num [ i ] ; Compute 2 ^ ( count - 1 ) and multiply with result ; Driver Code | def spellsCount ( num ) : NEW_LINE INDENT n = len ( num ) ; NEW_LINE result = 1 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT count = 1 ; NEW_LINE while ( i < n - 1 and num [ i + 1 ] == num [ i ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE i += 1 ; NEW_LINE DEDENT result = result * int ( pow ( 2 , count - 1 ) ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT num = "11112" ; NEW_LINE print ( spellsCount ( num ) ) ; NEW_LINE |
Happy Number | Utility method to return sum of square of digit of n ; method return true if n is Happy number ; initialize slow and fast by n ; move slow number by one iteration ; move fast number by two iteration ; if both number meet at 1 , then return true ; Driver Code | def numSquareSum ( n ) : NEW_LINE INDENT squareSum = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT squareSum += ( n % 10 ) * ( n % 10 ) ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE DEDENT return squareSum ; NEW_LINE DEDENT def isHappynumber ( n ) : NEW_LINE INDENT slow = n ; NEW_LINE fast = n ; NEW_LINE while ( True ) : NEW_LINE INDENT slow = numSquareSum ( slow ) ; NEW_LINE fast = numSquareSum ( numSquareSum ( fast ) ) ; NEW_LINE if ( slow != fast ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT return ( slow == 1 ) ; NEW_LINE DEDENT n = 13 ; NEW_LINE if ( isHappynumber ( n ) ) : NEW_LINE INDENT print ( n , " is β a β Happy β number " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( n , " is β not β a β Happy β number " ) ; NEW_LINE DEDENT |
Count Divisors of Factorial | allPrimes [ ] stores all prime numbers less than or equal to n . ; Fills above vector allPrimes [ ] for a given n ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is not a prime , else true . ; Loop to update prime [ ] ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store primes in the vector allPrimes ; Function to find all result of factorial number ; Initialize result ; find exponents of all primes which divides n and less than n ; Current divisor ; Find the highest power ( stored in exp ) ' β β of β allPrimes [ i ] β that β divides β n β using β β Legendre ' s formula . ; Multiply exponents of all primes less than n ; return total divisors ; Driver Code | allPrimes = [ ] ; NEW_LINE def sieve ( n ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT i = p * 2 ; NEW_LINE while ( i <= n ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE i += p ; NEW_LINE DEDENT DEDENT p += 1 ; NEW_LINE DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT allPrimes . append ( p ) ; NEW_LINE DEDENT DEDENT DEDENT def factorialDivisors ( n ) : NEW_LINE INDENT result = 1 ; NEW_LINE for i in range ( len ( allPrimes ) ) : NEW_LINE INDENT p = allPrimes [ i ] ; NEW_LINE exp = 0 ; NEW_LINE while ( p <= n ) : NEW_LINE INDENT exp = exp + int ( n / p ) ; NEW_LINE p = p * allPrimes [ i ] ; NEW_LINE DEDENT result = result * ( exp + 1 ) ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT print ( factorialDivisors ( 6 ) ) ; NEW_LINE |
Non Fibonacci Numbers | Returns n 'th Non-Fibonacci number ; curr is to keep track of current fibonacci number , prev is previous , prevPrev is previous of previous . ; While count of non - fibonacci numbers doesn 't become negative or zero ; Simple Fibonacci number logic ; ( curr - prev - 1 ) is count of non - Fibonacci numbers between curr and prev . ; n might be negative now . Make sure it becomes positive by removing last added gap . ; Now add the positive n to previous Fibonacci number to find the n 'th non-fibonacci. ; Driver code | def nonFibonacci ( n ) : NEW_LINE INDENT prevPrev = 1 NEW_LINE prev = 2 NEW_LINE curr = 3 NEW_LINE while n > 0 : NEW_LINE INDENT prevPrev = prev NEW_LINE prev = curr NEW_LINE curr = prevPrev + prev NEW_LINE n = n - ( curr - prev - 1 ) NEW_LINE DEDENT n = n + ( curr - prev - 1 ) NEW_LINE return prev + n NEW_LINE DEDENT print ( nonFibonacci ( 5 ) ) NEW_LINE |
Stein 's Algorithm for finding GCD | Function to implement Stein 's Algorithm ; GCD ( 0 , b ) == b ; GCD ( a , 0 ) == a , GCD ( 0 , 0 ) == 0 ; Finding K , where K is the greatest power of 2 that divides both a and b . ; Dividing a by 2 until a becomes odd ; From here on , ' a ' is always odd . ; If b is even , remove all factor of 2 in b ; Now a and b are both odd . Swap if necessary so a <= b , then set b = b - a ( which is even ) . ; restore common factors of 2 ; Driver code | def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT k = 0 NEW_LINE while ( ( ( a b ) & 1 ) == 0 ) : NEW_LINE INDENT a = a >> 1 NEW_LINE b = b >> 1 NEW_LINE k = k + 1 NEW_LINE DEDENT while ( ( a & 1 ) == 0 ) : NEW_LINE INDENT a = a >> 1 NEW_LINE DEDENT while ( b != 0 ) : NEW_LINE INDENT while ( ( b & 1 ) == 0 ) : NEW_LINE INDENT b = b >> 1 NEW_LINE DEDENT if ( a > b ) : NEW_LINE INDENT temp = a NEW_LINE a = b NEW_LINE b = temp NEW_LINE DEDENT b = ( b - a ) NEW_LINE DEDENT return ( a << k ) NEW_LINE DEDENT a = 34 NEW_LINE b = 17 NEW_LINE print ( " Gcd β of β given β numbers β is β " , gcd ( a , b ) ) NEW_LINE |
Print all n | n -- > value of input out -- > output array index -- > index of next digit to be filled in output array evenSum , oddSum -- > sum of even and odd digits so far ; Base case ; If number becomes n - digit ; if absolute difference between sum of even and odd digits is 1 , print the number ; If current index is odd , then add it to odd sum and recurse ; else : else add to even sum and recurse ; This is mainly a wrapper over findNDigitNumsUtil . It explicitly handles leading digit and calls findNDigitNumsUtil ( ) for remaining indexes . ; output array to store n - digit numbers ; Initialize number index considered so far ; Initialize even and odd sums ; Explicitly handle first digit and call recursive function findNDigitNumsUtil for remaining indexes . Note that the first digit is considered to be present in even position . ; Driver Code | def findNDigitNumsUtil ( n , out , index , evenSum , oddSum ) : NEW_LINE INDENT if ( index > n ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( index == n ) : NEW_LINE INDENT if ( abs ( evenSum - oddSum ) == 1 ) : NEW_LINE INDENT out [ index ] = ' ' NEW_LINE out = ' ' . join ( out ) NEW_LINE print ( out , end = " β " ) NEW_LINE DEDENT return NEW_LINE DEDENT if ( index & 1 ) : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT out [ index ] = chr ( i + ord ( '0' ) ) NEW_LINE findNDigitNumsUtil ( n , out , index + 1 , evenSum , oddSum + i ) NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT out [ index ] = chr ( i + ord ( '0' ) ) NEW_LINE findNDigitNumsUtil ( n , out , index + 1 , evenSum + i , oddSum ) NEW_LINE DEDENT DEDENT DEDENT def findNDigitNums ( n ) : NEW_LINE INDENT out = [ 0 ] * ( n + 1 ) NEW_LINE index = 0 NEW_LINE evenSum = 0 NEW_LINE oddSum = 0 NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT out [ index ] = chr ( i + ord ( '0' ) ) NEW_LINE findNDigitNumsUtil ( n , out , index + 1 , evenSum + i , oddSum ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE findNDigitNums ( n ) NEW_LINE DEDENT |
Program to convert a given number to words | Set 2 | strings at index 0 is not used , it is to make array indexing simple ; strings at index 0 and 1 are not used , they is to make array indexing simple ; n is 1 - or 2 - digit number ; if n is more than 19 , divide it ; if n is non - zero ; Function to print a given number in words ; stores word representation of given number n ; handles digits at ten millions and hundred millions places ( if any ) ; handles digits at hundred thousands and one millions places ( if any ) ; handles digits at thousands and tens thousands places ( if any ) ; handles digit at hundreds places ( if any ) ; handles digits at ones and tens places ( if any ) ; long handles upto 9 digit no change to unsigned long long int to handle more digit number ; convert given number in words | one = [ " " , " one β " , " two β " , " three β " , " four β " , " five β " , " six β " , " seven β " , " eight β " , " nine β " , " ten β " , " eleven β " , " twelve β " , " thirteen β " , " fourteen β " , " fifteen β " , " sixteen β " , " seventeen β " , " eighteen β " , " nineteen β " ] ; NEW_LINE ten = [ " " , " " , " twenty β " , " thirty β " , " forty β " , " fifty β " , " sixty β " , " seventy β " , " eighty β " , " ninety β " ] ; NEW_LINE def numToWords ( n , s ) : NEW_LINE INDENT str = " " ; NEW_LINE if ( n > 19 ) : NEW_LINE INDENT str += ten [ n // 10 ] + one [ n % 10 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT str += one [ n ] ; NEW_LINE DEDENT if ( n ) : NEW_LINE INDENT str += s ; NEW_LINE DEDENT return str ; NEW_LINE DEDENT def convertToWords ( n ) : NEW_LINE INDENT out = " " ; NEW_LINE out += numToWords ( ( n // 10000000 ) , " crore β " ) ; NEW_LINE out += numToWords ( ( ( n // 100000 ) % 100 ) , " lakh β " ) ; NEW_LINE out += numToWords ( ( ( n // 1000 ) % 100 ) , " thousand β " ) ; NEW_LINE out += numToWords ( ( ( n // 100 ) % 10 ) , " hundred β " ) ; NEW_LINE if ( n > 100 and n % 100 ) : NEW_LINE INDENT out += " and β " ; NEW_LINE DEDENT out += numToWords ( ( n % 100 ) , " " ) ; NEW_LINE return out ; NEW_LINE DEDENT n = 438237764 ; NEW_LINE print ( convertToWords ( n ) ) ; NEW_LINE |
Find number of subarrays with even sum | Python 3 program to count number of sub - arrays with even sum using an efficient algorithm Time Complexity - O ( N ) Space Complexity - O ( 1 ) ; result may be large enough not to fit in int ; ; to keep track of subarrays with even sum starting from index i ; if a [ i ] is odd then all subarrays starting from index i + 1 which was odd becomes even when a [ i ] gets added to it . ; if a [ i ] is even then all subarrays starting from index i + 1 which was even remains even and one extra a [ i ] even subarray gets added to it . ; Driver code | def countEvenSum ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE s = 0 NEW_LINE for i in reversed ( range ( n ) ) : NEW_LINE INDENT if arr [ i ] % 2 == 1 : NEW_LINE INDENT s = n - i - 1 - s NEW_LINE DEDENT else : NEW_LINE INDENT s = s + 1 NEW_LINE DEDENT res = res + s NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 3 , 4 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " The β Number β of β Subarrays β with β even " " β sum β is " , countEvenSum ( arr , n ) ) NEW_LINE DEDENT |
Linear Diophantine Equations | Python 3 program to check for solutions of diophantine equations ; This function checks if integral solutions are possible ; Driver Code ; First example ; Second example ; Third example | from math import gcd NEW_LINE def isPossible ( a , b , c ) : NEW_LINE INDENT return ( c % gcd ( a , b ) == 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 3 NEW_LINE b = 6 NEW_LINE c = 9 NEW_LINE if ( isPossible ( a , b , c ) ) : NEW_LINE INDENT print ( " Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT a = 3 NEW_LINE b = 6 NEW_LINE c = 8 NEW_LINE if ( isPossible ( a , b , c ) ) : NEW_LINE INDENT print ( " Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT a = 2 NEW_LINE b = 5 NEW_LINE c = 1 NEW_LINE if ( isPossible ( a , b , c ) ) : NEW_LINE INDENT print ( " Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT DEDENT |
Farey Sequence | Efficient Python3 program to print Farey Sequence of order n ; Optimized function to print Farey sequence of order n ; We know first two terms are 0 / 1 and 1 / n ; For next terms to be evaluated ; Using recurrence relation to find the next term ; Print next term ; Update x1 , y1 , x2 and y2 for next iteration ; Driver Code | import math NEW_LINE def farey ( n ) : NEW_LINE INDENT x1 = 0 ; NEW_LINE y1 = 1 ; NEW_LINE x2 = 1 ; NEW_LINE y2 = n ; NEW_LINE print ( x1 , end = " " ) NEW_LINE print ( " / " , end = " " ) NEW_LINE print ( y1 , x2 , end = " " ) NEW_LINE print ( " / " , end = " " ) NEW_LINE print ( y2 , end = " β " ) ; NEW_LINE x = 0 ; NEW_LINE y = 0 ; NEW_LINE while ( y != 1.0 ) : NEW_LINE INDENT x = math . floor ( ( y1 + n ) / y2 ) * x2 - x1 ; NEW_LINE y = math . floor ( ( y1 + n ) / y2 ) * y2 - y1 ; NEW_LINE print ( x , end = " " ) NEW_LINE print ( " / " , end = " " ) NEW_LINE print ( y , end = " β " ) ; NEW_LINE x1 = x2 ; NEW_LINE x2 = x ; NEW_LINE y1 = y2 ; NEW_LINE y2 = y ; NEW_LINE DEDENT DEDENT n = 7 ; NEW_LINE print ( " Farey β Sequence β of β order " , n , " is " ) ; NEW_LINE farey ( n ) ; NEW_LINE |
Find smallest values of x and y such that ax | To find GCD using Eculcid 's algorithm ; Prints smallest values of x and y that satisfy " ax β - β by β = β 0" ; Find LCM ; 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 findSmallest ( a , b ) : NEW_LINE INDENT lcm = ( a * b ) / gcd ( a , b ) NEW_LINE print ( " x β = " , lcm / a , " y = " , lcm / b ) NEW_LINE DEDENT a = 25 NEW_LINE b = 35 NEW_LINE findSmallest ( a , b ) NEW_LINE |
Compute n ! under modulo p | Utility function to do modular exponentiation . It returns ( x ^ y ) % p ; res = 1 ; Initialize result x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to find modular inverse of a under modulo p using Fermat 's method. Assumption: p is prime ; Returns n ! % p using Wilson 's Theorem ; n ! % p is 0 if n >= p ; Initialize result as ( p - 1 ) ! which is - 1 or ( p - 1 ) ; Multiply modulo inverse of all numbers from ( n + 1 ) to p ; Driver code | def power ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p ; NEW_LINE DEDENT x = ( x * x ) % p ; NEW_LINE DEDENT return res NEW_LINE DEDENT def modInverse ( a , p ) : NEW_LINE INDENT return power ( a , p - 2 , p ) NEW_LINE DEDENT def modFact ( n , p ) : NEW_LINE INDENT if ( p <= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = ( p - 1 ) NEW_LINE for i in range ( n + 1 , p ) : NEW_LINE INDENT res = ( res * modInverse ( i , p ) ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT n = 25 NEW_LINE p = 29 NEW_LINE print ( modFact ( n , p ) ) NEW_LINE |
Count number of ways to divide a number in 4 parts | Returns count of ways ; Generate all possible quadruplet and increment counter when sum of a quadruplet is equal to n ; Driver Code | def countWays ( n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT for k in range ( j , n ) : NEW_LINE INDENT for l in range ( k , n ) : NEW_LINE INDENT if ( i + j + k + l == n ) : NEW_LINE INDENT counter += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return counter NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 8 NEW_LINE print ( countWays ( n ) ) NEW_LINE DEDENT |
Sum of Bitwise And of all pairs in a given array | Returns value of " arr [ 0 ] β & β arr [ 1 ] β + β arr [ 0 ] β & β arr [ 2 ] β + β . . . β arr [ i ] β & β arr [ j ] β + β . . . . . β arr [ n - 2 ] β & β arr [ n - 1 ] " ; Consider all pairs ( arr [ i ] , arr [ j ) such that i < j ; Driver program to test above function | def pairAndSum ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( ( i + 1 ) , n ) : NEW_LINE INDENT ans = ans + arr [ i ] & arr [ j ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 5 , 10 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE print ( pairAndSum ( arr , n ) ) NEW_LINE |
Sum of Bitwise And of all pairs in a given array | Returns value of " arr [ 0 ] β & β arr [ 1 ] β + β arr [ 0 ] β & β arr [ 2 ] β + β . . . β arr [ i ] β & β arr [ j ] β + β . . . . . β arr [ n - 2 ] β & β arr [ n - 1 ] " ; Traverse over all bits ; Count number of elements with i 'th bit set Initialize the count ; There are k set bits , means k ( k - 1 ) / 2 pairs . Every pair adds 2 ^ i to the answer . Therefore , we add "2 ^ i β * β [ k * ( k - 1 ) / 2 ] " to the answer . ; Driver program to test above function | def pairAndSum ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , 32 ) : NEW_LINE INDENT k = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( ( arr [ j ] & ( 1 << i ) ) ) : NEW_LINE INDENT k = k + 1 NEW_LINE DEDENT DEDENT ans = ans + ( 1 << i ) * ( k * ( k - 1 ) // 2 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 5 , 10 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE print ( pairAndSum ( arr , n ) ) NEW_LINE |
Primality Test | Set 1 ( Introduction and School Method ) | A school method based Python3 program to check if a number is prime ; Corner case ; Check from 2 to n - 1 ; Driver Program to test above function | def isPrime ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT print ( " true " ) if isPrime ( 11 ) else print ( " false " ) NEW_LINE print ( " true " ) if isPrime ( 14 ) else print ( " false " ) NEW_LINE |
Euler 's Totient function for all numbers smaller than or equal to n | Computes and prints totient of all numbers smaller than or equal to n . ; Create and initialize an array to store phi or totient values ; Compute other Phi values ; If phi [ p ] is not computed already , then number p is prime ; Phi of a prime number p is always equal to p - 1. ; Update phi values of all multiples of p ; Add contribution of p to its multiple i by multiplying with ( 1 - 1 / p ) ; Print precomputed phi values ; Driver code | def computeTotient ( n ) : NEW_LINE INDENT phi = [ ] NEW_LINE for i in range ( n + 2 ) : NEW_LINE INDENT phi . append ( 0 ) NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( phi [ p ] == p ) : NEW_LINE INDENT phi [ p ] = p - 1 NEW_LINE for i in range ( 2 * p , n + 1 , p ) : NEW_LINE INDENT phi [ i ] = ( phi [ i ] // p ) * ( p - 1 ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( " Totient β of β " , i , " β is β " , phi [ i ] ) NEW_LINE DEDENT DEDENT n = 12 NEW_LINE computeTotient ( n ) NEW_LINE |
Euler 's Totient function for all numbers smaller than or equal to n | python program for the above approach ; Driver code | import math NEW_LINE def Euler_totient_function ( n ) : NEW_LINE INDENT result = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT c = 0 NEW_LINE if n % i == 0 : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE n //= i NEW_LINE DEDENT DEDENT if ( c > 0 ) : NEW_LINE INDENT power = math . pow ( i , c - 1 ) NEW_LINE m = math . pow ( i , c - 1 ) * ( i - 1 ) NEW_LINE result *= m NEW_LINE DEDENT DEDENT if ( n > 1 ) : NEW_LINE INDENT result *= ( n - 1 ) NEW_LINE DEDENT return int ( result ) NEW_LINE DEDENT for i in range ( 1 , 13 ) : NEW_LINE INDENT print ( " Euler _ totient _ function ( " , i , " ) : β " , end = " " ) NEW_LINE print ( Euler_totient_function ( i ) ) NEW_LINE DEDENT |
Check if a number can be expressed as x ^ y ( x raised to power y ) | Python3 program to check if a given number can be expressed as power ; Returns true if n can be written as x ^ y ; Driver code | import math NEW_LINE def isPower ( n ) : NEW_LINE INDENT p = 0 NEW_LINE if ( n <= 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for i in range ( 2 , ( int ) ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT p = math . log2 ( n ) / math . log2 ( i ) NEW_LINE if ( ( math . ceil ( p ) == math . floor ( p ) ) and p > 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT for i in range ( 2 , 100 ) : NEW_LINE INDENT if isPower ( i ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT |
Sum of all elements between k1 ' th β and β k2' th smallest elements | Returns sum between two kth smallest element of array ; Sort the given array ; Below code is equivalent to ; Driver code | def sumBetweenTwoKth ( arr , n , k1 , k2 ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE result = 0 NEW_LINE for i in range ( k1 , k2 - 1 ) : NEW_LINE INDENT result += arr [ i ] NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 20 , 8 , 22 , 4 , 12 , 10 , 14 ] NEW_LINE k1 = 3 ; k2 = 6 NEW_LINE n = len ( arr ) NEW_LINE print ( sumBetweenTwoKth ( arr , n , k1 , k2 ) ) NEW_LINE |
Puzzle | Program to find number of squares in a chessboard | Function to return count of squares ; ; better way to write n * ( n + 1 ) * ( 2 n + 1 ) / 6 ; Driver code | def countSquares ( n ) : NEW_LINE INDENT return ( ( n * ( n + 1 ) / 2 ) * ( 2 * n + 1 ) / 3 ) NEW_LINE DEDENT n = 4 NEW_LINE print ( " Count β of β squares β is β " , countSquares ( n ) ) NEW_LINE |
Find nth Magic Number | Function to find nth magic number ; Go through every bit of n ; If last bit of n is set ; proceed to next bit n >>= 1 or n = n / 2 ; Driver program to test above function | def nthMagicNo ( n ) : NEW_LINE INDENT pow = 1 NEW_LINE answer = 0 NEW_LINE while ( n ) : NEW_LINE INDENT pow = pow * 5 NEW_LINE if ( n & 1 ) : NEW_LINE INDENT answer += pow NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT n = 5 NEW_LINE print ( " nth β magic β number β is " , nthMagicNo ( n ) ) NEW_LINE |
Given a number n , count all multiples of 3 and / or 5 in set { 1 , 2 , 3 , ... n } | python program to find count of multiples of 3 and 5 in { 1 , 2 , 3 , . . n } ; Add multiples of 3 and 5. Since common multiples are counted twice in n / 3 + n / 15 , subtract common multiples ; Driver program to test above function | def countOfMultiples ( n ) : NEW_LINE INDENT return ( int ( n / 3 ) + int ( n / 5 ) - int ( n / 15 ) ) ; NEW_LINE DEDENT print ( countOfMultiples ( 6 ) ) NEW_LINE print ( countOfMultiples ( 16 ) ) NEW_LINE |
Program to find GCD or HCF of two numbers | Recursive function to return gcd of a and b ; Everything divides 0 ; base case ; a is greater ; Driver program to test above function | def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT if ( a == b ) : NEW_LINE INDENT return a NEW_LINE DEDENT if ( a > b ) : NEW_LINE INDENT return gcd ( a - b , b ) NEW_LINE DEDENT return gcd ( a , b - a ) NEW_LINE DEDENT a = 98 NEW_LINE b = 56 NEW_LINE if ( gcd ( a , b ) ) : NEW_LINE INDENT print ( ' GCD β of ' , a , ' and ' , b , ' is ' , gcd ( a , b ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' not β found ' ) NEW_LINE DEDENT |
Find XOR sum of Bitwise AND of all pairs from given two Arrays | Function to calculate the XOR sum of all ANDS of all pairs on A [ ] and B [ ] ; variable to store xor sums of first array and second array respectively . ; Xor sum of first array ; Xor sum of second array ; required answer ; Driver code ; Input ; Function call | def XorSum ( A , B , N , M ) : NEW_LINE INDENT ans1 = 0 NEW_LINE ans2 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT ans1 = ans1 ^ A [ i ] NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT ans2 = ans2 ^ B [ i ] NEW_LINE DEDENT return ( ans1 & ans2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 5 ] NEW_LINE B = [ 2 , 3 ] NEW_LINE N = len ( A ) NEW_LINE M = len ( B ) NEW_LINE print ( XorSum ( A , B , N , M ) ) NEW_LINE DEDENT |
Count levels in a Binary Tree consisting of node values having set bits at different positions | Structure of a node in the binary tree ; Function to find total unique levels ; Stores count of levels , where the set bits of all the nodes are at different positions ; Store nodes at each level of the tree using BFS ; Performing level order traversal ; Stores count of nodes at current level ; Stores prefix XOR of all the nodes at current level ; Stores prefix OR of all the nodes at current level ; Check if set bit of all the nodes at current level is at different positions or not ; Traverse nodes at current level ; Stores front element of the que ; Update prefix_OR ; Update prefix_XOR ; If left subtree not NULL ; If right subtree not NULL ; If bitwise AND is zero ; Driver Code ; Function Call | class TreeNode : NEW_LINE INDENT def __init__ ( self , val = 0 , left = None , right = None ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def uniqueLevels ( root ) : NEW_LINE INDENT uniqueLevels = 0 NEW_LINE que = [ root ] NEW_LINE while len ( que ) : NEW_LINE INDENT length = len ( que ) NEW_LINE prefix_XOR = 0 ; NEW_LINE prefix_OR = 0 NEW_LINE flag = True NEW_LINE while length : NEW_LINE INDENT temp = que . pop ( 0 ) NEW_LINE prefix_OR |= temp . val NEW_LINE prefix_XOR ^= temp . val NEW_LINE if prefix_XOR != prefix_OR : NEW_LINE INDENT flag = False NEW_LINE DEDENT if temp . left : NEW_LINE INDENT que . append ( temp . left ) NEW_LINE DEDENT if temp . right : NEW_LINE INDENT que . append ( temp . right ) NEW_LINE DEDENT length -= 1 NEW_LINE DEDENT if flag : NEW_LINE INDENT uniqueLevels += 1 NEW_LINE DEDENT DEDENT print ( uniqueLevels ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = TreeNode ( 5 ) NEW_LINE root . left = TreeNode ( 6 ) NEW_LINE root . right = TreeNode ( 9 ) NEW_LINE root . left . left = TreeNode ( 1 ) NEW_LINE root . left . right = TreeNode ( 4 ) NEW_LINE root . right . right = TreeNode ( 7 ) NEW_LINE uniqueLevels ( root ) NEW_LINE DEDENT |
Sum of all elements between k1 ' th β and β k2' th smallest elements | Python 3 implementation of above approach ; Driver Code ; decreasing value by 1 because we want min heapifying k times and it starts from 0 so we have to decrease it 1 time ; Step 1 : Do extract minimum k1 times ( This step takes O ( K1 Log n ) time ) ; Step 2 : Do extract minimum k2 k1 1 times and sum all extracted elements . ( This step takes O ( ( K2 k1 ) * Log n ) time ) | n = 7 NEW_LINE def minheapify ( a , index ) : NEW_LINE INDENT small = index NEW_LINE l = 2 * index + 1 NEW_LINE r = 2 * index + 2 NEW_LINE if ( l < n and a [ l ] < a [ small ] ) : NEW_LINE INDENT small = l NEW_LINE DEDENT if ( r < n and a [ r ] < a [ small ] ) : NEW_LINE INDENT small = r NEW_LINE DEDENT if ( small != index ) : NEW_LINE INDENT ( a [ small ] , a [ index ] ) = ( a [ index ] , a [ small ] ) NEW_LINE minheapify ( a , small ) NEW_LINE DEDENT DEDENT i = 0 NEW_LINE k1 = 3 NEW_LINE k2 = 6 NEW_LINE a = [ 20 , 8 , 22 , 4 , 12 , 10 , 14 ] NEW_LINE ans = 0 NEW_LINE for i in range ( ( n // 2 ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT minheapify ( a , i ) NEW_LINE DEDENT k1 -= 1 NEW_LINE k2 -= 1 NEW_LINE for i in range ( 0 , k1 + 1 ) : NEW_LINE INDENT a [ 0 ] = a [ n - 1 ] NEW_LINE n -= 1 NEW_LINE minheapify ( a , 0 ) NEW_LINE DEDENT for i in range ( k1 + 1 , k2 ) : NEW_LINE INDENT ans += a [ 0 ] NEW_LINE a [ 0 ] = a [ n - 1 ] NEW_LINE n -= 1 NEW_LINE minheapify ( a , 0 ) NEW_LINE DEDENT print ( ans ) NEW_LINE |
Construct a List using the given Q XOR queries | Function to return required list after performing all the queries ; Store cumulative Bitwise XOR ; Initialize final list to return ; Perform each query ; The initial value of 0 ; Sort the list ; Return final list ; Given Queries ; Function call | def ConstructList ( Q ) : NEW_LINE INDENT xor = 0 NEW_LINE ans = [ ] NEW_LINE for i in range ( len ( Q ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( Q [ i ] [ 0 ] == 0 ) : NEW_LINE INDENT ans . append ( Q [ i ] [ 1 ] ^ xor ) NEW_LINE DEDENT else : NEW_LINE INDENT xor ^= Q [ i ] [ 1 ] NEW_LINE DEDENT DEDENT ans . append ( xor ) NEW_LINE ans . sort ( ) NEW_LINE return ans NEW_LINE DEDENT Q = [ [ 0 , 6 ] , [ 0 , 3 ] , [ 0 , 2 ] , [ 1 , 4 ] , [ 1 , 5 ] ] NEW_LINE print ( ConstructList ( Q ) ) NEW_LINE |
Bitwise operations on Subarrays of size K | Function to convert bit array to decimal number ; Function to find maximum values of each bitwise OR operation on element of subarray of size K ; Maintain an integer array bit of size 32 all initialized to 0 ; Create a sliding window of size k ; Function call ; Perform operation for removed element ; Perform operation for added_element ; Taking maximum value ; Return the result ; Driver Code ; Given array arr ; Given subarray size K ; Function call | def build_num ( bit ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT if ( bit [ i ] > 0 ) : NEW_LINE INDENT ans += ( 1 << i ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT def maximumOR ( arr , n , k ) : NEW_LINE INDENT bit = [ 0 ] * 32 ; NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( 32 ) : NEW_LINE INDENT if ( ( arr [ i ] & ( 1 << j ) ) > 0 ) : NEW_LINE INDENT bit [ j ] += 1 ; NEW_LINE DEDENT DEDENT DEDENT max_or = build_num ( bit ) ; NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT for j in range ( 32 ) : NEW_LINE INDENT if ( ( arr [ i - k ] & ( 1 << j ) ) > 0 ) : NEW_LINE INDENT bit [ j ] -= 1 ; NEW_LINE DEDENT DEDENT for j in range ( 32 ) : NEW_LINE INDENT if ( ( arr [ i ] & ( 1 << j ) ) > 0 ) : NEW_LINE INDENT bit [ j ] += 1 ; NEW_LINE DEDENT DEDENT max_or = max ( build_num ( bit ) , max_or ) ; NEW_LINE DEDENT return max_or ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 5 , 3 , 6 , 11 , 13 ] ; NEW_LINE k = 3 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maximumOR ( arr , n , k ) ) ; NEW_LINE DEDENT |
Maximum XOR path of a Binary Tree | Binary tree node ; Function to create a new node ; Function calculate the value of max - xor ; Updating the xor value with the xor of the path from root to the node ; Check if node is leaf node ; Check if the left node exist in the tree ; Check if the right node exist in the tree ; Function to find the required count ; Recursively traverse the tree and compute the max_xor ; Return the result ; Create the binary tree | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def Solve ( root , xr , max_xor ) : NEW_LINE INDENT xr = xr ^ root . data NEW_LINE if ( root . left == None and root . right == None ) : NEW_LINE INDENT max_xor [ 0 ] = max ( max_xor [ 0 ] , xr ) NEW_LINE DEDENT if root . left != None : NEW_LINE INDENT Solve ( root . left , xr , max_xor ) NEW_LINE DEDENT if root . right != None : NEW_LINE INDENT Solve ( root . right , xr , max_xor ) NEW_LINE DEDENT return NEW_LINE DEDENT def findMaxXor ( root ) : NEW_LINE INDENT xr , max_xor = 0 , [ 0 ] NEW_LINE Solve ( root , xr , max_xor ) NEW_LINE return max_xor [ 0 ] NEW_LINE DEDENT root = Node ( 2 ) NEW_LINE root . left = Node ( 1 ) NEW_LINE root . right = Node ( 4 ) NEW_LINE root . left . left = Node ( 10 ) NEW_LINE root . left . right = Node ( 8 ) NEW_LINE root . right . left = Node ( 5 ) NEW_LINE root . right . right = Node ( 10 ) NEW_LINE print ( findMaxXor ( root ) ) NEW_LINE |
XOR of every element of an Array with a given number K | Function to construct new array ; Traverse the array and compute XOR with K ; Print new array ; Driver code | def constructXORArray ( A , n , K ) : NEW_LINE INDENT B = [ 0 ] * n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT B [ i ] = A [ i ] ^ K ; 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 A = [ 2 , 4 , 1 , 3 , 5 ] ; NEW_LINE K = 5 ; NEW_LINE n = len ( A ) ; NEW_LINE constructXORArray ( A , n , K ) ; NEW_LINE B = [ 4 , 75 , 45 , 42 ] ; NEW_LINE K = 2 ; NEW_LINE n = len ( B ) ; NEW_LINE constructXORArray ( B , n , K ) ; NEW_LINE DEDENT |
Bitwise AND of all the elements of array | Function to calculate bitwise AND ; Initialise ans variable is arr [ 0 ] ; Traverse the array compute AND ; Return ans ; Driver Code ; Function Call to find AND | def find_and ( arr ) : NEW_LINE INDENT ans = arr [ 0 ] NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT ans = ans & arr [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 5 , 9 , 11 ] NEW_LINE print ( find_and ( arr ) ) NEW_LINE DEDENT |
Subsets and Splits