text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
N | ; function to find Nth polite number ; Driver code | import math NEW_LINE def Polite ( n ) : NEW_LINE INDENT n = n + 1 NEW_LINE return ( int ) ( n + ( math . log ( ( n + math . log ( n , 2 ) ) , 2 ) ) ) NEW_LINE DEDENT n = 7 NEW_LINE print Polite ( n ) NEW_LINE |
Find the number of stair steps | Modified Binary search function to solve the equation ; if mid is solution to equation ; if our solution to equation lies between mid and mid - 1 ; if solution to equation is greater than mid ; if solution to equation is less than mid ; driver code ; call binary search method to solve for limits 1 to T ; Because our pattern starts from 2 , 3 , 4 , 5. . . so , we subtract 1 from ans | def solve ( low , high , T ) : NEW_LINE INDENT while low <= high : NEW_LINE INDENT mid = int ( ( low + high ) / 2 ) NEW_LINE if ( mid * ( mid + 1 ) ) == T : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( mid > 0 and ( mid * ( mid + 1 ) ) > T and ( mid * ( mid - 1 ) ) <= T ) : NEW_LINE INDENT return mid - 1 NEW_LINE DEDENT if ( mid * ( mid + 1 ) ) > T : NEW_LINE INDENT high = mid - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT T = 15 NEW_LINE ans = solve ( 1 , T , 2 * T ) NEW_LINE if ans != - 1 : NEW_LINE INDENT ans -= 1 NEW_LINE DEDENT print ( " Number β of β stair β steps β = β " , ans ) NEW_LINE |
Check for integer overflow on multiplication | Function to check whether there is overflow in a * b or not . It returns true if there is overflow . ; Check if either of them is zero ; Driver code | def isOverflow ( a , b ) : NEW_LINE INDENT if ( a == 0 or b == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT result = a * b NEW_LINE if ( result >= 9223372036854775807 or result <= - 9223372036854775808 ) : NEW_LINE INDENT result = 0 NEW_LINE DEDENT if ( a == ( result // b ) ) : NEW_LINE INDENT print ( result // b ) NEW_LINE return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 10000000000 NEW_LINE b = - 10000000000 NEW_LINE if ( isOverflow ( a , b ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Sum of first n odd numbers in O ( 1 ) Complexity | Python3 program to find sum of first n odd numbers ; Returns the sum of first n odd numbers ; Driver Code | def oddSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE curr = 1 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT sum = sum + curr NEW_LINE curr = curr + 2 NEW_LINE i = i + 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 20 NEW_LINE print ( " β Sum β of β first " , n , " Odd β Numbers β is : β " , oddSum ( n ) ) NEW_LINE |
Sum of first n odd numbers in O ( 1 ) Complexity | Returns the sum of first n odd numbers ; Driver Code | def oddSum ( n ) : NEW_LINE INDENT return ( n * n ) ; NEW_LINE DEDENT n = 20 NEW_LINE print ( " β Sum β of β first " , n , " Odd β Numbers β is : β " , oddSum ( n ) ) NEW_LINE |
K | Returns the sum of first n odd numbers ; Count prime factors of all numbers till B . ; Print all numbers with k prime factors ; Driver code | def printKPFNums ( A , B , K ) : NEW_LINE INDENT prime = [ True ] * ( B + 1 ) NEW_LINE p_factors = [ 0 ] * ( B + 1 ) NEW_LINE for p in range ( 2 , B + 1 ) : NEW_LINE INDENT if ( p_factors [ p ] == 0 ) : NEW_LINE INDENT for i in range ( p , B + 1 , p ) : NEW_LINE INDENT p_factors [ i ] = p_factors [ i ] + 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( A , B + 1 ) : NEW_LINE INDENT if ( p_factors [ i ] == K ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT A = 14 NEW_LINE B = 18 NEW_LINE K = 2 NEW_LINE printKPFNums ( A , B , K ) NEW_LINE |
Queries for maximum difference between prime numbers in given ranges | Python 3 program to find maximum differences between two prime numbers in given ranges ; Precompute Sieve , Prefix array , Suffix array ; Sieve of Eratosthenes ; Precomputing Prefix array . ; Precompute Suffix array . ; Function to solve each query ; Driver Code | from math import sqrt NEW_LINE MAX = 100005 NEW_LINE def precompute ( prefix , suffix ) : NEW_LINE INDENT prime = [ True for i in range ( MAX ) ] NEW_LINE k = int ( sqrt ( MAX ) ) NEW_LINE for i in range ( 2 , k , 1 ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , MAX , i ) : NEW_LINE INDENT prime [ j ] = False NEW_LINE DEDENT DEDENT DEDENT prefix [ 1 ] = 1 NEW_LINE suffix [ MAX - 1 ] = int ( 1e9 + 7 ) NEW_LINE for i in range ( 2 , MAX , 1 ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT prefix [ i ] = i NEW_LINE DEDENT else : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] NEW_LINE DEDENT DEDENT i = MAX - 2 NEW_LINE while ( i > 1 ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT suffix [ i ] = i NEW_LINE DEDENT else : NEW_LINE INDENT suffix [ i ] = suffix [ i + 1 ] NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT DEDENT def query ( prefix , suffix , L , R ) : NEW_LINE INDENT if ( prefix [ R ] < L or suffix [ L ] > R ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return prefix [ R ] - suffix [ L ] NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT q = 3 NEW_LINE L = [ 2 , 2 , 24 ] NEW_LINE R = [ 5 , 2 , 28 ] NEW_LINE prefix = [ 0 for i in range ( MAX ) ] NEW_LINE suffix = [ 0 for i in range ( MAX ) ] NEW_LINE precompute ( prefix , suffix ) NEW_LINE for i in range ( 0 , q , 1 ) : NEW_LINE INDENT print ( query ( prefix , suffix , L [ i ] , R [ i ] ) ) NEW_LINE DEDENT DEDENT |
Sum of the Series 1 + x / 1 + x ^ 2 / 2 + x ^ 3 / 3 + . . + x ^ n / n | Function to print the sum of the series ; Driver Code | def SUM ( x , n ) : NEW_LINE INDENT total = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT total = total + ( ( x ** i ) / i ) NEW_LINE DEDENT return total NEW_LINE DEDENT x = 2 NEW_LINE n = 5 NEW_LINE s = SUM ( x , n ) NEW_LINE print ( round ( s , 2 ) ) NEW_LINE |
Find if a number is part of AP whose first element and difference are given | '' returns yes if exist else no. ; If difference is 0 , then x must be same as a . ; Else difference between x and a must be divisible by d . ; Driver code | def isMember ( a , d , x ) : NEW_LINE INDENT if d == 0 : NEW_LINE INDENT return x == a NEW_LINE DEDENT return ( ( x - a ) % d == 0 and int ( ( x - a ) / d ) >= 0 ) NEW_LINE DEDENT a = 1 NEW_LINE x = 7 NEW_LINE d = 3 NEW_LINE if isMember ( a , d , x ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Number of GP ( Geometric Progression ) subsequences of size 3 | Python3 program to count GP subsequences of size 3. ; To calculate nCr DP approach ; nC0 is 1 ; Compute next row of pascal triangle using the previous row ; 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 ; IF RATIO IS ONE ; Traverse the count in hash ; calculating nC3 , where ' n ' is the number of times each number is repeated in the input ; 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 binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ 0 ] * ( k + 1 ) NEW_LINE C [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) , - 1 , - 1 ) : NEW_LINE C [ j ] = C [ j ] + C [ j - 1 ] NEW_LINE DEDENT return C [ k ] NEW_LINE DEDENT def subsequences ( a , n , r ) : NEW_LINE INDENT left = defaultdict ( int ) NEW_LINE right = defaultdict ( int ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT right [ a [ i ] ] += 1 NEW_LINE DEDENT if ( r == 1 ) : NEW_LINE INDENT for i in right : NEW_LINE INDENT ans += binomialCoeff ( right [ i ] , 3 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT c1 = 0 NEW_LINE c2 = 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 |
Check whether a number can be represented by sum of two squares | function to check if there exist two numbers sum of whose squares is n . ; driver Program | def sumSquare ( n ) : NEW_LINE INDENT i = 1 NEW_LINE while i * i <= n : NEW_LINE INDENT j = 1 NEW_LINE while ( j * j <= n ) : NEW_LINE INDENT if ( i * i + j * j == n ) : NEW_LINE INDENT print ( i , " ^ 2 β + β " , j , " ^ 2" ) NEW_LINE return True NEW_LINE DEDENT j = j + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT return False NEW_LINE DEDENT n = 25 NEW_LINE if ( sumSquare ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Queries to count minimum flips required to fill a binary submatrix with 0 s only | Python3 program for the above approach ; Function to compute the matrix prefixCnt [ M ] [ N ] from mat [ M ] [ N ] such that prefixCnt [ i ] [ j ] stores the count of 0 's from (0, 0) to (i, j) ; Initialize prefixCnt [ i ] [ j ] with 1 if mat [ i ] [ j ] is 0 ; Otherwise , assign with 0 ; Calculate prefix sum for each row ; Calculate prefix sum for each column ; Function to compute count of 0 's in submatrix from (pi, pj) to (qi, qj) from prefixCnt[M][N] ; Initialize that count of 0 's in the sub-matrix within indices (0, 0) to (qi, qj) ; Subtract count of 0 's within indices (0, 0) and (pi-1, qj) ; Subtract count of 0 's within indices (0, 0) and (qi, pj-1) ; Add prefixCnt [ pi - 1 ] [ pj - 1 ] because its value has been added once but subtracted twice ; Function to count the 0 s in the each given submatrix ; Stores the prefix sum of each row and column ; Compute matrix prefixCnt [ ] [ ] ; Function Call for each query ; Driver Code ; Given matrix ; Function Call | M = 6 NEW_LINE N = 7 NEW_LINE def preCompute ( mat , prefixCnt ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 0 ) : NEW_LINE INDENT prefixCnt [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT prefixCnt [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( 1 , N ) : NEW_LINE INDENT prefixCnt [ i ] [ j ] += prefixCnt [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 1 , M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT prefixCnt [ i ] [ j ] += prefixCnt [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT return prefixCnt NEW_LINE DEDENT def countQuery ( prefixCnt , pi , pj , qi , qj ) : NEW_LINE INDENT cnt = prefixCnt [ qi ] [ qj ] NEW_LINE if ( pi > 0 ) : NEW_LINE INDENT cnt -= prefixCnt [ pi - 1 ] [ qj ] NEW_LINE DEDENT if ( pj > 0 ) : NEW_LINE INDENT cnt -= prefixCnt [ qi ] [ pj - 1 ] NEW_LINE DEDENT if ( pi > 0 and pj > 0 ) : NEW_LINE INDENT cnt += prefixCnt [ pi - 1 ] [ pj - 1 ] NEW_LINE DEDENT return cnt NEW_LINE DEDENT def count0s ( mat , Q , sizeQ ) : NEW_LINE INDENT prefixCnt = [ [ 0 for i in range ( N ) ] for i in range ( M ) ] NEW_LINE prefixCnt = preCompute ( mat , prefixCnt ) NEW_LINE for i in range ( sizeQ ) : NEW_LINE INDENT print ( countQuery ( prefixCnt , Q [ i ] [ 0 ] , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , Q [ i ] [ 3 ] ) , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 0 , 1 , 0 , 1 , 1 , 1 , 0 ] , [ 1 , 0 , 1 , 1 , 1 , 0 , 1 ] , [ 1 , 1 , 0 , 0 , 1 , 1 , 0 ] , [ 1 , 1 , 1 , 1 , 1 , 0 , 1 ] , [ 0 , 0 , 1 , 0 , 1 , 1 , 1 ] , [ 1 , 1 , 0 , 1 , 1 , 0 , 1 ] ] NEW_LINE Q = [ [ 0 , 1 , 3 , 2 ] , [ 2 , 2 , 4 , 5 ] , [ 4 , 3 , 5 , 6 ] ] NEW_LINE sizeQ = len ( Q ) NEW_LINE count0s ( mat , Q , sizeQ ) NEW_LINE DEDENT |
Smallest root of the equation x ^ 2 + s ( x ) * x | Python3 program to find smallest value of root of an equation under given constraints . ; function to check if the sum of digits is equal to the summation assumed ; calculate the sum of digit ; function to find the largest root possible . ; iterate for all possible sum of digits . ; check if discriminent is a perfect square . ; check if discriminent is a perfect square and if it as perefect root of the equation ; function returns answer ; Driver Code | import math NEW_LINE def check ( a , b ) : NEW_LINE INDENT c = 0 ; NEW_LINE while ( a != 0 ) : NEW_LINE INDENT c = c + a % 10 ; NEW_LINE a = int ( a / 10 ) ; NEW_LINE DEDENT return True if ( c == b ) else False ; NEW_LINE DEDENT def root ( n ) : NEW_LINE INDENT found = False ; NEW_LINE mx = 1000000000000000001 ; NEW_LINE for i in range ( 91 ) : NEW_LINE INDENT s = i * i + 4 * n ; NEW_LINE sq = int ( math . sqrt ( s ) ) ; NEW_LINE if ( sq * sq == s and check ( int ( ( sq - i ) / 2 ) , i ) ) : NEW_LINE INDENT found = True ; NEW_LINE mx = min ( mx , int ( ( sq - i ) / 2 ) ) ; NEW_LINE DEDENT DEDENT if ( found ) : NEW_LINE INDENT return mx ; NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT n = 110 ; NEW_LINE print ( root ( n ) ) ; NEW_LINE |
Sum of digits of a given number to a given power | Function to calculate sum ; Driver Code | def calculate ( n , power ) : NEW_LINE INDENT return sum ( [ int ( i ) for i in str ( pow ( n , power ) ) ] ) NEW_LINE DEDENT n = 5 NEW_LINE power = 4 NEW_LINE print ( calculate ( n , power ) ) NEW_LINE |
Co | Python3 program to represent a number as sum of a co - prime pair such that difference between them is minimum ; function to check if pair is co - prime or not ; function to find and print co - prime pair ; Driver code | import math NEW_LINE def coprime ( a , b ) : NEW_LINE INDENT return 1 if ( math . gcd ( a , b ) == 1 ) else 0 ; NEW_LINE DEDENT def pairSum ( n ) : NEW_LINE INDENT mid = int ( n / 2 ) ; NEW_LINE i = mid ; NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT if ( coprime ( i , n - i ) == 1 ) : NEW_LINE INDENT print ( i , n - i ) ; NEW_LINE break ; NEW_LINE DEDENT i = i - 1 ; NEW_LINE DEDENT DEDENT n = 11 ; NEW_LINE pairSum ( n ) ; NEW_LINE |
Program for quotient and remainder of big number | Function to calculate the modulus ; Store the modulus of big number ; Do step by step division ; Update modulo by concatenating current digit . ; Update quotient ; Update mod for next iteration . ; Flag used to remove starting zeros ; Driver Code | def modBigNumber ( num , m ) : NEW_LINE INDENT vec = [ ] NEW_LINE mod = 0 NEW_LINE for i in range ( 0 , len ( num ) , 1 ) : NEW_LINE INDENT digit = ord ( num [ i ] ) - ord ( '0' ) NEW_LINE mod = mod * 10 + digit NEW_LINE quo = int ( mod / m ) NEW_LINE vec . append ( quo ) NEW_LINE mod = mod % m NEW_LINE DEDENT print ( " Remainder β : " , mod ) NEW_LINE print ( " Quotient β : " , end = " β " ) NEW_LINE zeroflag = 0 ; NEW_LINE for i in range ( 0 , len ( vec ) , 1 ) : NEW_LINE INDENT if ( vec [ i ] == 0 and zeroflag == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT zeroflag = 1 NEW_LINE print ( vec [ i ] , end = " " ) NEW_LINE DEDENT return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num = "14598499948265358486" NEW_LINE m = 487 NEW_LINE modBigNumber ( num , m ) NEW_LINE DEDENT |
Queries to find whether a number has exactly four distinct factors or not | Initialize global variable according to given condition so that it can be accessible to all function ; Function to calculate all number having four distinct factors ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Initialize prime [ ] array which will contain all the primes from 1 - N ; Iterate over all the prime numbers ; Mark cube root of prime numbers ; Mark product of prime numbers ; Driver Code | N = 1000001 ; NEW_LINE fourDiv = [ False ] * ( N + 1 ) ; NEW_LINE def fourDistinctFactors ( ) : NEW_LINE INDENT primeAll = [ True ] * ( N + 1 ) ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= N ) : NEW_LINE INDENT if ( primeAll [ p ] == True ) : NEW_LINE INDENT i = p * 2 ; NEW_LINE while ( i <= N ) : NEW_LINE INDENT primeAll [ i ] = False ; NEW_LINE i += p ; NEW_LINE DEDENT DEDENT p += 1 ; NEW_LINE DEDENT prime = [ ] ; NEW_LINE for p in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( primeAll [ p ] ) : NEW_LINE INDENT prime . append ( p ) ; NEW_LINE DEDENT DEDENT for i in range ( len ( prime ) ) : NEW_LINE INDENT p = prime [ i ] ; NEW_LINE if ( 1 * p * p * p <= N ) : NEW_LINE INDENT fourDiv [ p * p * p ] = True ; NEW_LINE DEDENT for j in range ( i + 1 , len ( prime ) ) : NEW_LINE INDENT q = prime [ j ] ; NEW_LINE if ( 1 * p * q > N ) : NEW_LINE INDENT break ; NEW_LINE DEDENT fourDiv [ p * q ] = True ; NEW_LINE DEDENT DEDENT DEDENT fourDistinctFactors ( ) ; NEW_LINE num = 10 ; NEW_LINE if ( fourDiv [ num ] ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT num = 12 ; NEW_LINE if ( fourDiv [ num ] ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Leonardo Number | A simple recursive program to find n - th leonardo number . ; Driver code | def leonardo ( n ) : NEW_LINE INDENT dp = [ ] ; NEW_LINE dp . append ( 1 ) ; NEW_LINE dp . append ( 1 ) ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp . append ( dp [ i - 1 ] + dp [ i - 2 ] + 1 ) ; NEW_LINE DEDENT return dp [ n ] ; NEW_LINE DEDENT print ( leonardo ( 3 ) ) ; NEW_LINE |
Cholesky Decomposition : Matrix Decomposition | Python3 program to decompose a matrix using Cholesky Decomposition ; Decomposing a matrix into Lower Triangular ; summation for diagonals ; Evaluating L ( i , j ) using L ( j , j ) ; Displaying Lower Triangular and its Transpose ; Lower Triangular ; Transpose of Lower Triangular ; Driver Code | import math NEW_LINE MAX = 100 ; NEW_LINE def Cholesky_Decomposition ( matrix , n ) : NEW_LINE INDENT lower = [ [ 0 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT sum1 = 0 ; NEW_LINE if ( j == i ) : NEW_LINE INDENT for k in range ( j ) : NEW_LINE INDENT sum1 += pow ( lower [ j ] [ k ] , 2 ) ; NEW_LINE DEDENT lower [ j ] [ j ] = int ( math . sqrt ( matrix [ j ] [ j ] - sum1 ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT for k in range ( j ) : NEW_LINE INDENT sum1 += ( lower [ i ] [ k ] * lower [ j ] [ k ] ) ; NEW_LINE DEDENT if ( lower [ j ] [ j ] > 0 ) : NEW_LINE INDENT lower [ i ] [ j ] = int ( ( matrix [ i ] [ j ] - sum1 ) / lower [ j ] [ j ] ) ; NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( " Lower β Triangular TABSYMBOL TABSYMBOL Transpose " ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( lower [ i ] [ j ] , end = " TABSYMBOL " ) ; NEW_LINE DEDENT print ( " " , end = " TABSYMBOL " ) ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT print ( lower [ j ] [ i ] , end = " TABSYMBOL " ) ; NEW_LINE DEDENT print ( " " ) ; NEW_LINE DEDENT DEDENT n = 3 ; NEW_LINE matrix = [ [ 4 , 12 , - 16 ] , [ 12 , 37 , - 43 ] , [ - 16 , - 43 , 98 ] ] ; NEW_LINE Cholesky_Decomposition ( matrix , n ) ; NEW_LINE |
Program for sum of arithmetic series | Python3 Efficient solution to find sum of arithmetic series . ; Driver code | def sumOfAP ( a , d , n ) : NEW_LINE INDENT sum = ( n / 2 ) * ( 2 * a + ( n - 1 ) * d ) NEW_LINE return sum NEW_LINE DEDENT n = 20 NEW_LINE a = 2.5 NEW_LINE d = 1.5 NEW_LINE print ( sumOfAP ( a , d , n ) ) NEW_LINE |
Program for cube sum of first n natural numbers | Returns the sum of series ; Driver Function | def sumOfSeries ( n ) : NEW_LINE INDENT x = 0 NEW_LINE if n % 2 == 0 : NEW_LINE INDENT x = ( n / 2 ) * ( n + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT x = ( ( n + 1 ) / 2 ) * n NEW_LINE DEDENT return ( int ) ( x * x ) NEW_LINE DEDENT n = 5 NEW_LINE print ( sumOfSeries ( n ) ) NEW_LINE |
Maximum value of | arr [ i ] | Return maximum value of | arr [ i ] - arr [ j ] | + | i - j | ; Iterating two for loop , one for i and another for j . ; Evaluating | arr [ i ] - arr [ j ] | + | i - j | and compare with previous maximum . ; Driver Code | def findValue ( arr , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT ans = ans if ans > ( abs ( arr [ i ] - arr [ j ] ) + abs ( i - j ) ) else ( abs ( arr [ i ] - arr [ j ] ) + abs ( i - j ) ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findValue ( arr , n ) ) ; NEW_LINE |
Maximum value of | arr [ i ] | Return maximum | arr [ i ] - arr [ j ] | + | i - j | ; Calculating first_array and second_array ; Finding maximum and minimum value in first_array ; Storing the difference between maximum and minimum value in first_array ; Finding maximum and minimum value in second_array ; Storing the difference between maximum and minimum value in second_array ; Driver Code | def findValue ( arr , n ) : NEW_LINE INDENT a = [ ] NEW_LINE b = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT a . append ( arr [ i ] + i ) NEW_LINE b . append ( arr [ i ] - i ) NEW_LINE DEDENT x = a [ 0 ] NEW_LINE y = a [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > x ) : NEW_LINE INDENT x = a [ i ] NEW_LINE DEDENT if ( a [ i ] < y ) : NEW_LINE INDENT y = a [ i ] NEW_LINE DEDENT DEDENT ans1 = ( x - y ) NEW_LINE x = b [ 0 ] NEW_LINE y = b [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( b [ i ] > x ) : NEW_LINE INDENT x = b [ i ] NEW_LINE DEDENT if ( b [ i ] < y ) : NEW_LINE INDENT y = b [ i ] NEW_LINE DEDENT DEDENT ans2 = ( x - y ) NEW_LINE return max ( ans1 , ans2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findValue ( arr , n ) ) NEW_LINE DEDENT |
Number of subarrays having product less than K | Python3 program to count subarrays having product less than k . ; Counter for single element ; Multiple subarray ; If this multiple is less than k , then increment ; Driver Code | def countsubarray ( array , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if array [ i ] < k : NEW_LINE INDENT count += 1 NEW_LINE DEDENT mul = array [ i ] NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT mul = mul * array [ j ] NEW_LINE if mul < k : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT array = [ 1 , 2 , 3 , 4 ] NEW_LINE k = 10 NEW_LINE size = len ( array ) NEW_LINE count = countsubarray ( array , size , k ) NEW_LINE print ( count , end = " β " ) NEW_LINE |
Perfect Cube factors of a Number | Function that returns the count of factors that are perfect cube ; To store the count of number of times a prime number divides N ; To store the count of factors that are perfect cube ; Count number of 2 's that divides N ; Calculate ans according to above formula ; Check for all possible numbers that can divide it ; Loop to check the number of times prime number i divides it ; Calculate ans according to above formula ; ; Given number ; Function call | def noofFactors ( N ) : NEW_LINE INDENT if N == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT count = 0 NEW_LINE ans = 1 NEW_LINE while ( N % 2 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE N //= 2 NEW_LINE DEDENT ans *= ( ( count // 3 ) + 1 ) NEW_LINE i = 3 NEW_LINE while ( ( i * i ) <= N ) : NEW_LINE INDENT count = 0 NEW_LINE while ( N % i == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE N //= i NEW_LINE DEDENT ans *= ( ( count // 3 ) + 1 ) NEW_LINE i += 2 NEW_LINE DEDENT DEDENT / * Return final count * / NEW_LINE INDENT return ans NEW_LINE DEDENT N = 216 NEW_LINE print ( noofFactors ( N ) ) NEW_LINE |
Efficient program to print the number of factors of n numbers | Python3 program to count number of factors of an array of integers ; function to generate all prime factors of numbers from 1 to 10 ^ 6 ; Initializes all the positions with their value . ; Initializes all multiples of 2 with 2 ; A modified version of Sieve of Eratosthenes to store the smallest prime factor that divides every number . ; check if it has no prime factor . ; Initializes of j starting from i * i ; if it has no prime factor before , then stores the smallest prime divisor ; function to calculate number of factors ; stores the smallest prime number that divides n ; stores the count of number of times a prime number divides n . ; reduces to the next number after prime factorization of n ; false when prime factorization is done ; if the same prime number is dividing n , then we increase the count ; if its a new prime factor that is factorizing n , then we again set c = 1 and change dup to the new prime factor , and apply the formula explained above . ; prime factorizes a number ; for the last prime factor ; Driver Code ; generate prime factors of number upto 10 ^ 6 | MAX = 1000001 ; NEW_LINE factor = [ 0 ] * ( MAX + 1 ) ; NEW_LINE def generatePrimeFactors ( ) : NEW_LINE INDENT factor [ 1 ] = 1 ; NEW_LINE for i in range ( 2 , MAX ) : NEW_LINE INDENT factor [ i ] = i ; NEW_LINE DEDENT for i in range ( 4 , MAX , 2 ) : NEW_LINE INDENT factor [ i ] = 2 ; NEW_LINE DEDENT i = 3 ; NEW_LINE while ( i * i < MAX ) : NEW_LINE INDENT if ( factor [ i ] == i ) : NEW_LINE INDENT j = i * i ; NEW_LINE while ( j < MAX ) : NEW_LINE INDENT if ( factor [ j ] == j ) : NEW_LINE INDENT factor [ j ] = i ; NEW_LINE DEDENT j += i ; NEW_LINE DEDENT DEDENT i += 1 ; NEW_LINE DEDENT DEDENT def calculateNoOFactors ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT ans = 1 ; NEW_LINE dup = factor [ n ] ; NEW_LINE c = 1 ; NEW_LINE j = int ( n / factor [ n ] ) ; NEW_LINE while ( j > 1 ) : NEW_LINE INDENT if ( factor [ j ] == dup ) : NEW_LINE INDENT c += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT dup = factor [ j ] ; NEW_LINE ans = ans * ( c + 1 ) ; NEW_LINE c = 1 ; NEW_LINE DEDENT j = int ( j / factor [ j ] ) ; NEW_LINE DEDENT ans = ans * ( c + 1 ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT generatePrimeFactors ( ) NEW_LINE a = [ 10 , 30 , 100 , 450 , 987 ] NEW_LINE q = len ( a ) NEW_LINE for i in range ( 0 , q ) : NEW_LINE INDENT print ( calculateNoOFactors ( a [ i ] ) , end = " β " ) NEW_LINE DEDENT DEDENT |
Digit | function to produce and print Digit Product Sequence ; Array which store sequence ; Temporary variable to store product ; Initialize first element of the array with 1 ; Run a loop from 1 to N . Check if previous number is single digit or not . If yes then product = 1 else take modulus . Then again check if previous number is single digit or not if yes then store previous number , else store its first value Then for every i store value in the array . ; Print sequence ; Value of N ; Calling function | def digit_product_Sum ( N ) : NEW_LINE INDENT a = [ 0 ] * ( N + 1 ) ; NEW_LINE product = 1 ; NEW_LINE a [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT product = int ( a [ i - 1 ] / 10 ) ; NEW_LINE if ( product == 0 ) : NEW_LINE INDENT product = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT product = a [ i - 1 ] % 10 ; NEW_LINE DEDENT val = int ( a [ i - 1 ] / 10 ) ; NEW_LINE if ( val == 0 ) : NEW_LINE INDENT val = a [ i - 1 ] ; NEW_LINE DEDENT a [ i ] = a [ i - 1 ] + ( val * product ) ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT N = 10 ; NEW_LINE digit_product_Sum ( N ) ; NEW_LINE |
Geometric mean ( Two Methods ) | Python Program to calculate the geometric mean of the given array elements . ; function to calculate geometric mean and return float value . ; declare product variable and initialize it to 1. ; Compute the product of all the elements in the array . ; compute geometric mean through formula pow ( product , 1 / n ) and return the value to main function . ; Driver function | import math NEW_LINE def geometricMean ( arr , n ) : NEW_LINE INDENT product = 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT product = product * arr [ i ] NEW_LINE DEDENT gm = ( float ) ( math . pow ( product , ( 1 / n ) ) ) NEW_LINE return ( float ) ( gm ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( ' { 0 : . 6f } ' . format ( geometricMean ( arr , n ) ) ) NEW_LINE |
Check whether a number can be expressed as a product of single digit numbers | Number of single digit prime numbers ; function to check whether a number can be expressed as a product of single digit numbers ; if ' n ' is a single digit number , then it can be expressed ; define single digit prime numbers array ; repeatedly divide ' n ' by the given prime numbers until all the numbers are used or ' n ' > 1 ; if true , then ' n ' can be expressed ; Driver code | SIZE = 4 NEW_LINE def productOfSingelDgt ( n ) : NEW_LINE INDENT if n >= 0 and n <= 9 : NEW_LINE INDENT return True NEW_LINE DEDENT prime = [ 2 , 3 , 5 , 7 ] NEW_LINE i = 0 NEW_LINE while i < SIZE and n > 1 : NEW_LINE INDENT while n % prime [ i ] == 0 : NEW_LINE INDENT n = n / prime [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return n == 1 NEW_LINE DEDENT n = 24 NEW_LINE if productOfSingelDgt ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Program to find sum of first n natural numbers | Returns sum of first n natural numbers ; Driver code | def findSum ( n ) : NEW_LINE INDENT return n * ( n + 1 ) / 2 NEW_LINE DEDENT n = 5 NEW_LINE print findSum ( n ) NEW_LINE |
Program to find sum of first n natural numbers | Returns sum of first n natural numbers ; If n is odd , ( n + 1 ) must be even ; Driver code | def findSum ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return ( n / 2 ) * ( n + 1 ) NEW_LINE DEDENT else : NEW_LINE return ( ( n + 1 ) / 2 ) * n NEW_LINE DEDENT n = 5 NEW_LINE print findSum ( n ) NEW_LINE |
Maximum number of unique prime factors | Return maximum number of prime factors for any number in [ 1 , N ] ; Based on Sieve of Eratosthenes ; If p is prime ; We simply multiply first set of prime numbers while the product is smaller than N . ; Driver Code | def maxPrimefactorNum ( N ) : NEW_LINE INDENT if ( N < 2 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT arr = [ True ] * ( N + 1 ) ; NEW_LINE prod = 1 ; NEW_LINE res = 0 ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= N ) : NEW_LINE INDENT if ( arr [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , N + 1 , p ) : NEW_LINE INDENT arr [ i ] = False ; NEW_LINE DEDENT prod *= p ; NEW_LINE if ( prod > N ) : NEW_LINE INDENT return res ; NEW_LINE DEDENT res += 1 ; NEW_LINE DEDENT p += 1 ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT N = 500 ; NEW_LINE print ( maxPrimefactorNum ( N ) ) ; NEW_LINE |
To check a number is palindrome or not without using any extra space | Function to check if given number is palindrome or not without using the extra space ; Find the appropriate divisor to extract the leading digit ; If first and last digit not same return false ; Removing the leading and trailing digit from number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Driver code | def isPalindrome ( n ) : NEW_LINE INDENT divisor = 1 NEW_LINE while ( n / divisor >= 10 ) : NEW_LINE INDENT divisor *= 10 NEW_LINE DEDENT while ( n != 0 ) : NEW_LINE INDENT leading = n // divisor NEW_LINE trailing = n % 10 NEW_LINE if ( leading != trailing ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = ( n % divisor ) // 10 NEW_LINE divisor = divisor / 100 NEW_LINE DEDENT return True NEW_LINE DEDENT if ( isPalindrome ( 1001 ) ) : NEW_LINE INDENT print ( ' Yes , β it β is β palindrome ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No , β not β palindrome ' ) NEW_LINE DEDENT |
Find whether a given integer is a power of 3 or not | Returns true if n is power of 3 , else false ; The maximum power of 3 value that integer can hold is 1162261467 ( 3 ^ 19 ) . ; Driver code | def check ( n ) : NEW_LINE INDENT return 1162261467 % n == 0 NEW_LINE DEDENT n = 9 NEW_LINE if ( check ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Demlo number ( Square of 11. . .1 ) | To return demlo number Length of s is smaller than 10 ; Add numbers to res upto size of s then add in reverse ; Driver Code | def printDemlo ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE res = " " NEW_LINE for i in range ( 1 , l + 1 ) : NEW_LINE INDENT res = res + str ( i ) NEW_LINE DEDENT for i in range ( l - 1 , 0 , - 1 ) : NEW_LINE INDENT res = res + str ( i ) NEW_LINE DEDENT return res NEW_LINE DEDENT s = "111111" NEW_LINE print printDemlo ( s ) NEW_LINE |
Number of times a number can be replaced by the sum of its digits until it only contains one digit | Python 3 program to count number of times we need to add digits to get a single digit . ; Here the count variable store how many times we do sum of digits and temporary_sum always store the temporary sum we get at each iteration . ; In this loop we always compute the sum of digits in temporary_ sum variable and convert it into string str till its length become 1 and increase the count in each iteration . ; computing sum of its digits ; converting temporary_sum into string str again . ; increase the count ; Driver Code | def NumberofTimes ( s ) : NEW_LINE INDENT temporary_sum = 0 NEW_LINE count = 0 NEW_LINE while ( len ( s ) > 1 ) : NEW_LINE INDENT temporary_sum = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT temporary_sum += ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT s = str ( temporary_sum ) NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "991" NEW_LINE print ( NumberofTimes ( s ) ) NEW_LINE DEDENT |
Climb n | Function to calculate leaps ; Driver code | def calculateLeaps ( n ) : NEW_LINE INDENT if n == 0 or n == 1 : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT leaps = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT leaps = leaps + calculateLeaps ( i ) ; NEW_LINE DEDENT return leaps ; NEW_LINE DEDENT DEDENT print ( calculateLeaps ( 4 ) ) ; NEW_LINE |
Print last k digits of a ^ b ( a raised to power b ) | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; 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 calculate number of digits in x ; function to print last k digits of a ^ b ; Generating 10 ^ k ; Calling modular exponentiation ; Printing leftmost zeros . Since ( a ^ b ) % k can have digits less then k . In that case we need to print zeros ; If temp is not zero then print temp If temp is zero then already printed ; Driver Code | def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE 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 numberOfDigits ( x ) : NEW_LINE INDENT i = 0 NEW_LINE while ( x ) : NEW_LINE INDENT x //= 10 NEW_LINE i += 1 NEW_LINE DEDENT return i NEW_LINE DEDENT def printLastKDigits ( a , b , k ) : NEW_LINE INDENT print ( " Last β " + str ( k ) + " β digits β of β " + str ( a ) + " ^ " + str ( b ) , end = " β = β " ) NEW_LINE temp = 1 NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT temp *= 10 NEW_LINE DEDENT temp = power ( a , b , temp ) NEW_LINE for i in range ( k - numberOfDigits ( temp ) ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT if ( temp ) : NEW_LINE INDENT print ( temp ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 11 NEW_LINE b = 3 NEW_LINE k = 2 NEW_LINE printLastKDigits ( a , b , k ) NEW_LINE DEDENT |
Adam Number | To reverse Digits of numbers ; To square number ; To check Adam Number ; Square first number and square reverse digits of second number ; If reverse of b equals a then given number is Adam number ; Driver program to test above functions | def reverseDigits ( num ) : NEW_LINE INDENT rev = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT rev = rev * 10 + num % 10 NEW_LINE num /= 10 NEW_LINE DEDENT return rev NEW_LINE DEDENT def square ( num ) : NEW_LINE INDENT return ( num * num ) NEW_LINE DEDENT def checkAdamNumber ( num ) : NEW_LINE INDENT a = square ( num ) NEW_LINE b = square ( reverseDigits ( num ) ) NEW_LINE if ( a == reverseDigits ( b ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT num = 13 NEW_LINE if ( checkAdamNumber ( num ) ) : NEW_LINE INDENT print " Adam β Number " NEW_LINE DEDENT else : NEW_LINE INDENT print " Not β a β Adam β Number " NEW_LINE DEDENT |
Compute the parity of a number using XOR and table look | Generating the look - up table while pre - processing ; LOOK_UP is the macro expansion to generate the table ; Function to find the parity ; Number is considered to be of 32 bits ; Dividing the number o 8 - bit chunks while performing X - OR ; Masking the number with 0xff ( 11111111 ) to produce valid 8 - bit result ; Driver code ; Result is 1 for odd parity , 0 for even parity ; Printing the desired result | def P2 ( n , table ) : NEW_LINE INDENT table . extend ( [ n , n ^ 1 , n ^ 1 , n ] ) NEW_LINE DEDENT def P4 ( n , table ) : NEW_LINE INDENT return ( P2 ( n , table ) , P2 ( n ^ 1 , table ) , P2 ( n ^ 1 , table ) , P2 ( n , table ) ) NEW_LINE DEDENT def P6 ( n , table ) : NEW_LINE INDENT return ( P4 ( n , table ) , P4 ( n ^ 1 , table ) , P4 ( n ^ 1 , table ) , P4 ( n , table ) ) NEW_LINE DEDENT def LOOK_UP ( table ) : NEW_LINE INDENT return ( P6 ( 0 , table ) , P6 ( 1 , table ) , P6 ( 1 , table ) , P6 ( 0 , table ) ) NEW_LINE DEDENT table = [ 0 ] * 256 NEW_LINE LOOK_UP ( table ) NEW_LINE def Parity ( num ) : NEW_LINE INDENT max = 16 NEW_LINE while ( max >= 8 ) : NEW_LINE INDENT num = num ^ ( num >> max ) NEW_LINE max = max // 2 NEW_LINE DEDENT return table [ num & 0xff ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT num = 1742346774 NEW_LINE result = Parity ( num ) NEW_LINE print ( " Odd β Parity " ) if result else print ( " Even β Parity " ) NEW_LINE DEDENT |
Count total number of digits from 1 to n | Python3 program to count total number of digits we have to write from 1 to n ; number_of_digits store total digits we have to write ; In the loop we are decreasing 0 , 9 , 99 ... from n till ( n - i + 1 ) is greater than 0 and sum them to number_of_digits to get the required sum ; Driver code | def totalDigits ( n ) : NEW_LINE INDENT number_of_digits = 0 ; NEW_LINE for i in range ( 1 , n , 10 ) : NEW_LINE INDENT number_of_digits = ( number_of_digits + ( n - i + 1 ) ) ; NEW_LINE DEDENT return number_of_digits ; NEW_LINE DEDENT n = 13 ; NEW_LINE s = totalDigits ( n ) + 1 ; NEW_LINE print ( s ) ; NEW_LINE |
Numbers with exactly 3 divisors | Generates all primes upto n and prints their squares ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; print squares of primes upto n . ; Driver program | def numbersWith3Divisors ( n ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) ; NEW_LINE prime [ 0 ] = prime [ 1 ] = False ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT p += 1 ; NEW_LINE DEDENT print ( " Numbers β with β 3 β divisors β : " ) ; NEW_LINE i = 0 ; NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT print ( i * i , end = " β " ) ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT DEDENT n = 96 ; NEW_LINE numbersWith3Divisors ( n ) ; NEW_LINE |
Program for decimal to hexadecimal conversion | function to convert decimal to hexadecimal ; char array to store hexadecimal number ; counter for hexadecimal number array ; temporary variable to store remainder ; storing remainder in temp variable . ; check if temp < 10 ; printing hexadecimal number array in reverse order ; Driver Code | def decToHexa ( n ) : NEW_LINE INDENT hexaDeciNum = [ '0' ] * 100 NEW_LINE i = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT temp = 0 NEW_LINE temp = n % 16 NEW_LINE if ( temp < 10 ) : NEW_LINE INDENT hexaDeciNum [ i ] = chr ( temp + 48 ) NEW_LINE i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT hexaDeciNum [ i ] = chr ( temp + 55 ) NEW_LINE i = i + 1 NEW_LINE DEDENT n = int ( n / 16 ) NEW_LINE DEDENT j = i - 1 NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT print ( ( hexaDeciNum [ j ] ) , end = " " ) NEW_LINE j = j - 1 NEW_LINE DEDENT DEDENT n = 2545 NEW_LINE decToHexa ( n ) NEW_LINE |
Program for Decimal to Binary Conversion | function to convert decimal to binary ; array to store binary number ; counter for binary array ; storing remainder in binary array ; printing binary array in reverse order ; Driver Code | def decToBinary ( n ) : NEW_LINE INDENT binaryNum = [ 0 ] * n ; NEW_LINE i = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT binaryNum [ i ] = n % 2 ; NEW_LINE n = int ( n / 2 ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( binaryNum [ j ] , end = " " ) ; NEW_LINE DEDENT DEDENT n = 17 ; NEW_LINE decToBinary ( n ) ; NEW_LINE |
Break the number into three parts | Function to count number of ways to make the given number n ; Driver code | def count_of_ways ( n ) : NEW_LINE INDENT count = 0 NEW_LINE count = ( n + 1 ) * ( n + 2 ) // 2 NEW_LINE return count NEW_LINE DEDENT n = 3 NEW_LINE print ( count_of_ways ( n ) ) NEW_LINE |
Implement * , | Function to flip the sign using only " + " operator ( It is simple with ' * ' allowed . We need to do a = ( - 1 ) * a ; If sign is + ve turn it - ve and vice - versa ; Check if a and b are of different signs ; Function to subtract two numbers by negating b and adding them ; Negating b ; Function to multiply a by b by adding a to itself b times ; because algo is faster if b < a ; Adding a to itself b times ; Check if final sign must be - ve or + ve ; Function to divide a by b by counting how many times ' b ' can be subtracted from ' a ' before getting 0 ; Negating b to subtract from a ; Subtracting divisor from dividend ; Check if a and b are of similar symbols or not ; Driver code | def flipSign ( a ) : NEW_LINE INDENT neg = 0 ; NEW_LINE tmp = 1 if a < 0 else - 1 ; NEW_LINE while ( a != 0 ) : NEW_LINE INDENT neg += tmp ; NEW_LINE a += tmp ; NEW_LINE DEDENT return neg ; NEW_LINE DEDENT def areDifferentSign ( a , b ) : NEW_LINE INDENT return ( ( a < 0 and b > 0 ) or ( a > 0 and b < 0 ) ) ; NEW_LINE DEDENT def sub ( a , b ) : NEW_LINE INDENT return a + flipSign ( b ) ; NEW_LINE DEDENT def mul ( a , b ) : NEW_LINE INDENT if ( a < b ) : NEW_LINE INDENT return mul ( b , a ) ; NEW_LINE DEDENT sum = 0 ; NEW_LINE for i in range ( abs ( b ) , 0 , - 1 ) : NEW_LINE INDENT sum += a ; NEW_LINE DEDENT if ( b < 0 ) : NEW_LINE INDENT sum = flipSign ( sum ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def division ( a , b ) : NEW_LINE INDENT quotient = 0 ; NEW_LINE divisor = flipSign ( abs ( b ) ) ; NEW_LINE for dividend in range ( abs ( a ) , abs ( divisor ) + divisor , divisor ) : NEW_LINE INDENT quotient += 1 ; NEW_LINE DEDENT if ( areDifferentSign ( a , b ) ) : NEW_LINE INDENT quotient = flipSign ( quotient ) ; NEW_LINE DEDENT return quotient ; NEW_LINE DEDENT print ( " Subtraction β is " , sub ( 4 , - 2 ) ) ; NEW_LINE print ( " Product β is " , mul ( - 9 , 6 ) ) ; NEW_LINE a , b = 8 , 2 ; NEW_LINE if ( b ) : NEW_LINE INDENT print ( " Division β is " , division ( a , b ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Exception β : - β Divide β by β 0" ) ; NEW_LINE DEDENT |
Number of Groups of Sizes Two Or Three Divisible By 3 | Program to find groups of 2 or 3 whose sum is divisible by 3 ; Initialize groups to 0 ; Increment group with specified remainder ; Return groups using the formula ; Driver code | def numOfCombinations ( arr , N ) : NEW_LINE INDENT C = [ 0 , 0 , 0 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT C [ arr [ i ] % 3 ] = C [ arr [ i ] % 3 ] + 1 NEW_LINE DEDENT return ( C [ 1 ] * C [ 2 ] + C [ 0 ] * ( C [ 0 ] - 1 ) / 2 + C [ 0 ] * ( C [ 0 ] - 1 ) * ( C [ 0 ] - 2 ) / 6 + C [ 1 ] * ( C [ 1 ] - 1 ) * ( C [ 1 ] - 2 ) / 6 + C [ 2 ] * ( C [ 2 ] - 1 ) * ( C [ 2 ] - 2 ) / 6 + C [ 0 ] * C [ 1 ] * C [ 2 ] ) NEW_LINE DEDENT arr1 = [ 1 , 5 , 7 , 2 , 9 , 14 ] NEW_LINE print ( int ( numOfCombinations ( arr1 , 6 ) ) ) NEW_LINE arr2 = [ 3 , 6 , 9 , 12 ] NEW_LINE print ( int ( numOfCombinations ( arr2 , 4 ) ) ) NEW_LINE |
Check if a number can be written as a sum of ' k ' prime numbers | Checking if a number is prime or not ; check for numbers from 2 to sqrt ( x ) if it is divisible return false ; Returns true if N can be written as sum of K primes ; N < 2 K directly return false ; If K = 1 return value depends on primality of N ; if N is even directly return true ; ; If N is odd , then one prime must be 2. All other primes are odd and cannot have a pair sum as even . ; If K >= 3 return true ; ; Driver function | def isprime ( x ) : NEW_LINE INDENT i = 2 NEW_LINE while ( i * i <= x ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def isSumOfKprimes ( N , K ) : NEW_LINE INDENT if ( N < 2 * K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( K == 1 ) : NEW_LINE INDENT return isprime ( N ) NEW_LINE DEDENT if ( K == 2 ) : NEW_LINE INDENT if ( N % 2 == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return isprime ( N - 2 ) NEW_LINE DEDENT return 1 NEW_LINE DEDENT n = 15 NEW_LINE k = 2 NEW_LINE if ( isSumOfKprimes ( n , k ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Count total divisors of A or B in a given range | Utility function to find GCD of two numbers ; Utility function to find LCM of two numbers ; Function to calculate all divisors in given range ; Find LCM of a and b ; Find common divisor by using LCM ; Driver code | def __gcd ( x , y ) : NEW_LINE INDENT if x > y : NEW_LINE INDENT small = y NEW_LINE DEDENT else : NEW_LINE INDENT small = x NEW_LINE DEDENT for i in range ( 1 , small + 1 ) : NEW_LINE INDENT if ( ( x % i == 0 ) and ( y % i == 0 ) ) : NEW_LINE INDENT gcd = i NEW_LINE DEDENT DEDENT return gcd NEW_LINE DEDENT def FindLCM ( a , b ) : NEW_LINE INDENT return ( a * b ) / __gcd ( a , b ) ; NEW_LINE DEDENT def rangeDivisor ( m , n , a , b ) : NEW_LINE INDENT lcm = FindLCM ( a , b ) NEW_LINE a_divisor = int ( n / a - ( m - 1 ) / a ) NEW_LINE b_divisor = int ( n / b - ( m - 1 ) / b ) NEW_LINE common_divisor = int ( n / lcm - ( m - 1 ) / lcm ) NEW_LINE ans = a_divisor + b_divisor - common_divisor NEW_LINE return ans NEW_LINE DEDENT m = 3 NEW_LINE n = 11 NEW_LINE a = 2 NEW_LINE b = 3 ; NEW_LINE print ( rangeDivisor ( m , n , a , b ) ) NEW_LINE m = 11 NEW_LINE n = 1000000 NEW_LINE a = 6 NEW_LINE b = 35 NEW_LINE print ( rangeDivisor ( m , n , a , b ) ) NEW_LINE |
Numbers having Unique ( or Distinct ) digits | Function to print unique digit numbers in range from l to r . ; Start traversing the numbers ; Find digits and maintain its hash ; if a digit occurs more than 1 time then break ; num will be 0 only when above loop doesn 't get break that means the number is unique so print it. ; Driver code | def printUnique ( l , r ) : NEW_LINE INDENT for i in range ( l , r + 1 ) : NEW_LINE INDENT num = i ; NEW_LINE visited = [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] ; NEW_LINE while ( num ) : NEW_LINE INDENT if visited [ num % 10 ] == 1 : NEW_LINE INDENT break ; NEW_LINE DEDENT visited [ num % 10 ] = 1 ; NEW_LINE num = ( int ) ( num / 10 ) ; NEW_LINE DEDENT if num == 0 : NEW_LINE INDENT print ( i , end = " β " ) ; NEW_LINE DEDENT DEDENT DEDENT l = 1 ; NEW_LINE r = 20 ; NEW_LINE printUnique ( l , r ) ; NEW_LINE |
Fibonacci modulo p | Returns position of first Fibonacci number whose modulo p is 0. ; add previous two remainders and then take its modulo p . ; Driver code | def findMinZero ( p ) : NEW_LINE INDENT first = 1 NEW_LINE second = 1 NEW_LINE number = 2 NEW_LINE next = 1 NEW_LINE while ( next ) : NEW_LINE INDENT next = ( first + second ) % p NEW_LINE first = second NEW_LINE second = next NEW_LINE number = number + 1 NEW_LINE DEDENT return number NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT p = 7 NEW_LINE print ( " Minimal β zero β is : " , findMinZero ( p ) ) NEW_LINE DEDENT |
Perfect cubes in a range | A Simple Method to count cubes between a and b ; Traverse through all numbers in given range and one by one check if number is prime ; Check if current number ' i ' is perfect cube ; Driver code | def printCubes ( a , b ) : NEW_LINE INDENT for i in range ( a , b + 1 ) : NEW_LINE INDENT j = 1 NEW_LINE for j in range ( j ** 3 , i + 1 ) : NEW_LINE INDENT if ( j ** 3 == i ) : NEW_LINE INDENT print ( j ** 3 , end = " β " ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT a = 1 ; b = 100 NEW_LINE print ( " Perfect β cubes β in β given β range : β " ) NEW_LINE printCubes ( a , b ) NEW_LINE |
Converting a Real Number ( between 0 and 1 ) to Binary String | Function to convert Binary real number to String ; Check if the number is Between 0 to 1 or Not ; Setting a limit on length : 32 characters . ; compare the number to .5 ; Now it become 0.25 ; Input value | def toBinary ( n ) : NEW_LINE INDENT if ( n >= 1 or n <= 0 ) : NEW_LINE INDENT return " ERROR " ; NEW_LINE DEDENT frac = 0.5 ; NEW_LINE answer = " . " ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( len ( answer ) >= 32 ) : NEW_LINE INDENT return " ERROR " ; NEW_LINE DEDENT if ( n >= frac ) : NEW_LINE INDENT answer += "1" ; NEW_LINE n = n - frac ; NEW_LINE DEDENT else : NEW_LINE INDENT answer += "0" ; NEW_LINE DEDENT frac = ( frac / 2 ) ; NEW_LINE DEDENT return answer ; NEW_LINE DEDENT n = 0.625 ; NEW_LINE result = toBinary ( n ) ; NEW_LINE print ( " ( β 0" , result , " ) β in β base β 2" ) ; NEW_LINE m = 0.72 ; NEW_LINE result = toBinary ( m ) ; NEW_LINE print ( " ( " , result , " ) " ) ; NEW_LINE |
Given a number n , find the first k digits of n ^ n | function that manually calculates n ^ n and then removes digits until k digits remain ; loop will terminate when there are only k digits left ; Driver Code | def firstkdigits ( n , k ) : NEW_LINE INDENT product = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT product *= n NEW_LINE DEDENT while ( ( product // pow ( 10 , k ) ) != 0 ) : NEW_LINE INDENT product = product // 10 NEW_LINE DEDENT return product NEW_LINE DEDENT n = 15 NEW_LINE k = 4 NEW_LINE print ( firstkdigits ( n , k ) ) NEW_LINE |
Check if a large number is divisible by 9 or not | Function to find that number divisible by 9 or not ; Compute sum of digits ; Check if sum of digits is divisible by 9. ; Driver code | def check ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE digitSum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT digitSum = digitSum + ( int ) ( st [ i ] ) NEW_LINE DEDENT return ( digitSum % 9 == 0 ) NEW_LINE DEDENT st = "99333" NEW_LINE if ( check ( st ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
XOR of all subarray XORs | Set 1 | Returns XOR of all subarray xors ; initialize result by 0 as ( a xor 0 = a ) ; select the starting element ; select the eNding element ; Do XOR of elements in current subarray ; Driver code to test above methods | def getTotalXorOfSubarrayXors ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i , N ) : NEW_LINE INDENT for k in range ( i , j + 1 ) : NEW_LINE INDENT res = res ^ arr [ k ] NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 3 , 5 , 2 , 4 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( getTotalXorOfSubarrayXors ( arr , N ) ) NEW_LINE |
XOR of all subarray XORs | Set 1 | Returns XOR of all subarray xors ; initialize result by 0 as ( a XOR 0 = a ) ; loop over all elements once ; get the frequency of current element ; if frequency is odd , then include it in the result ; return the result ; Driver Code | def getTotalXorOfSubarrayXors ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT freq = ( i + 1 ) * ( N - i ) NEW_LINE if ( freq % 2 == 1 ) : NEW_LINE INDENT res = res ^ arr [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 3 , 5 , 2 , 4 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( getTotalXorOfSubarrayXors ( arr , N ) ) NEW_LINE |
Refactorable number | Function to count all divisors ; Initialize result ; If divisors are equal , count only one ; else : Otherwise count both ; Driver Code | import math NEW_LINE def isRefactorableNumber ( n ) : NEW_LINE INDENT divCount = 0 NEW_LINE for i in range ( 1 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT if n / i == i : NEW_LINE INDENT divCount += 1 NEW_LINE divCount += 2 NEW_LINE DEDENT DEDENT DEDENT return n % divCount == 0 NEW_LINE DEDENT n = 8 NEW_LINE if isRefactorableNumber ( n ) : NEW_LINE INDENT print " yes " NEW_LINE DEDENT else : NEW_LINE INDENT print " no " NEW_LINE DEDENT n = 14 NEW_LINE if ( isRefactorableNumber ( n ) ) : NEW_LINE INDENT print " yes " NEW_LINE DEDENT else : NEW_LINE INDENT print " no " NEW_LINE DEDENT |
Count all perfect divisors of a number | Python3 implementation of Naive method to count all perfect divisors ; Utility function to check perfect square number ; function to count all perfect divisors ; Initialize result ; Consider every number that can be a divisor of n ; If i is a divisor ; Driver program to test above function | import math NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sq = ( int ) ( math . sqrt ( x ) ) NEW_LINE return ( x == sq * sq ) NEW_LINE DEDENT def countPerfectDivisors ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( 1 , ( int ) ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if isPerfectSquare ( i ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE DEDENT if n / i != i and isPerfectSquare ( n / i ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT print ( " Total β perfect β divisor β of β 16 β = β " , countPerfectDivisors ( 16 ) ) NEW_LINE print ( " Total β perfect β divisor β of β 12 β = β " , countPerfectDivisors ( 12 ) ) NEW_LINE |
Nearest element with at | Python 3 program to print nearest element with at least one common prime factor . ; Loop covers the every element of arr [ ] ; Loop that covers from 0 to i - 1 and i + 1 to n - 1 indexes simultaneously ; print position of closest element ; Driver code | import math NEW_LINE def nearestGcd ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT closest = - 1 NEW_LINE j = i - 1 NEW_LINE k = i + 1 NEW_LINE while j > 0 or k <= n : NEW_LINE INDENT if ( j >= 0 and math . gcd ( arr [ i ] , arr [ j ] ) > 1 ) : NEW_LINE INDENT closest = j + 1 NEW_LINE break NEW_LINE DEDENT if ( k < n and math . gcd ( arr [ i ] , arr [ k ] ) > 1 ) : NEW_LINE INDENT closest = k + 1 NEW_LINE break NEW_LINE DEDENT k += 1 NEW_LINE j -= 1 NEW_LINE DEDENT print ( closest , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 9 , 4 , 3 , 13 ] NEW_LINE n = len ( arr ) NEW_LINE nearestGcd ( arr , n ) NEW_LINE DEDENT |
Largest subsequence having GCD greater than 1 | Efficient Python3 program to find length of the largest subsequence with GCD greater than 1. ; prime [ ] for storing smallest prime divisor of element count [ ] for storing the number of times a particular divisor occurs in a subsequence ; Simple sieve to find smallest prime factors of numbers smaller than MAX ; Prime number will have same divisor ; Returns length of the largest subsequence with GCD more than 1. ; Fetch total unique prime divisor of element ; Increment count [ ] of Every unique divisor we get till now ; Find maximum frequency of divisor ; Pre - compute smallest divisor of all numbers | import math as mt NEW_LINE MAX = 100001 NEW_LINE prime = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE countdiv = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT for i in range ( 2 , mt . ceil ( mt . sqrt ( MAX + 1 ) ) ) : NEW_LINE INDENT if ( prime [ i ] == 0 ) : NEW_LINE INDENT for j in range ( i * 2 , MAX + 1 , i ) : NEW_LINE INDENT prime [ j ] = i NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , MAX ) : NEW_LINE INDENT if ( prime [ i ] == 0 ) : NEW_LINE INDENT prime [ i ] = i NEW_LINE DEDENT DEDENT DEDENT def largestGCDSubsequence ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT element = arr [ i ] NEW_LINE while ( element > 1 ) : NEW_LINE INDENT div = prime [ element ] NEW_LINE countdiv [ div ] += 1 NEW_LINE ans = max ( ans , countdiv [ div ] ) NEW_LINE while ( element % div == 0 ) : NEW_LINE INDENT element = element // div NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT SieveOfEratosthenes ( ) NEW_LINE arr = [ 10 , 15 , 7 , 25 , 9 , 35 ] NEW_LINE size = len ( arr ) NEW_LINE print ( largestGCDSubsequence ( arr , size ) ) NEW_LINE |
Count of Binary Digit numbers smaller than N | Python3 program to count all binary digit numbers smaller than N ; method returns count of binary digit numbers smaller than N ; queue to store all intermediate binary digit numbers ; binary digits start with 1 ; loop until we have element in queue ; push next binary digit numbers only if current popped element is N ; uncomment below line to print actual number in sorted order ; Driver code to test above methods | from collections import deque NEW_LINE def countOfBinaryNumberLessThanN ( N ) : NEW_LINE INDENT q = deque ( ) NEW_LINE q . append ( 1 ) NEW_LINE cnt = 0 NEW_LINE while ( q ) : NEW_LINE INDENT t = q . popleft ( ) NEW_LINE if ( t <= N ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE q . append ( t * 10 ) NEW_LINE q . append ( t * 10 + 1 ) NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 200 NEW_LINE print ( countOfBinaryNumberLessThanN ( N ) ) NEW_LINE DEDENT |
Sum of product of x and y such that floor ( n / x ) = y | Return the sum of product x * y ; Iterating x from 1 to n ; Finding y = n / x . ; Adding product of x and y to answer . ; Driven Program | def sumofproduct ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for x in range ( 1 , n + 1 ) : NEW_LINE INDENT y = int ( n / x ) NEW_LINE ans += ( y * x ) NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 10 NEW_LINE print ( sumofproduct ( n ) ) NEW_LINE |
Find the first natural number whose factorial is divisible by x | function for calculating factorial ; function for check Special_Factorial_Number ; call fact function and the Modulo with k and check if condition is TRUE then return i ; Driver Code ; taking input | def fact ( n ) : NEW_LINE INDENT num = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT num = num * i NEW_LINE DEDENT return num NEW_LINE DEDENT def Special_Factorial_Number ( k ) : NEW_LINE INDENT for i in range ( 1 , k + 1 ) : NEW_LINE INDENT if ( fact ( i ) % k == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 16 NEW_LINE print ( Special_Factorial_Number ( k ) ) NEW_LINE DEDENT |
Program for Chocolate and Wrapper Puzzle | Returns maximum number of chocolates we can eat with given money , price of chocolate and number of wrapprices required to get a chocolate . ; Corner case ; First find number of chocolates that can be purchased with the given amount ; Now just add number of chocolates with the chocolates gained by wrapprices ; total money ; cost of each candy ; no of wrappers needs to be ; exchanged for one chocolate . | def countMaxChoco ( money , price , wrap ) : NEW_LINE INDENT if ( money < price ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT choc = int ( money / price ) NEW_LINE choc = choc + ( choc - 1 ) / ( wrap - 1 ) NEW_LINE return int ( choc ) NEW_LINE DEDENT money = 15 NEW_LINE price = 1 NEW_LINE wrap = 3 NEW_LINE print ( countMaxChoco ( money , price , wrap ) ) NEW_LINE |
Check if possible to move from given coordinate to desired coordinate | Python program to check if it is possible to reach ( a , b ) from ( x , y ) . Returns GCD of i and j ; Returns true if it is possible to go to ( a , b ) from ( x , y ) ; Find absolute values of all as sign doesn 't matter. ; If gcd is equal then it is possible to reach . Else not possible . ; Driven Program Converting coordinate into positive integer | def gcd ( i , j ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return i NEW_LINE DEDENT if ( i > j ) : NEW_LINE INDENT return gcd ( i - j , j ) NEW_LINE DEDENT return gcd ( i , j - i ) NEW_LINE DEDENT def ispossible ( x , y , a , b ) : NEW_LINE INDENT x , y , a , b = abs ( x ) , abs ( y ) , abs ( a ) , abs ( b ) NEW_LINE return ( gcd ( x , y ) == gcd ( a , b ) ) NEW_LINE DEDENT x , y = 35 , 15 NEW_LINE a , b = 20 , 25 NEW_LINE if ( ispossible ( x , y , a , b ) ) : NEW_LINE INDENT print " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT print " No " NEW_LINE DEDENT |
Equidigital Numbers | Python3 Program to find Equidigital Numbers till n ; Array to store all prime less than and equal to MAX . ; Utility function for sieve of sundaram ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than MAX , we reduce MAX to half . This array is used to separate numbers of the form i + j + 2 ij from others where 1 <= i <= j ; Main logic of Sundaram . Mark all numbers which do not generate prime number by doing 2 * i + 1 ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Returns true if n is a Equidigital number , else false . ; Count digits in original number ; Count all digits in prime factors of n pDigit is going to hold this value . ; Count powers of p in n ; If primes [ i ] is a prime factor , ; Count the power of prime factors ; Add its digits to pDigit . ; Add digits of power of prime factors to pDigit . ; If n != 1 then one prime factor still to be summed up ; ; If digits in prime factors and digits in original number are same , then return true . Else return false . ; Finding all prime numbers before limit . These numbers are used to find prime factors . | import math NEW_LINE MAX = 10000 ; NEW_LINE primes = [ ] ; NEW_LINE def sieveSundaram ( ) : NEW_LINE INDENT marked = [ False ] * int ( MAX / 2 + 1 ) ; NEW_LINE for i in range ( 1 , int ( ( math . sqrt ( MAX ) - 1 ) / 2 ) + 1 ) : NEW_LINE INDENT for j in range ( ( i * ( i + 1 ) ) << 1 , int ( MAX / 2 ) + 1 , 2 * i + 1 ) : NEW_LINE INDENT marked [ j ] = True ; NEW_LINE DEDENT DEDENT primes . append ( 2 ) ; NEW_LINE for i in range ( 1 , int ( MAX / 2 ) + 1 ) : NEW_LINE INDENT if ( marked [ i ] == False ) : NEW_LINE INDENT primes . append ( 2 * i + 1 ) ; NEW_LINE DEDENT DEDENT DEDENT def isEquidigital ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT original_no = n ; NEW_LINE sumDigits = 0 ; NEW_LINE while ( original_no > 0 ) : NEW_LINE INDENT sumDigits += 1 ; NEW_LINE original_no = int ( original_no / 10 ) ; NEW_LINE DEDENT pDigit = 0 ; NEW_LINE count_exp = 0 ; NEW_LINE p = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( primes [ i ] <= int ( n / 2 ) ) : NEW_LINE INDENT while ( n % primes [ i ] == 0 ) : NEW_LINE INDENT p = primes [ i ] ; NEW_LINE n = int ( n / p ) ; NEW_LINE count_exp += 1 ; NEW_LINE DEDENT while ( p > 0 ) : NEW_LINE INDENT pDigit += 1 ; NEW_LINE p = int ( p / 10 ) ; NEW_LINE DEDENT while ( count_exp > 1 ) : NEW_LINE INDENT pDigit += 1 ; NEW_LINE count_exp = int ( count_exp / 10 ) ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT if ( n != 1 ) : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT pDigit += 1 ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE DEDENT DEDENT return ( pDigit == sumDigits ) ; NEW_LINE DEDENT sieveSundaram ( ) ; NEW_LINE print ( " Printing β first β few β Equidigital " , " Numbers β using β isEquidigital ( ) " ) ; NEW_LINE for i in range ( 1 , 20 ) : NEW_LINE INDENT if ( isEquidigital ( i ) ) : NEW_LINE INDENT print ( i , end = " β " ) ; NEW_LINE DEDENT DEDENT |
LCM of First n Natural Numbers | To calculate hcf ; to calculate lcm ; lcm ( a , b ) = ( a * b ) hcf ( a , b ) ; Assign a = lcm of n , n - 1 ; b = b - 1 ; Driver code ; ; Function call pass n , n - 1 in function to find LCM of first n natural number | def hcf ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return hcf ( b , a % b ) NEW_LINE DEDENT def findlcm ( a , b ) : NEW_LINE INDENT if ( b == 1 ) : NEW_LINE INDENT return a NEW_LINE DEDENT a = ( a * b ) // hcf ( a , b ) NEW_LINE b -= 1 NEW_LINE return findlcm ( a , b ) NEW_LINE DEDENT n = 7 NEW_LINE if ( n < 3 ) : NEW_LINE / * base case * / NEW_LINE INDENT print ( n ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( findlcm ( n , n - 1 ) ) NEW_LINE DEDENT |
Smallest number divisible by first n numbers | Python program to find the smallest number evenly divisible by all number 1 to n ; Returns the lcm of first n numbers ; Driver code | import math NEW_LINE def lcm ( n ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = int ( ( ans * i ) / math . gcd ( ans , i ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 20 NEW_LINE print ( lcm ( n ) ) NEW_LINE |
Trapezoidal Rule for Approximate Value of Definite Integral | A sample function whose definite integral 's approximate value is computed using Trapezoidal rule ; Declaring the function f ( x ) = 1 / ( 1 + x * x ) ; Function to evaluate the value of integral ; Grid spacing ; Computing sum of first and last terms in above formula ; Adding middle terms in above formula ; h / 2 indicates ( b - a ) / 2 n . Multiplying h / 2 with s . ; Range of definite integral ; Number of grids . Higher value means more accuracy | def y ( x ) : NEW_LINE INDENT return ( 1 / ( 1 + x * x ) ) NEW_LINE DEDENT def trapezoidal ( a , b , n ) : NEW_LINE INDENT h = ( b - a ) / n NEW_LINE s = ( y ( a ) + y ( b ) ) NEW_LINE i = 1 NEW_LINE while i < n : NEW_LINE INDENT s += 2 * y ( a + i * h ) NEW_LINE i += 1 NEW_LINE DEDENT return ( ( h / 2 ) * s ) NEW_LINE DEDENT x0 = 0 NEW_LINE xn = 1 NEW_LINE n = 6 NEW_LINE print ( " Value β of β integral β is β " , " % .4f " % trapezoidal ( x0 , xn , n ) ) NEW_LINE |
Breaking an Integer to get Maximum Product | The main function that returns the max possible product ; n equals to 2 or 3 must be handled explicitly ; Keep removing parts of size 3 while n is greater than 4 ; Keep multiplying 3 to res ; The last part multiplied by previous parts ; Driver program to test above functions | def maxProd ( n ) : NEW_LINE INDENT if ( n == 2 or n == 3 ) : NEW_LINE INDENT return ( n - 1 ) ; NEW_LINE DEDENT res = 1 ; NEW_LINE while ( n > 4 ) : NEW_LINE INDENT n -= 3 ; NEW_LINE res *= 3 ; NEW_LINE DEDENT return ( n * res ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( " Maximum β Product β is " , maxProd ( 45 ) ) NEW_LINE DEDENT |
Number of elements with odd factors in given range | Function to count odd squares ; Driver code | def countOddSquares ( n , m ) : NEW_LINE INDENT return int ( m ** 0.5 ) - int ( ( n - 1 ) ** 0.5 ) NEW_LINE DEDENT n = 5 NEW_LINE m = 100 NEW_LINE print ( " Count β is " , countOddSquares ( n , m ) ) NEW_LINE |
Check if a number exists having exactly N factors and K prime factors | Function to compute the number of factors of the given number ; Vector to store the prime factors ; While there are no two multiples in the number , divide it by 2 ; If the size is already greater than K , then return true ; Computing the remaining divisors of the number ; If n is divisible by i , then it is a divisor ; If the size is already greater than K , then return true ; If the size is already greater than K , then return true ; If none of the above conditions satisfies , then return false ; Function to check if it is possible to make a number having total N factors and K prime factors ; If total divisors are less than the number of prime divisors , then print No ; Find the number of factors of n ; Driver Code | def factors ( n , k ) : NEW_LINE INDENT v = [ ] ; NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT v . append ( 2 ) ; NEW_LINE n //= 2 ; NEW_LINE DEDENT if ( len ( v ) >= k ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT for i in range ( 3 , int ( n ** ( 1 / 2 ) ) , 2 ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT n = n // i ; NEW_LINE v . append ( i ) ; NEW_LINE DEDENT if ( len ( v ) >= k ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT v . append ( n ) ; NEW_LINE DEDENT if ( len ( v ) >= k ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def operation ( n , k ) : NEW_LINE INDENT answered = False ; NEW_LINE if ( n < k ) : NEW_LINE INDENT answered = True ; NEW_LINE print ( " No " ) ; NEW_LINE DEDENT ok = factors ( n , k ) ; NEW_LINE if ( not ok and not answered ) : NEW_LINE INDENT answered = True ; NEW_LINE print ( " No " ) ; NEW_LINE DEDENT if ( ok and not answered ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 ; NEW_LINE k = 2 ; NEW_LINE operation ( n , k ) ; NEW_LINE DEDENT |
To Generate a One Time Password or Unique Identification URL | A Python3 Program to generate OTP ( One Time Password ) ; A Function to generate a unique OTP everytime ; All possible characters of my OTP ; String to hold my OTP ; Driver code ; Declare the length of OTP | import random NEW_LINE def generateOTP ( length ) : NEW_LINE INDENT str = " abcdefghijklmnopqrstuvwxyzAB\ STRNEWLINE TABSYMBOL CDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ; NEW_LINE n = len ( str ) ; NEW_LINE OTP = " " ; NEW_LINE for i in range ( 1 , length + 1 ) : NEW_LINE INDENT OTP += str [ int ( random . random ( ) * 10 ) % n ] ; NEW_LINE DEDENT return ( OTP ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT length = 6 ; NEW_LINE print ( " Your β OTP β is β - β " , generateOTP ( length ) ) ; NEW_LINE DEDENT |
LCM of given array elements | Recursive function to return gcd of a and b ; recursive implementation ; lcm ( a , b ) = ( a * b / gcd ( a , b ) ) ; 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 LcmOfArray ( arr , idx ) : NEW_LINE INDENT if ( idx == len ( arr ) - 1 ) : NEW_LINE INDENT return arr [ idx ] NEW_LINE DEDENT a = arr [ idx ] NEW_LINE b = LcmOfArray ( arr , idx + 1 ) NEW_LINE return int ( a * b / __gcd ( a , b ) ) NEW_LINE DEDENT arr = [ 1 , 2 , 8 , 3 ] NEW_LINE print ( LcmOfArray ( arr , 0 ) ) NEW_LINE arr = [ 2 , 7 , 3 , 9 , 4 ] NEW_LINE print ( LcmOfArray ( arr , 0 ) ) NEW_LINE |
Check if a number is a power of another number | Returns true if y is a power of x ; The only power of 1 is 1 itself ; Repeatedly compute power of x ; Check if power of x becomes y ; check the result for true / false and print | def isPower ( x , y ) : NEW_LINE INDENT if ( x == 1 ) : NEW_LINE INDENT return ( y == 1 ) NEW_LINE DEDENT pow = 1 NEW_LINE while ( pow < y ) : NEW_LINE INDENT pow = pow * x NEW_LINE DEDENT return ( pow == y ) NEW_LINE DEDENT if ( isPower ( 10 , 1 ) ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT if ( isPower ( 1 , 20 ) ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT if ( isPower ( 2 , 128 ) ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT if ( isPower ( 2 , 30 ) ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT |
Number of perfect squares between two given numbers | An Efficient Method to count squares between a and b ; An efficient solution to count square between a and b ; Driver Code | import math NEW_LINE def CountSquares ( a , b ) : NEW_LINE INDENT return ( math . floor ( math . sqrt ( b ) ) - math . ceil ( math . sqrt ( a ) ) + 1 ) NEW_LINE DEDENT a = 9 NEW_LINE b = 25 NEW_LINE print " Count β of β squares β is : " , int ( CountSquares ( a , b ) ) NEW_LINE |
Check if count of divisors is even or odd | Naive Solution to find if count of divisors is even or odd ; Function to count the divisors ; Initialize count of divisors ; Note that this loop runs till square root ; If divisors are equal , increment count by one Otherwise increment count by 2 ; Driver Code | import math NEW_LINE def countDivisors ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , ( int ) ( math . sqrt ( n ) ) + 2 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n // i == i ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = count + 2 NEW_LINE DEDENT DEDENT DEDENT if ( count % 2 == 0 ) : NEW_LINE INDENT print ( " Even " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Odd " ) NEW_LINE DEDENT DEDENT print ( " The β count β of β divisor : β " ) NEW_LINE countDivisors ( 10 ) NEW_LINE |
Gray to Binary and Binary to Gray conversion | Python3 code for above approach ; Driver code | def greyConverter ( n ) : NEW_LINE INDENT return n ^ ( n >> 1 ) NEW_LINE DEDENT n = 3 NEW_LINE print ( greyConverter ( n ) ) NEW_LINE n = 9 NEW_LINE print ( greyConverter ( n ) ) NEW_LINE |
Compute n ! under modulo p | Returns largest power of p that divides n ! ; Initialize result ; Calculate x = n / p + n / ( p ^ 2 ) + n / ( p ^ 3 ) + ... . ; Utility function to do modular exponentiation . It returns ( x ^ y ) % p ; Initialize result 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 ; Returns n ! % p ; Use Sieve of Eratosthenes to find all primes smaller than n ; Consider all primes found by Sieve ; Find the largest power of prime ' i ' that divides n ; Multiply result with ( i ^ k ) % p ; Driver code | def largestPower ( n , p ) : NEW_LINE INDENT x = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n //= p NEW_LINE x += n NEW_LINE DEDENT return x NEW_LINE DEDENT def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def modFact ( n , p ) : NEW_LINE INDENT if ( n >= p ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = 1 NEW_LINE isPrime = [ 1 ] * ( n + 1 ) NEW_LINE i = 2 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT for j in range ( 2 * i , n , i ) : NEW_LINE INDENT isPrime [ j ] = 0 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT k = largestPower ( n , i ) NEW_LINE res = ( res * power ( i , k , p ) ) % p NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 25 NEW_LINE p = 29 NEW_LINE print ( modFact ( n , p ) ) NEW_LINE DEDENT |
Count number of squares in a rectangle | Returns count of all squares in a rectangle of size m x n ; If n is smaller , swap m and n ; Now n is greater dimension , apply formula ; Driver Code | def countSquares ( m , n ) : NEW_LINE INDENT if ( n < m ) : NEW_LINE INDENT temp = m NEW_LINE m = n NEW_LINE n = temp NEW_LINE DEDENT return ( ( m * ( m + 1 ) * ( 2 * m + 1 ) / 6 + ( n - m ) * m * ( m + 1 ) / 2 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 4 NEW_LINE n = 3 NEW_LINE print ( " Count β of β squares β is β " , countSquares ( m , n ) ) NEW_LINE DEDENT |
Count factorial numbers in a given range | Function to count factorial ; Find the first factorial number ' fact ' greater than or equal to 'low ; Count factorial numbers in range [ low , high ] ; Return the count ; Driver code | def countFact ( low , high ) : NEW_LINE ' NEW_LINE INDENT fact = 1 NEW_LINE x = 1 NEW_LINE while ( fact < low ) : NEW_LINE INDENT fact = fact * x NEW_LINE x += 1 NEW_LINE DEDENT res = 0 NEW_LINE while ( fact <= high ) : NEW_LINE INDENT res += 1 NEW_LINE fact = fact * x NEW_LINE x += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT print ( " Count β is β " , countFact ( 2 , 720 ) ) NEW_LINE |
Find number of days between two given dates | A date has day ' d ' , month ' m ' and year 'y ; To store number of days in all months from January to Dec . ; This function counts number of leap years before the given date ; Check if the current year needs to be considered for the count of leap years or not ; An year is a leap year if it is a multiple of 4 , multiple of 400 and not a multiple of 100. ; This function returns number of days between two given dates ; initialize count using years and day ; Add days for months in given date ; Since every leap year is of 366 days , Add a day for every leap year ; SIMILARLY , COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2 ; return difference between two counts ; Driver Code ; Function call | ' NEW_LINE class Date : NEW_LINE INDENT def __init__ ( self , d , m , y ) : NEW_LINE INDENT self . d = d NEW_LINE self . m = m NEW_LINE self . y = y NEW_LINE DEDENT DEDENT monthDays = [ 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ] NEW_LINE def countLeapYears ( d ) : NEW_LINE INDENT years = d . y NEW_LINE if ( d . m <= 2 ) : NEW_LINE INDENT years -= 1 NEW_LINE DEDENT ans = int ( years / 4 ) NEW_LINE ans -= int ( years / 100 ) NEW_LINE ans += int ( years / 400 ) NEW_LINE return ans NEW_LINE DEDENT def getDifference ( dt1 , dt2 ) : NEW_LINE INDENT n1 = dt1 . y * 365 + dt1 . d NEW_LINE for i in range ( 0 , dt1 . m - 1 ) : NEW_LINE INDENT n1 += monthDays [ i ] NEW_LINE DEDENT n1 += countLeapYears ( dt1 ) NEW_LINE DEDENT ' NEW_LINE INDENT n2 = dt2 . y * 365 + dt2 . d NEW_LINE for i in range ( 0 , dt2 . m - 1 ) : NEW_LINE INDENT n2 += monthDays [ i ] NEW_LINE DEDENT n2 += countLeapYears ( dt2 ) NEW_LINE return ( n2 - n1 ) NEW_LINE DEDENT dt1 = Date ( 1 , 9 , 2014 ) NEW_LINE dt2 = Date ( 3 , 9 , 2020 ) NEW_LINE print ( " Difference β between β two β dates β is " , getDifference ( dt1 , dt2 ) ) NEW_LINE |
Find length of period in decimal value of 1 / n | Function to find length of period in 1 / n ; Find the ( n + 1 ) th remainder after decimal point in value of 1 / n ; Store ( n + 1 ) th remainder ; Count the number of remainders before next occurrence of ( n + 1 ) ' th β remainder β ' d ; Driver Code | def getPeriod ( n ) : NEW_LINE INDENT rem = 1 NEW_LINE for i in range ( 1 , n + 2 ) : NEW_LINE INDENT rem = ( 10 * rem ) % n NEW_LINE DEDENT d = rem NEW_LINE DEDENT ' NEW_LINE INDENT count = 0 NEW_LINE rem = ( 10 * rem ) % n NEW_LINE count += 1 NEW_LINE while rem != d : NEW_LINE INDENT rem = ( 10 * rem ) % n NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( getPeriod ( 3 ) ) NEW_LINE print ( getPeriod ( 7 ) ) NEW_LINE DEDENT |
Replace all Γ’ β¬Λ 0 Γ’ β¬β’ with Γ’ β¬Λ 5 Γ’ β¬β’ in an input Integer | ; returns the number to be added to the input to replace all zeroes with five ; amount to be added ; unit decimal place ; a number divisible by 10 , then this is a zero occurrence in the input ; move one decimal place ; Driver code | def replace0with5 ( number ) : NEW_LINE INDENT number += calculateAddedValue ( number ) NEW_LINE return number NEW_LINE DEDENT def calculateAddedValue ( number ) : NEW_LINE INDENT result = 0 NEW_LINE decimalPlace = 1 NEW_LINE if ( number == 0 ) : NEW_LINE INDENT result += ( 5 * decimalPlace ) NEW_LINE DEDENT while ( number > 0 ) : NEW_LINE INDENT if ( number % 10 == 0 ) : NEW_LINE INDENT result += ( 5 * decimalPlace ) NEW_LINE DEDENT number //= 10 NEW_LINE decimalPlace *= 10 NEW_LINE DEDENT return result NEW_LINE DEDENT print ( replace0with5 ( 1020 ) ) NEW_LINE |
Program to find remainder without using modulo or % operator | This function returns remainder of num / divisor without using % ( modulo ) operator ; Driver program to test above functions | def getRemainder ( num , divisor ) : NEW_LINE INDENT return ( num - divisor * ( num // divisor ) ) NEW_LINE DEDENT num = 100 NEW_LINE divisor = 7 NEW_LINE print ( getRemainder ( num , divisor ) ) NEW_LINE |
Efficient Program to Compute Sum of Series 1 / 1 ! + 1 / 2 ! + 1 / 3 ! + 1 / 4 ! + . . + 1 / n ! | Function to return value of 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; Update factorial ; Update series sum ; Driver program to test above functions | def sum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE fact = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fact *= i NEW_LINE sum += 1.0 / fact NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT n = 5 NEW_LINE sum ( n ) NEW_LINE |
Print first k digits of 1 / n where n is a positive integer | Python code to Print first k digits of 1 / n where n is a positive integer ; Function to print first k digits after dot in value of 1 / n . n is assumed to be a positive integer . ; Initialize remainder ; Run a loop k times to print k digits ; The next digit can always be obtained as doing ( 10 * rem ) / 10 ; Update remainder ; Driver program to test above function | import math NEW_LINE def Print ( n , k ) : NEW_LINE INDENT rem = 1 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT print ( math . floor ( ( ( 10 * rem ) / n ) ) , end = " " ) NEW_LINE rem = ( 10 * rem ) % n NEW_LINE DEDENT DEDENT n = 7 NEW_LINE k = 3 NEW_LINE Print ( n , k ) ; NEW_LINE print ( " β " ) NEW_LINE n = 21 NEW_LINE k = 4 NEW_LINE Print ( n , k ) ; NEW_LINE |
Program to find sum of series 1 + 1 / 2 + 1 / 3 + 1 / 4 + . . + 1 / n | Function to return sum of 1 / 1 + 1 / 2 + 1 / 3 + . . + 1 / n ; Driver Code | def sum ( n ) : NEW_LINE INDENT i = 1 NEW_LINE s = 0.0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT s = s + 1 / i ; NEW_LINE DEDENT return s ; NEW_LINE DEDENT n = 5 NEW_LINE print ( " Sum β is " , round ( sum ( n ) , 6 ) ) NEW_LINE |
Program to find GCD or HCF of two numbers | Recursive function to return gcd of a and b ; Driver program to test above function | 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 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 |
Rearrange an array so that arr [ i ] becomes arr [ arr [ i ] ] with O ( 1 ) extra space | The function to rearrange an array in - place so that arr [ i ] becomes arr [ arr [ i ] ] . ; First step : Increase all values by ( arr [ arr [ i ] ] % n ) * n ; Second Step : Divide all values by n ; A utility function to print an array of size n ; Driver program | def rearrange ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT arr [ i ] += ( arr [ arr [ i ] ] % n ) * n NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT arr [ i ] = int ( arr [ i ] / n ) NEW_LINE DEDENT DEDENT def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT arr = [ 3 , 2 , 0 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Given β array β is " ) NEW_LINE printArr ( arr , n ) NEW_LINE rearrange ( arr , n ) ; NEW_LINE print ( " Modified β array β is " ) NEW_LINE printArr ( arr , n ) NEW_LINE |
Print all sequences of given length | A utility function that prints a given arr [ ] of length size ; The core function that recursively generates and prints all sequences of length k ; A function that uses printSequencesRecur ( ) to prints all sequences from 1 , 1 , . .1 to n , n , . . n ; Driver Code | def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT print ( " " ) ; NEW_LINE return ; NEW_LINE DEDENT def printSequencesRecur ( arr , n , k , index ) : NEW_LINE INDENT if ( k == 0 ) : NEW_LINE INDENT printArray ( arr , index ) ; NEW_LINE DEDENT if ( k > 0 ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT arr [ index ] = i ; NEW_LINE printSequencesRecur ( arr , n , k - 1 , index + 1 ) ; NEW_LINE DEDENT DEDENT DEDENT def printSequences ( n , k ) : NEW_LINE INDENT arr = [ 0 ] * n ; NEW_LINE printSequencesRecur ( arr , n , k , 0 ) ; NEW_LINE return ; NEW_LINE DEDENT n = 3 ; NEW_LINE k = 2 ; NEW_LINE printSequences ( n , k ) ; NEW_LINE |
Check if a number is multiple of 5 without using / and % operators | Assumes that n is a positive integer ; Driver Code | def isMultipleof5 ( n ) : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT n = n - 5 NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT i = 19 NEW_LINE if ( isMultipleof5 ( i ) == 1 ) : NEW_LINE INDENT print ( i , " is β multiple β of β 5" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( i , " is β not β a β multiple β of β 5" ) NEW_LINE DEDENT |
Count pairs from an array having sum of twice of their AND and XOR equal to K | Python3 program for the above approach ; Function to count number of pairs satisfying the given conditions ; Stores the frequency of array elements ; Stores the total number of pairs ; Traverse the array ; Add it to cnt ; Update frequency of current array element ; Print the count ; Given array ; Size of the array ; Given value of K | from collections import defaultdict NEW_LINE def countPairs ( arr , N , K ) : NEW_LINE INDENT mp = defaultdict ( int ) NEW_LINE cnt = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cnt += mp [ K - arr [ i ] ] NEW_LINE mp [ arr [ i ] ] += 1 NEW_LINE DEDENT print ( cnt ) NEW_LINE DEDENT arr = [ 1 , 5 , 4 , 8 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE K = 9 NEW_LINE countPairs ( arr , N , K ) NEW_LINE |
Queries to count array elements from a given range having a single set bit | Function to check whether only one bit is set or not ; Function to perform Range - query ; Function to count array elements with a single set bit for each range in a query ; Initialize array for Prefix sum ; Driver Code ; Given array ; Size of the array ; Given queries ; Size of queries array | def check ( x ) : NEW_LINE INDENT if ( ( ( x ) & ( x - 1 ) ) == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def query ( l , r , pre ) : NEW_LINE INDENT if ( l == 0 ) : NEW_LINE INDENT return pre [ r ] NEW_LINE DEDENT else : NEW_LINE INDENT return pre [ r ] - pre [ l - 1 ] NEW_LINE DEDENT DEDENT def countInRange ( arr , N , queries , Q ) : NEW_LINE INDENT pre = [ 0 ] * N NEW_LINE pre [ 0 ] = check ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + check ( arr [ i ] ) NEW_LINE DEDENT c = 0 NEW_LINE while ( Q > 0 ) : NEW_LINE INDENT l = queries [ 0 ] NEW_LINE r = queries [ 1 ] NEW_LINE c += 1 NEW_LINE print ( query ( l , r , pre ) , end = " β " ) NEW_LINE Q -= 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , 11 , 16 , 8 , 2 , 5 , 1 , 3 , 256 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE queries = [ [ 0 , 9 ] , [ 4 , 9 ] ] NEW_LINE Q = len ( queries ) NEW_LINE countInRange ( arr , N , queries , Q ) NEW_LINE DEDENT |
Bitwise operations on Subarrays of size K | Function to convert bit array to decimal number ; Function to find minimum values of each bitwise AND 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 to removed element ; Perform operation to add element ; Taking minimum value ; Return the result ; Driver Code ; Given array arr ; Given subarray size K ; Function call | def build_num ( bit , k ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT if ( bit [ i ] == k ) : NEW_LINE INDENT ans += ( 1 << i ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT def minimumAND ( 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 min_and = build_num ( bit , k ) ; 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 min_and = min ( build_num ( bit , k ) , min_and ) ; NEW_LINE DEDENT return min_and ; 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 ( minimumAND ( arr , n , k ) ) ; NEW_LINE DEDENT |
Equal Sum and XOR of three Numbers | Function to calculate power of 3 ; Function to return the count of the unset bit ( zeros ) ; Check the bit is 0 or not ; Right shifting ( dividing by 2 ) ; Driver Code | def calculate ( bit_cnt ) : NEW_LINE INDENT res = 1 ; NEW_LINE while ( bit_cnt > 0 ) : NEW_LINE INDENT bit_cnt -= 1 ; NEW_LINE res = res * 3 ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def unset_bit_count ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( ( n & 1 ) == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT n = n >> 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 ; NEW_LINE count = unset_bit_count ( n ) ; NEW_LINE ans = calculate ( count ) ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT |
Count pairs of elements such that number of set bits in their AND is B [ i ] | Function to return the count of pairs which satisfy the given condition ; Check if the count of set bits in the AND value is B [ j ] ; Driver code | def solve ( A , B , n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT c = A [ i ] & A [ j ] NEW_LINE if ( bin ( c ) . count ( '1' ) == B [ j ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 2 , 3 , 1 , 4 , 5 ] ; NEW_LINE B = [ 2 , 2 , 1 , 4 , 2 ] ; NEW_LINE size = len ( A ) ; NEW_LINE print ( solve ( A , B , size ) ) ; NEW_LINE DEDENT |
Total pairs in an array such that the bitwise AND , bitwise OR and bitwise XOR of LSB is 1 | Function to find the count of required pairs ; To store the count of elements which give remainder 0 i . e . even values ; To store the count of elements which give remainder 1 i . e . odd values ; Driver code | def CalculatePairs ( a , n ) : NEW_LINE INDENT cnt_zero = 0 NEW_LINE cnt_one = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( a [ i ] % 2 == 0 ) : NEW_LINE INDENT cnt_zero += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt_one += 1 NEW_LINE DEDENT DEDENT total_XOR_pairs = cnt_zero * cnt_one NEW_LINE total_AND_pairs = ( cnt_one ) * ( cnt_one - 1 ) / 2 NEW_LINE total_OR_pairs = cnt_zero * cnt_one + ( cnt_one ) * ( cnt_one - 1 ) / 2 NEW_LINE print ( " cntXOR β = β " , int ( total_XOR_pairs ) ) NEW_LINE print ( " cntAND β = β " , int ( total_AND_pairs ) ) NEW_LINE print ( " cntOR β = β " , int ( total_OR_pairs ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 3 , 4 , 2 ] NEW_LINE n = len ( a ) NEW_LINE CalculatePairs ( a , n ) NEW_LINE DEDENT |
Assign other value to a variable from two possible values | Function to alternate the values ; Driver code | def alternate ( a , b , x ) : NEW_LINE INDENT x = a + b - x NEW_LINE print ( " After β change β x β is : " , x ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = - 10 NEW_LINE b = 15 NEW_LINE x = a NEW_LINE print ( " x β is : " , x ) NEW_LINE alternate ( a , b , x ) NEW_LINE DEDENT |
Subsets and Splits