text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Triplet with no element divisible by 3 and sum N | Function to print a , b and c ; check if n - 2 is divisible by 3 or not ; Driver code | def printCombination ( n ) : NEW_LINE INDENT print ( "1 β " , end = " " ) ; NEW_LINE if ( ( n - 2 ) % 3 == 0 ) : NEW_LINE INDENT print ( "2" , n - 3 , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( "1" , ( n - 2 ) , end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 233 ; NEW_LINE printCombination ( n ) ; NEW_LINE DEDENT |
Pairs with GCD equal to one in the given range | Function to print all pairs ; check if even ; we can print all adjacent pairs for i in range ( l , r , 2 ) : print ( " { " , i , " , " , i + 1 , " } , " ) ; Driver Code | def checkPairs ( l , r ) : NEW_LINE INDENT if ( l - r ) % 2 == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l , r = 1 , 8 NEW_LINE if checkPairs ( l , r ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Check if a number with even number of digits is palindrome or not | Function to check if the number is palindrome ; if divisible by 11 then return True ; if not divisible by 11 then return False ; Driver code | def isPalindrome ( n ) : NEW_LINE INDENT if n % 11 == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 123321 NEW_LINE if isPalindrome ( n ) : NEW_LINE INDENT print ( " Palindrome " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Palindrome " ) NEW_LINE DEDENT DEDENT |
Count number of triplets with product equal to given number with duplicates allowed | The target value for which we have to find the solution ; This variable contains the total count of triplets found ; Loop from the first to the third last integer in the list ; Check if arr [ i ] is a factor of target or not . If not , skip to the next element ; Check if the pair ( arr [ i ] , arr [ j ] ) can be a part of triplet whose product is equal to the target ; Find the remaining element of the triplet ; If element is found . increment the total count of the triplets | target = 93 NEW_LINE arr = [ 1 , 31 , 3 , 1 , 93 , 3 , 31 , 1 , 93 ] NEW_LINE length = len ( arr ) NEW_LINE totalCount = 0 NEW_LINE for i in range ( length - 2 ) : NEW_LINE INDENT if target % arr [ i ] == 0 : NEW_LINE INDENT for j in range ( i + 1 , length - 1 ) : NEW_LINE INDENT if target % ( arr [ i ] * arr [ j ] ) == 0 : NEW_LINE INDENT toFind = target // ( arr [ i ] * arr [ j ] ) NEW_LINE for k in range ( j + 1 , length ) : NEW_LINE INDENT if arr [ k ] == toFind : NEW_LINE INDENT totalCount += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT print ( ' Total β number β of β triplets β found : β ' , totalCount ) NEW_LINE |
Number of Permutations such that no Three Terms forms Increasing Subsequence | Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver code | def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 NEW_LINE if k > n - k : NEW_LINE INDENT k = n - k NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT res = res * ( n - i ) NEW_LINE res = res // ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def catalan ( n ) : NEW_LINE INDENT c = binomialCoeff ( 2 * n , n ) NEW_LINE return c // ( n + 1 ) NEW_LINE DEDENT n = 3 NEW_LINE print ( catalan ( n ) ) NEW_LINE |
Fascinating Number | function to check if number is fascinating or not ; frequency count array using 1 indexing ; obtaining the resultant number using string concatenation ; Traversing the string character by character ; gives integer value of a character digit ; To check if any digit has appeared multiple times ; Traversing through freq array to check if any digit was missing ; Driver Code ; Input number ; Not a valid number ; Calling the function to check if input number is fascinating or not | def isFascinating ( num ) : NEW_LINE INDENT freq = [ 0 ] * 10 NEW_LINE val = ( str ( num ) + str ( num * 2 ) + str ( num * 3 ) ) NEW_LINE for i in range ( len ( val ) ) : NEW_LINE INDENT digit = int ( val [ i ] ) NEW_LINE if freq [ digit ] and digit != 0 > 0 : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT freq [ digit ] += 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , 10 ) : NEW_LINE INDENT if freq [ i ] == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT num = 192 NEW_LINE if num < 100 : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = isFascinating ( num ) NEW_LINE if ans : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT DEDENT |
Count ways to distribute m items among n people | function used to generate binomial coefficient time complexity O ( m ) ; helper function for generating no of ways to distribute m mangoes amongst n people ; not enough mangoes to be distributed ; ways -> ( n + m - 1 ) C ( n - 1 ) ; Driver function ; m represents number of mangoes n represents number of people | def binomial_coefficient ( n , m ) : NEW_LINE INDENT res = 1 NEW_LINE if m > n - m : NEW_LINE INDENT m = n - m NEW_LINE DEDENT for i in range ( 0 , m ) : NEW_LINE INDENT res *= ( n - i ) NEW_LINE res /= ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def calculate_ways ( m , n ) : NEW_LINE INDENT if m < n : NEW_LINE INDENT return 0 NEW_LINE DEDENT ways = binomial_coefficient ( n + m - 1 , n - 1 ) NEW_LINE return int ( ways ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 7 ; n = 5 NEW_LINE result = calculate_ways ( m , n ) NEW_LINE print ( result ) NEW_LINE DEDENT |
Queries to count the number of unordered co | Python3 program to find number of unordered coprime pairs of integers from 1 to N ; to store euler 's totient function ; to store required answer ; Computes and prints totient of all numbers smaller than or equal to N . ; Initialise the phi [ ] with 1 ; Compute other Phi values ; If phi [ p ] is not computed already , then number p is prime ; Phi of a prime number p is always equal to p - 1. ; Update phi values of all multiples of p ; Add contribution of p to its multiple i by multiplying with ( 1 - 1 / p ) ; function to compute number coprime pairs ; function call to compute euler totient function ; prefix sum of all euler totient function values ; Driver code ; function call | N = 100005 NEW_LINE phi = [ 0 ] * N NEW_LINE S = [ 0 ] * N NEW_LINE def computeTotient ( ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT phi [ i ] = i NEW_LINE DEDENT for p in range ( 2 , N ) : NEW_LINE INDENT if ( phi [ p ] == p ) : NEW_LINE INDENT phi [ p ] = p - 1 NEW_LINE for i in range ( 2 * p , N , p ) : NEW_LINE INDENT phi [ i ] = ( phi [ i ] // p ) * ( p - 1 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def CoPrimes ( ) : NEW_LINE INDENT computeTotient ( ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT S [ i ] = S [ i - 1 ] + phi [ i ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT CoPrimes ( ) NEW_LINE q = [ 3 , 4 ] NEW_LINE n = len ( q ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( " Number of unordered coprime " β + β " pairs of integers from 1 to " , β q [ i ] , β " are " , S [ q [ i ] ] ) NEW_LINE DEDENT DEDENT |
N | Function to return the decimal value of a binary number ; Initializing base value to 1 , i . e 2 ^ 0 ; find the binary representation of the N - th number in sequence ; base case ; answer string ; add n - 1 1 's ; add 0 ; add n 1 's at end ; Driver Code | def binaryToDecimal ( n ) : NEW_LINE INDENT num = n NEW_LINE dec_value = 0 NEW_LINE base = 1 NEW_LINE l = len ( num ) NEW_LINE for i in range ( l - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( num [ i ] == '1' ) : NEW_LINE INDENT dec_value += base NEW_LINE DEDENT base = base * 2 NEW_LINE DEDENT return dec_value NEW_LINE DEDENT def numberSequence ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT s = " " NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT s += '1' NEW_LINE DEDENT s += '0' NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT s += '1' NEW_LINE DEDENT num = binaryToDecimal ( s ) NEW_LINE return num NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE print ( numberSequence ( n ) ) NEW_LINE DEDENT |
N | calculate Nth term of series ; calculates the N - th term ; Driver Code | def numberSequence ( n ) : NEW_LINE INDENT num = pow ( 4 , n ) - pow ( 2 , n ) - 1 NEW_LINE return num NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE print ( numberSequence ( n ) ) NEW_LINE DEDENT |
Alternate Primes till N | Function for checking number is prime or not ; if flag = 0 then number is prime and return 1 otherwise return 0 ; Function for printing alternate prime number ; counter is initialize with 0 ; looping through 2 to n - 1 ; function calling along with if condition ; if counter is multiple of 2 then only print prime number ; Driver code ; Function calling | def prime ( num ) : NEW_LINE INDENT flag = 0 NEW_LINE for i in range ( 2 , num // 2 + 1 ) : NEW_LINE INDENT if num % i == 0 : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if flag == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def print_alternate_prime ( n ) : NEW_LINE INDENT counter = 0 NEW_LINE for num in range ( 2 , n ) : NEW_LINE INDENT if prime ( num ) == 1 : NEW_LINE INDENT if counter % 2 == 0 : NEW_LINE INDENT print ( num , end = " β " ) NEW_LINE DEDENT counter += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 15 NEW_LINE print ( " Following β are β the β alternate β prime " + " number β smaller β than β or β equal β to " , n ) NEW_LINE print_alternate_prime ( n ) NEW_LINE DEDENT |
Alternate Primes till N | Python 3 program to print all equal to n using Sieve of Eratosthenes ; 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 ; Print all prime numbers ; for next prime to get printed ; Driver Code | def SieveOfEratosthenes ( n ) : NEW_LINE INDENT prime = [ None ] * ( n + 1 ) NEW_LINE for i in range ( len ( prime ) ) : NEW_LINE INDENT prime [ i ] = True NEW_LINE DEDENT 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 flag = True NEW_LINE for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT if ( flag ) : NEW_LINE INDENT print ( str ( p ) , end = " β " ) NEW_LINE flag = False NEW_LINE DEDENT else : NEW_LINE INDENT flag = True NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 15 NEW_LINE print ( " Following β are β the β alternate " + " β prime β numbers β smaller β " + " than β or β equal β to β " + str ( n ) ) NEW_LINE SieveOfEratosthenes ( n ) NEW_LINE DEDENT |
Find maximum among x ^ ( y ^ 2 ) or y ^ ( x ^ 2 ) where x and y are given | Function to find maximum ; Case 1 ; Case 2 ; Driver Code | def findGreater ( x , y ) : NEW_LINE INDENT if ( x > y ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT else : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT x = 4 ; NEW_LINE y = 9 ; NEW_LINE if ( findGreater ( x , y ) ) : NEW_LINE INDENT print ( "1" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( "2" ) ; NEW_LINE DEDENT |
Maximum profit after buying and selling stocks with transaction fees | Python3 implementation of above approach ; b [ 0 ] will contain the maximum profit ; b [ 1 ] will contain the day on which we are getting the maximum profit ; here finding the max profit ; if we get less then or equal to zero it means we are not getting the profit ; check if Sum is greater then maximum then store the new maximum ; Driver code | def max_profit ( a , b , n , fee ) : NEW_LINE INDENT i , j , profit = 1 , n - 1 , 0 NEW_LINE l , r , diff_day = 0 , 0 , 1 NEW_LINE b [ 0 ] = 0 NEW_LINE b [ 1 ] = diff_day NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT l = 0 NEW_LINE r = diff_day NEW_LINE Sum = 0 NEW_LINE for j in range ( n - 1 , i - 1 , - 1 ) : NEW_LINE INDENT profit = ( a [ r ] - a [ l ] ) - fee NEW_LINE if ( profit > 0 ) : NEW_LINE INDENT Sum = Sum + profit NEW_LINE DEDENT l += 1 NEW_LINE r += 1 NEW_LINE DEDENT if ( b [ 0 ] < Sum ) : NEW_LINE INDENT b [ 0 ] = Sum NEW_LINE b [ 1 ] = diff_day NEW_LINE DEDENT DEDENT diff_day += 1 NEW_LINE return 0 NEW_LINE DEDENT arr = [ 6 , 1 , 7 , 2 , 8 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE b = [ 0 for i in range ( 2 ) ] NEW_LINE tranFee = 2 NEW_LINE max_profit ( arr , b , n , tranFee ) NEW_LINE print ( b [ 0 ] , " , " , b [ 1 ] ) NEW_LINE |
Eggs dropping puzzle ( Binomial Coefficient and Binary Search Solution ) | Find sum of binomial coefficients xCi ( where i varies from 1 to n ) . If the sum becomes more than K ; Do binary search to find minimum number of trials in worst case . ; Initialize low and high as 1 st and last floors ; Do binary search , for every mid , find sum of binomial coefficients and check if the sum is greater than k or not . ; Driver Code | def binomialCoeff ( x , n , k ) : NEW_LINE INDENT sum = 0 ; NEW_LINE term = 1 ; NEW_LINE i = 1 ; NEW_LINE while ( i <= n and sum < k ) : NEW_LINE INDENT term *= x - i + 1 ; NEW_LINE term /= i ; NEW_LINE sum += term ; NEW_LINE i += 1 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def minTrials ( n , k ) : NEW_LINE INDENT low = 1 ; NEW_LINE high = k ; NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = int ( ( low + high ) / 2 ) ; NEW_LINE if ( binomialCoeff ( mid , n , k ) < k ) : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT high = mid ; NEW_LINE DEDENT DEDENT return int ( low ) ; NEW_LINE DEDENT print ( minTrials ( 2 , 10 ) ) ; NEW_LINE |
Find next palindrome prime | Python3 program to find next palindromic prime for a given number . ; if ( 8 <= N <= 11 ) return 11 ; generate odd length palindrome number which will cover given constraint . ; if y >= N and it is a prime number then return it . ; Driver code | import math as mt NEW_LINE def isPrime ( num ) : NEW_LINE INDENT if ( num < 2 or num % 2 == 0 ) : NEW_LINE INDENT return num == 2 NEW_LINE DEDENT for i in range ( 3 , mt . ceil ( mt . sqrt ( num + 1 ) ) ) : NEW_LINE INDENT if ( num % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def primePalindrome ( N ) : NEW_LINE INDENT if ( 8 <= N and N <= 11 ) : NEW_LINE INDENT return 11 NEW_LINE DEDENT for x in range ( 1 , 100000 ) : NEW_LINE INDENT s = str ( x ) NEW_LINE d = s [ : : - 1 ] NEW_LINE y = int ( s + d [ 1 : ] ) NEW_LINE if ( y >= N and isPrime ( y ) ) : NEW_LINE INDENT return y NEW_LINE DEDENT DEDENT DEDENT print ( primePalindrome ( 112 ) ) NEW_LINE |
Number of integral solutions for equation x = b * ( sumofdigits ( x ) ^ a ) + c | This function returns the sum of the digits of a number ; This function creates the array of valid numbers ; this computes s ( x ) ^ a ; this gives the result of equation ; checking if the sum same as i ; counter to keep track of numbers ; resultant array ; prints the number ; Driver Code ; calculate which value of x are possible | def getsum ( a ) : NEW_LINE INDENT r = 0 NEW_LINE sum = 0 NEW_LINE while ( a > 0 ) : NEW_LINE INDENT r = a % 10 NEW_LINE sum = sum + r NEW_LINE a = a // 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def value ( a , b , c ) : NEW_LINE INDENT x = 0 NEW_LINE q = 0 NEW_LINE w = 0 NEW_LINE v = [ ] NEW_LINE for i in range ( 1 , 82 ) : NEW_LINE INDENT no = pow ( i , a ) NEW_LINE no = b * no + c NEW_LINE if ( no > 0 and no < 1000000000 ) : NEW_LINE INDENT x = getsum ( no ) NEW_LINE if ( x == i ) : NEW_LINE INDENT q += 1 NEW_LINE v . append ( no ) NEW_LINE w += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( len ( v ) ) : NEW_LINE INDENT print ( v [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 2 NEW_LINE b = 2 NEW_LINE c = - 1 NEW_LINE value ( a , b , c ) NEW_LINE DEDENT |
Cunningham chain | Function to print Cunningham chain of the second kind ; Iterate till all elements are printed ; check prime or not ; Driver Code | def print_t ( p0 ) : NEW_LINE INDENT i = 0 ; NEW_LINE while ( True ) : NEW_LINE INDENT flag = 1 ; NEW_LINE x = pow ( 2 , i ) ; NEW_LINE p1 = x * p0 - ( x - 1 ) ; NEW_LINE for k in range ( 2 , p1 ) : NEW_LINE INDENT if ( p1 % k == 0 ) : NEW_LINE INDENT flag = 0 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT print ( p1 , end = " β " ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT DEDENT p0 = 19 ; NEW_LINE print_t ( p0 ) ; NEW_LINE |
Count number of right triangles possible with a given perimeter | Function to return the count ; making a list to store ( a , b ) pairs ; no triangle if p is odd ; make ( a , b ) pair in sorted order ; check to avoid duplicates ; store the new pair ; Driver Code | def countTriangles ( p ) : NEW_LINE INDENT store = [ ] NEW_LINE if p % 2 != 0 : return 0 NEW_LINE else : NEW_LINE INDENT count = 0 NEW_LINE for b in range ( 1 , p // 2 ) : NEW_LINE INDENT a = p / 2 * ( ( p - 2 * b ) / ( p - b ) ) NEW_LINE inta = int ( a ) NEW_LINE if ( a == inta ) : NEW_LINE INDENT ab = tuple ( sorted ( ( inta , b ) ) ) NEW_LINE if ab not in store : NEW_LINE INDENT count += 1 NEW_LINE store . append ( ab ) NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT DEDENT p = 840 NEW_LINE print ( " number β of β right β triangles β = β " + str ( countTriangles ( p ) ) ) NEW_LINE |
Count pairs with Bitwise AND as ODD number | Python program to count pairs with Odd AND ; Count total odd numbers ; return count of even pair ; Driver Code ; calling function findOddPair and print number of odd pair | def findOddPair ( A , N ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( 0 , N - 1 ) : NEW_LINE INDENT if ( ( A [ i ] % 2 == 1 ) ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return count * ( count - 1 ) / 2 NEW_LINE DEDENT a = [ 5 , 1 , 3 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( int ( findOddPair ( a , n ) ) ) NEW_LINE |
Surd number | define a isSurd function which Returns true if x is Surd number . ; Try all powers of i ; Driver code | def isSurd ( n ) : NEW_LINE INDENT i = 2 NEW_LINE for i in range ( 2 , ( i * i ) + 1 ) : NEW_LINE INDENT j = i NEW_LINE while ( j < n ) : NEW_LINE INDENT j = j * i NEW_LINE DEDENT if ( j == n ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 15 NEW_LINE if ( isSurd ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Program to find last two digits of 2 ^ n | Find the first digit ; Get the last digit from the number ; Remove last digit from number ; Get the last digit from the number ( last second of num ) ; Take last digit to ten 's position i.e. last second digit ; Add the value of ones and tens to make it complete 2 digit number ; return the first digit ; Driver Code ; pow function used | def LastTwoDigit ( num ) : NEW_LINE INDENT one = num % 10 NEW_LINE num //= 10 NEW_LINE tens = num % 10 NEW_LINE tens *= 10 NEW_LINE num = tens + one NEW_LINE return num NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 NEW_LINE num = 1 NEW_LINE num = pow ( 2 , n ) ; NEW_LINE print ( " Last β " + str ( 2 ) + " β digits β of β " + str ( 2 ) + " ^ " + str ( n ) + " β = β " , end = " " ) NEW_LINE print ( LastTwoDigit ( num ) ) NEW_LINE DEDENT |
Program to find last two digits of 2 ^ n | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; function to calculate number of digits in x ; function to print last 2 digits of 2 ^ n ; Generating 10 ^ 2 ; Calling modular exponentiation ; Printing leftmost zeros . Since ( 2 ^ n ) % 2 can have digits less then 2. 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 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 LastTwoDigit ( n ) : NEW_LINE INDENT print ( " Last β " + str ( 2 ) + " β digits β of β " + str ( 2 ) , end = " " ) NEW_LINE print ( " ^ " + str ( n ) + " β = β " , end = " " ) NEW_LINE temp = 1 NEW_LINE for i in range ( 1 , 3 ) : NEW_LINE INDENT temp *= 10 NEW_LINE DEDENT temp = power ( 2 , n , temp ) NEW_LINE for i in range ( 2 - numberOfDigits ( temp ) ) : NEW_LINE INDENT print ( 0 , end = " " ) NEW_LINE DEDENT if temp : NEW_LINE INDENT print ( temp ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 72 NEW_LINE LastTwoDigit ( n ) NEW_LINE DEDENT |
Find gcd ( a ^ n , c ) where a , n and c can vary from 1 to 10 ^ 9 | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; Finds GCD of a and b ; Finds GCD of a ^ n and c ; check if c is a divisor of a ; First compute ( a ^ n ) % c ; Now simply return GCD of modulo power and c . ; Driver code | def modPower ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def gcdPow ( a , n , c ) : NEW_LINE INDENT if ( a % c == 0 ) : NEW_LINE INDENT return c NEW_LINE DEDENT modexpo = modPower ( a , n , c ) NEW_LINE return gcd ( modexpo , c ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 10248585 NEW_LINE n = 1000000 NEW_LINE c = 12564 NEW_LINE print ( gcdPow ( a , n , c ) ) NEW_LINE DEDENT |
Number of sub arrays with odd sum | Python 3 code to find count of sub - arrays with odd sum ; Find sum of all subarrays and increment result if sum is odd ; Driver code | def countOddSum ( ar , n ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT val = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT val = val + ar [ j ] NEW_LINE if ( val % 2 != 0 ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT DEDENT return ( result ) NEW_LINE DEDENT ar = [ 5 , 4 , 4 , 5 , 1 , 3 ] NEW_LINE print ( " The β Number β of β Subarrays " , " with β odd " , end = " " ) NEW_LINE print ( " β sum β is β " + str ( countOddSum ( ar , 6 ) ) ) NEW_LINE |
Number of sub arrays with odd sum | Python 3 proggram to find count of sub - arrays with odd sum ; A temporary array of size 2. temp [ 0 ] is going to store count of even subarrays and temp [ 1 ] count of odd . temp [ 0 ] is initialized as 1 because there is a single odd element is also counted as a subarray ; Initialize count . sum is sum of elements under modulo 2 and ending with arr [ i ] . ; i ' th β iteration β computes β β sum β of β arr [ 0 . . i ] β under β β modulo β 2 β and β increments β β even / odd β count β according β β to β sum ' s value ; 2 is added to handle negative numbers ; Increment even / odd count ; An odd can be formed by even - odd pair ; Driver code | def countOddSum ( ar , n ) : NEW_LINE INDENT temp = [ 1 , 0 ] NEW_LINE result = 0 NEW_LINE val = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT val = ( ( val + ar [ i ] ) % 2 + 2 ) % 2 NEW_LINE temp [ val ] += 1 NEW_LINE DEDENT result = ( temp [ 0 ] * temp [ 1 ] ) NEW_LINE return ( result ) NEW_LINE DEDENT ar = [ 5 , 4 , 4 , 5 , 1 , 3 ] NEW_LINE print ( " The β Number β of β Subarrays " " β with β odd β sum β is β " + str ( countOddSum ( ar , 6 ) ) ) NEW_LINE |
Program to print factors of a number in pairs | Python 3 program to print prime factors in pairs . ; Driver code | def printPFsInPairs ( n ) : NEW_LINE INDENT for i in range ( 1 , int ( pow ( n , 1 / 2 ) ) + 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT print ( str ( i ) + " * " + str ( int ( n / i ) ) ) NEW_LINE DEDENT DEDENT DEDENT n = 24 NEW_LINE printPFsInPairs ( n ) NEW_LINE |
Sum of elements in range L | Function to find the sum between L and R ; array created ; fill the first half of array ; fill the second half of array ; find the sum between range ; Driver Code | def rangesum ( n , l , r ) : NEW_LINE INDENT arr = [ 0 ] * n ; NEW_LINE c = 1 ; i = 0 ; NEW_LINE while ( c <= n ) : NEW_LINE INDENT arr [ i ] = c ; NEW_LINE i += 1 ; NEW_LINE c += 2 ; NEW_LINE DEDENT c = 2 ; NEW_LINE while ( c <= n ) : NEW_LINE INDENT arr [ i ] = c ; NEW_LINE i += 1 ; NEW_LINE c += 2 ; NEW_LINE DEDENT sum = 0 ; NEW_LINE for i in range ( l - 1 , r , 1 ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 ; NEW_LINE l , r = 1 , 11 ; NEW_LINE print ( rangesum ( n , l , r ) ) ; NEW_LINE DEDENT |
Sum of elements in range L | Function to calculate the sum if n is even ; Both l and r are to the left of mid ; First and last element ; Total number of terms in the sequence is r - l + 1 ; Use of formula derived ; Both l and r are to the right of mid ; First and last element ; Use of formula derived ; Left is to the left of mid and right is to the right of mid ; Take two sums i . e left and right differently and add ; First and last element ; total terms ; no of terms ; The first even number is 2 ; The last element is ; formula applied ; Function to calculate the sum if n is odd ; Take ceil value if n is odd ; Both l and r are to the left of mid ; First and last element ; number of terms ; formula ; both l and r are to the right of mid ; first and last term , ; no of terms ; formula used ; If l is on left and r on right ; calculate separate sums ; first half ; calculate terms ; second half ; add both halves ; Function to find the sum between L and R ; If n is even ; If n is odd ; Driver Code | def sumeven ( n , l , r ) : NEW_LINE INDENT sum = 0 NEW_LINE mid = n // 2 NEW_LINE if ( r <= mid ) : NEW_LINE INDENT first = ( 2 * l - 1 ) NEW_LINE last = ( 2 * r - 1 ) NEW_LINE no_of_terms = r - l + 1 NEW_LINE sum = ( ( no_of_terms ) * ( ( first + last ) ) ) // 2 NEW_LINE DEDENT elif ( l >= mid ) : NEW_LINE INDENT first = ( 2 * ( l - n // 2 ) ) NEW_LINE last = ( 2 * ( r - n // 2 ) ) NEW_LINE no_of_terms = r - l + 1 NEW_LINE sum = ( ( no_of_terms ) * ( ( first + last ) ) ) // 2 NEW_LINE DEDENT else : NEW_LINE INDENT sumleft , sumright = 0 , 0 NEW_LINE first_term1 = ( 2 * l - 1 ) NEW_LINE last_term1 = ( 2 * ( n // 2 ) - 1 ) NEW_LINE no_of_terms1 = n // 2 - l + 1 NEW_LINE sumleft = ( ( ( no_of_terms1 ) * ( ( first_term1 + last_term1 ) ) ) // 2 ) NEW_LINE first_term2 = 2 NEW_LINE last_term2 = ( 2 * ( r - n // 2 ) ) NEW_LINE no_of_terms2 = r - mid NEW_LINE sumright = ( ( ( no_of_terms2 ) * ( ( first_term2 + last_term2 ) ) ) // 2 ) NEW_LINE sum = ( sumleft + sumright ) ; NEW_LINE DEDENT return sum NEW_LINE DEDENT def sumodd ( n , l , r ) : NEW_LINE INDENT mid = n // 2 + 1 ; NEW_LINE sum = 0 NEW_LINE if ( r <= mid ) : NEW_LINE INDENT first = ( 2 * l - 1 ) NEW_LINE last = ( 2 * r - 1 ) NEW_LINE no_of_terms = r - l + 1 NEW_LINE sum = ( ( ( no_of_terms ) * ( ( first + last ) ) ) // 2 ) NEW_LINE DEDENT elif ( l > mid ) : NEW_LINE INDENT first = ( 2 * ( l - mid ) ) NEW_LINE last = ( 2 * ( r - mid ) ) NEW_LINE no_of_terms = r - l + 1 NEW_LINE sum = ( ( ( no_of_terms ) * ( ( first + last ) ) ) // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT sumleft , sumright = 0 , 0 NEW_LINE first_term1 = ( 2 * l - 1 ) NEW_LINE last_term1 = ( 2 * mid - 1 ) NEW_LINE no_of_terms1 = mid - l + 1 NEW_LINE sumleft = ( ( ( no_of_terms1 ) * ( ( first_term1 + last_term1 ) ) ) // 2 ) NEW_LINE first_term2 = 2 NEW_LINE last_term2 = ( 2 * ( r - mid ) ) NEW_LINE no_of_terms2 = r - mid NEW_LINE sumright = ( ( ( no_of_terms2 ) * ( ( first_term2 + last_term2 ) ) ) // 2 ) NEW_LINE sum = ( sumleft + sumright ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def rangesum ( n , l , r ) : NEW_LINE INDENT sum = 0 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT return sumeven ( n , l , r ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return sumodd ( n , l , r ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 12 NEW_LINE l = 1 NEW_LINE r = 11 ; NEW_LINE print ( rangesum ( n , l , r ) ) NEW_LINE DEDENT |
Program to find the Interior and Exterior Angle of a Regular Polygon | function to find the interior and exterior angle ; formula to find the interior angle ; formula to find the exterior angle ; Displaying the output ; Driver code ; Function calling | def findAngle ( n ) : NEW_LINE INDENT interiorAngle = int ( ( n - 2 ) * 180 / n ) NEW_LINE exteriorAngle = int ( 360 / n ) NEW_LINE print ( " Interior β angle : β " , interiorAngle ) NEW_LINE print ( " Exterior β angle : β " , exteriorAngle ) NEW_LINE DEDENT n = 10 NEW_LINE findAngle ( n ) NEW_LINE |
Program to calculate distance between two points in 3 D | Python program to find distance between two points in 3 D . ; Function to find distance ; Driver Code ; function call for distance | import math NEW_LINE def distance ( x1 , y1 , z1 , x2 , y2 , z2 ) : NEW_LINE INDENT d = math . sqrt ( math . pow ( x2 - x1 , 2 ) + math . pow ( y2 - y1 , 2 ) + math . pow ( z2 - z1 , 2 ) * 1.0 ) NEW_LINE print ( " Distance β is β " ) NEW_LINE print ( d ) NEW_LINE DEDENT x1 = 2 NEW_LINE y1 = - 5 NEW_LINE z1 = 7 NEW_LINE x2 = 3 NEW_LINE y2 = 4 NEW_LINE z2 = 5 NEW_LINE distance ( x1 , y1 , z1 , x2 , y2 , z2 ) NEW_LINE |
Check if the large number formed is divisible by 41 or not | Check if a number is divisible by 41 or not ; array to store all the digits ; base values ; calculate remaining digits ; calculate answer ; check for divisibility ; Driver Code | def DivisibleBy41 ( first , second , c , n ) : NEW_LINE INDENT digit = [ 0 ] * n NEW_LINE digit [ 0 ] = first NEW_LINE digit [ 1 ] = second NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT digit [ i ] = ( digit [ i - 1 ] * c + digit [ i - 2 ] ) % 10 NEW_LINE DEDENT ans = digit [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ans = ( ans * 10 + digit [ i ] ) % 41 NEW_LINE DEDENT if ( ans % 41 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT first = 1 NEW_LINE second = 2 NEW_LINE c = 1 NEW_LINE n = 3 NEW_LINE if ( DivisibleBy41 ( first , second , c , n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Program to print pentatope numbers upto Nth term | Function to generate nth tetrahedral number ; Function to print pentatope number series upto nth term . ; Initialize prev as 0. It store the sum of all previously generated pentatope numbers ; Loop to print pentatope series ; Find ith tetrahedral number ; Add ith tetrahedral number to sum of all previously generated tetrahedral number to get ith pentatope number ; Update sum of all previously generated tetrahedral number ; Driver code ; Function call to print pentatope number series | def findTetrahedralNumber ( n ) : NEW_LINE INDENT return ( int ( ( n * ( n + 1 ) * ( n + 2 ) ) / 6 ) ) NEW_LINE DEDENT def printSeries ( n ) : NEW_LINE INDENT prev = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT curr = findTetrahedralNumber ( i ) NEW_LINE curr = curr + prev ; NEW_LINE print ( curr , end = ' β ' ) NEW_LINE prev = curr NEW_LINE DEDENT DEDENT n = 10 NEW_LINE printSeries ( n ) NEW_LINE |
Program to print pentatope numbers upto Nth term | Function to print pentatope series up to nth term ; Loop to print pentatope number series ; calculate and print ith pentatope number ; Driver code ; Function call to print pentatope number series | def printSeries ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT num = int ( i * ( i + 1 ) * ( i + 2 ) * ( i + 3 ) // 24 ) NEW_LINE print ( num , end = ' β ' ) ; NEW_LINE DEDENT DEDENT n = 10 NEW_LINE printSeries ( n ) NEW_LINE |
Find unique pairs such that each element is less than or equal to N | Finding the number of unique pairs ; Using the derived formula ; Printing the unique pairs ; Driver Code | def No_Of_Pairs ( N ) : NEW_LINE INDENT i = 1 ; NEW_LINE while ( ( i * i * i ) + ( 2 * i * i ) + i <= N ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT return ( i - 1 ) ; NEW_LINE DEDENT def print_pairs ( pairs ) : NEW_LINE INDENT i = 1 ; NEW_LINE mul = 0 ; NEW_LINE for i in range ( 1 , pairs + 1 ) : NEW_LINE INDENT mul = i * ( i + 1 ) ; NEW_LINE print ( " Pair β no . " , i , " β - - > β ( " , ( mul * i ) , " , β " , mul * ( i + 1 ) , " ) " ) ; NEW_LINE DEDENT DEDENT N = 500 ; NEW_LINE i = 1 ; NEW_LINE pairs = No_Of_Pairs ( N ) ; NEW_LINE print ( " No . β of β pairs β = β " , pairs ) ; NEW_LINE print_pairs ( pairs ) ; NEW_LINE |
Program to print tetrahedral numbers upto Nth term | function to generate nth triangular number ; function to print tetrahedral number series up to n ; Initialize prev as 0. It stores the sum of all previously generated triangular number ; Loop to print series ; Find ith triangular number ; Add ith triangular number to sum of all previously generated triangular number to get ith tetrahedral number ; Update sum of all previously generated triangular number ; Driver code ; function call to print series | def findTriangularNumber ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) ) / 2 NEW_LINE DEDENT def printSeries ( n ) : NEW_LINE INDENT prev = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT curr = findTriangularNumber ( i ) NEW_LINE curr = int ( curr + prev ) NEW_LINE print ( curr , end = ' β ' ) NEW_LINE prev = curr NEW_LINE DEDENT DEDENT n = 10 NEW_LINE printSeries ( n ) NEW_LINE |
Program to print tetrahedral numbers upto Nth term | function to print tetrahedral series up to n ; loop to print series ; Calculate and print ith Tetrahedral number ; Driver code ; function call to print series | def printSeries ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT num = i * ( i + 1 ) * ( i + 2 ) // 6 NEW_LINE print ( num , end = ' β ' ) NEW_LINE DEDENT DEDENT n = 10 NEW_LINE printSeries ( n ) NEW_LINE |
Number of odd and even results for every value of x in range [ min , max ] after performing N steps | Function that prints the number of odd and even results ; If constant at layer i is even , beven is True , otherwise False . If the coefficient of x at layer i is even , aeven is True , otherwise False . ; If any of the coefficients at any layer is found to be even , then the product of all the coefficients will always be even . ; Checking whether the constant added after all layers is even or odd . ; Assuming input x is even . ; Assuming input x is odd . ; Displaying the counts . ; Driver Code | def count_even_odd ( min , max , steps ) : NEW_LINE INDENT beven = True NEW_LINE aeven = False NEW_LINE n = 2 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT a = steps [ i ] [ 0 ] NEW_LINE b = steps [ i ] [ 1 ] NEW_LINE if ( not ( aeven or a & 1 ) ) : NEW_LINE INDENT aeven = True NEW_LINE DEDENT if ( beven ) : NEW_LINE INDENT if ( b & 1 ) : NEW_LINE INDENT beven = False NEW_LINE DEDENT DEDENT elif ( not ( a & 1 ) ) : NEW_LINE INDENT if ( not ( b & 1 ) ) : NEW_LINE INDENT beven = True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( b & 1 ) : NEW_LINE INDENT beven = True NEW_LINE DEDENT DEDENT DEDENT if ( beven ) : NEW_LINE INDENT even = ( int ( max / 2 ) - int ( ( min - 1 ) / 2 ) ) NEW_LINE odd = 0 NEW_LINE DEDENT else : NEW_LINE INDENT even = ( int ( max / 2 ) - int ( ( min - 1 ) / 2 ) ) NEW_LINE odd = 0 NEW_LINE DEDENT if ( not ( beven ^ aeven ) ) : NEW_LINE INDENT even += ( max - min + 1 - int ( max / 2 ) + int ( ( min - 1 ) / 2 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT odd += ( max - min + 1 - int ( max / 2 ) + int ( ( min - 1 ) / 2 ) ) NEW_LINE DEDENT print ( " even β = β " , even , " , β odd β = β " , odd , sep = " " ) NEW_LINE DEDENT min = 1 NEW_LINE max = 4 NEW_LINE steps = [ [ 1 , 2 ] , [ 3 , 4 ] ] NEW_LINE count_even_odd ( min , max , steps ) NEW_LINE |
Maximum number of ones in a N * N matrix with given constraints | Function that returns the maximum number of ones ; Minimum number of zeroes ; Totol cells = square of the size of the matrices ; Initialising the answer ; Initialising the variables | def getMaxOnes ( n , x ) : NEW_LINE INDENT zeroes = ( int ) ( n / x ) ; NEW_LINE zeroes = zeroes * zeroes ; NEW_LINE total = n * n ; NEW_LINE ans = total - zeroes ; NEW_LINE return ans ; NEW_LINE DEDENT n = 5 ; NEW_LINE x = 2 ; NEW_LINE print ( getMaxOnes ( n , x ) ) ; NEW_LINE |
Minimum operations required to make all the elements distinct in an array | Function that returns minimum number of changes ; Hash - table to store frequency ; Increase the frequency of elements ; Traverse in the map to sum up the ( occurrences - 1 ) of duplicate elements ; Driver Code | def minimumOperations ( a , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ a [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ a [ i ] ] = 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for it in mp : NEW_LINE INDENT if ( mp [ it ] > 1 ) : NEW_LINE INDENT count += mp [ it ] - 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT a = [ 2 , 1 , 2 , 3 , 3 , 4 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( minimumOperations ( a , n ) ) NEW_LINE |
Check if a M | Python 3 program to check if M - th fibonacci divides N - th fibonacci ; exceptional case for F ( 2 ) ; if none of the above cases , hence not divisible ; Driver Code | def check ( n , m ) : NEW_LINE INDENT if ( n == 2 or m == 2 or n % m == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT m = 3 NEW_LINE n = 9 NEW_LINE check ( n , m ) NEW_LINE |
Surface Area and Volume of Hexagonal Prism | Python3 program to find the Surface Area and Volume of Hexagonal Prism . ; Function to calculate Surface area ; Formula to calculate surface area ; Display surface area ; Function to calculate Volume ; formula to calculate Volume ; Display Volume ; Driver Code ; surface area function call ; volume function call | import math NEW_LINE def findSurfaceArea ( a , h ) : NEW_LINE INDENT Area = 0 ; NEW_LINE Area = ( 6 * a * h + 3 * math . sqrt ( 3 ) * a * a ) ; NEW_LINE print ( " Surface β Area : " , round ( Area , 3 ) ) ; NEW_LINE DEDENT def findVolume ( a , h ) : NEW_LINE INDENT Volume = 0 ; NEW_LINE Volume = ( 3 * math . sqrt ( 3 ) * a * a * h / 2 ) ; NEW_LINE print ( " Volume : " , round ( Volume , 3 ) ) ; NEW_LINE DEDENT a = 5 ; NEW_LINE h = 10 ; NEW_LINE findSurfaceArea ( a , h ) ; NEW_LINE findVolume ( a , h ) ; NEW_LINE |
Minimum number of mails required to distribute all the questions | Python3 code to find the minimum number of mails ; Function returns the min no of mails required ; Using the formula derived above ; no of questions ; no of students ; maximum no of questions a mail can hold ; Calling function | import math NEW_LINE def MinimumMail ( n , k , x ) : NEW_LINE INDENT m = ( ( n - 1 ) + int ( math . ceil ( ( n - 1 ) * 1.0 / x ) * ( n - 1 ) + math . ceil ( n * 1.0 / x ) * ( k - n ) ) ) ; NEW_LINE return m ; NEW_LINE DEDENT N = 4 ; NEW_LINE K = 9 ; NEW_LINE X = 2 ; NEW_LINE print ( MinimumMail ( N , K , X ) ) ; NEW_LINE |
Program to find the Area of an Ellipse | Function to find area of an ellipse . ; formula to find the area of an Ellipse . ; Display the result ; Driver code | def findArea ( a , b ) : NEW_LINE INDENT Area = 3.142 * a * b ; NEW_LINE print ( " Area : " , round ( Area , 2 ) ) ; NEW_LINE DEDENT a = 5 ; NEW_LINE b = 4 ; NEW_LINE findArea ( a , b ) ; NEW_LINE |
Compute power of power k times % m | Python3 program for computing x ^ x ^ x ^ x . . % m ; Function to compute the given value ; compute power k times ; Driver Code ; Calling function | import math NEW_LINE def calculate ( x , k , m ) : NEW_LINE INDENT result = x ; NEW_LINE k = k - 1 ; NEW_LINE while ( k ) : NEW_LINE INDENT result = math . pow ( result , x ) ; NEW_LINE if ( result > m ) : NEW_LINE INDENT result = result % m ; NEW_LINE DEDENT k = k - 1 ; NEW_LINE DEDENT return int ( result ) ; NEW_LINE DEDENT x = 5 ; NEW_LINE k = 2 ; NEW_LINE m = 3 ; NEW_LINE print ( calculate ( x , k , m ) ) ; NEW_LINE |
Recursive program to check if number is palindrome or not | Recursive function that returns the reverse of digits ; base case ; stores the reverse of a number ; Driver Code | def rev ( n , temp ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return temp ; NEW_LINE DEDENT temp = ( temp * 10 ) + ( n % 10 ) ; NEW_LINE return rev ( n / 10 , temp ) ; NEW_LINE DEDENT n = 121 ; NEW_LINE temp = rev ( n , 0 ) ; NEW_LINE if ( temp != n ) : NEW_LINE INDENT print ( " yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " no " ) ; NEW_LINE DEDENT |
Program to find greater value between a ^ n and b ^ n | Python3 code for finding greater between the a ^ n and b ^ n ; Function to find the greater value ; If n is even ; Driver code | import math NEW_LINE def findGreater ( a , b , n ) : NEW_LINE INDENT if ( ( n & 1 ) > 0 ) : NEW_LINE INDENT a = abs ( a ) ; NEW_LINE b = abs ( b ) ; NEW_LINE DEDENT if ( a == b ) : NEW_LINE INDENT print ( " a ^ n β is β equal β to β b ^ n " ) ; NEW_LINE DEDENT elif ( a > b ) : NEW_LINE INDENT print ( " a ^ n β is β greater β than β b ^ n " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " b ^ n β is β greater β than β a ^ n " ) ; NEW_LINE DEDENT DEDENT a = 12 ; NEW_LINE b = 24 ; NEW_LINE n = 5 ; NEW_LINE findGreater ( a , b , n ) ; NEW_LINE |
Print first n Fibonacci Numbers using direct formula | Python3 code to print fibonacci numbers till n using direct formula . ; Function to calculate fibonacci using recurrence relation formula ; Using direct formula ; Driver code | import math NEW_LINE def fibonacci ( n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT fib = ( ( pow ( ( 1 + math . sqrt ( 5 ) ) , i ) - pow ( ( 1 - math . sqrt ( 5 ) ) , i ) ) / ( pow ( 2 , i ) * math . sqrt ( 5 ) ) ) ; NEW_LINE print ( int ( fib ) , end = " β " ) ; NEW_LINE DEDENT DEDENT n = 8 ; NEW_LINE fibonacci ( n ) ; NEW_LINE |
Centered Hexadecagonal Number | centered hexadecagonal function ; Formula to calculate nth centered hexadecagonal number ; Driver Code | def center_hexadecagonal_num ( n ) : NEW_LINE INDENT return 8 * n * n - 8 * n + 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 NEW_LINE print ( n , " nd β centered β hexadecagonal β " + " number β : β " , center_hexadecagonal_num ( n ) ) NEW_LINE n = 12 NEW_LINE print ( n , " th β centered β hexadecagonal β " + " number β : β " , center_hexadecagonal_num ( n ) ) NEW_LINE DEDENT |
Check if the n | Python3 Program to check if the nth is odd or even in a sequence where each term is sum of previous two term ; Return if the nth term is even or odd . ; Return true if odd ; Driver Code | MAX = 100 ; NEW_LINE def findNature ( a , b , n ) : NEW_LINE INDENT seq = [ 0 ] * MAX ; NEW_LINE seq [ 0 ] = a ; NEW_LINE seq [ 1 ] = b ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT seq [ i ] = seq [ i - 1 ] + seq [ i - 2 ] ; NEW_LINE DEDENT return ( seq [ n ] & 1 ) ; NEW_LINE DEDENT a = 2 ; NEW_LINE b = 4 ; NEW_LINE n = 3 ; NEW_LINE if ( findNature ( a , b , n ) ) : NEW_LINE INDENT print ( " Odd " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Even " ) ; NEW_LINE DEDENT |
Program to compare m ^ n and n ^ m | Python3 program to compare which is greater m ^ n or n ^ m ; function to compare m ^ n and n ^ m ; m ^ n ; n ^ m ; Driver Code ; function call to compare m ^ n and n ^ m | import math NEW_LINE def check ( m , n ) : NEW_LINE INDENT RHS = m * math . log ( n ) ; NEW_LINE LHS = n * math . log ( m ) ; NEW_LINE if ( LHS > RHS ) : NEW_LINE INDENT print ( " m ^ n β > β n ^ m " ) ; NEW_LINE DEDENT elif ( LHS < RHS ) : NEW_LINE INDENT print ( " m ^ n β < β n ^ m " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " m ^ n β = β n ^ m " ) ; NEW_LINE DEDENT DEDENT m = 987654321 ; NEW_LINE n = 123456987 ; NEW_LINE check ( m , n ) ; NEW_LINE |
LCM of two large numbers | Python3 program to find LCM of two large numbers ; Function to calculate LCM of two large numbers ; Convert string ' a ' and ' b ' into Integer ; Calculate multiplication of both integers ; Calculate gcd of two integers ; Calculate lcm using formula : lcm * gcd = x * y ; Driver Code ; Input ' a ' and ' b ' are in the form of strings | import math NEW_LINE def lcm ( a , b ) : NEW_LINE INDENT s = int ( a ) NEW_LINE s1 = int ( b ) NEW_LINE mul = s * s1 NEW_LINE gcd = math . gcd ( s , s1 ) NEW_LINE lcm = mul // gcd NEW_LINE return lcm NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = "36594652830916364940473625749407" NEW_LINE b = "448507083624364748494746353648484939" NEW_LINE print ( lcm ( a , b ) ) NEW_LINE DEDENT |
Find the GCD that lies in given range | Return the greatest common divisor of two numbers ; Return the gretest common divisor of a and b which lie in the given range . ; Loop from 1 to sqrt ( GCD ( a , b ) . ; if i divides the GCD ( a , b ) , then find maximum of three numbers res , i and g / i ; Driver Code | def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT return gcd ( b , a % b ) ; NEW_LINE DEDENT def maxDivisorRange ( a , b , l , h ) : NEW_LINE INDENT g = gcd ( a , b ) ; NEW_LINE res = - 1 ; NEW_LINE i = l ; NEW_LINE while ( i * i <= g and i <= h ) : NEW_LINE INDENT if ( g % i == 0 ) : NEW_LINE INDENT res = max ( res , max ( i , g / i ) ) ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT return int ( res ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 3 ; NEW_LINE b = 27 ; NEW_LINE l = 1 ; NEW_LINE h = 5 ; NEW_LINE print ( maxDivisorRange ( a , b , l , h ) ) ; NEW_LINE DEDENT |
Number expressed as sum of five consecutive integers | function to check if a number can be expressed as sum of five consecutive integer . ; if n is 0 ; if n is positive , increment loop by 1. ; if n is negative , decrement loop by 1. ; Running loop from 0 to n - 4 ; check if sum of five consecutive integer is equal to n . ; Driver Code | def checksum ( n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT print ( " - 2 β - 1 β 0 β 1 β 2" ) NEW_LINE return 0 NEW_LINE DEDENT inc = 0 NEW_LINE if n > 0 : NEW_LINE INDENT inc = 1 NEW_LINE DEDENT else : NEW_LINE INDENT inc = - 1 NEW_LINE DEDENT for i in range ( 0 , n - 3 , inc ) : NEW_LINE INDENT if i + i + 1 + i + 2 + i + 3 + i + 4 == n : NEW_LINE INDENT print ( i , " β " , i + 1 , " β " , i + 2 , " β " , i + 3 , " β " , i + 4 ) NEW_LINE return 0 NEW_LINE DEDENT DEDENT print ( " - 1" ) NEW_LINE DEDENT n = 15 NEW_LINE checksum ( n ) NEW_LINE |
Number expressed as sum of five consecutive integers | function to check if a number can be expressed as sum of five consecutive integers . ; if n is multiple of 5 ; else print " - 1" . ; Driver Code | def checksum ( n ) : NEW_LINE INDENT n = int ( n ) NEW_LINE if n % 5 == 0 : NEW_LINE INDENT print ( int ( n / 5 - 2 ) , " β " , int ( n / 5 - 1 ) , " β " , int ( n / 5 ) , " β " , int ( n / 5 + 1 ) , " β " , int ( n / 5 + 2 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT n = 15 NEW_LINE checksum ( n ) NEW_LINE |
Number of Transpositions in a Permutation | Python Program to find the number of transpositions in a permutation ; This array stores which element goes to which position ; This function returns the size of a component cycle ; If it is already visited ; This functio returns the number of transpositions in the permutation ; Initializing visited [ ] array ; building the goesTo [ ] array ; Driver Code | N = 1000001 NEW_LINE visited = [ 0 ] * N ; NEW_LINE goesTo = [ 0 ] * N ; NEW_LINE def dfs ( i ) : NEW_LINE INDENT if ( visited [ i ] == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT visited [ i ] = 1 ; NEW_LINE x = dfs ( goesTo [ i ] ) ; NEW_LINE return ( x + 1 ) ; NEW_LINE DEDENT def noOfTranspositions ( P , n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT visited [ i ] = 0 ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT goesTo [ P [ i ] ] = i + 1 ; NEW_LINE DEDENT transpositions = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( visited [ i ] == 0 ) : NEW_LINE INDENT ans = dfs ( i ) ; NEW_LINE transpositions += ans - 1 ; NEW_LINE DEDENT DEDENT return transpositions ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT permutation = [ 5 , 1 , 4 , 3 , 2 ] ; NEW_LINE n = len ( permutation ) ; NEW_LINE print ( noOfTranspositions ( permutation , n ) ) ; NEW_LINE DEDENT |
n | Function to find the nth term of series ; Loop to add 4 th powers ; Driver code | def sumOfSeries ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = ans + i * i * i * i NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 4 NEW_LINE print ( sumOfSeries ( n ) ) NEW_LINE |
Number of unmarked integers in a special sieve | Python3 Program to determine the number of unmarked integers in a special sieve ; Driver Code | def countUnmarked ( N ) : NEW_LINE INDENT if ( N % 2 == 0 ) : NEW_LINE INDENT return N / 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT return N / 2 + 1 ; NEW_LINE DEDENT DEDENT N = 4 ; NEW_LINE print ( " Number β of β unmarked β elements : " , int ( countUnmarked ( N ) ) ) ; NEW_LINE |
Sum of series 1 * 1 ! + 2 * 2 ! + β¦β¦ . . + n * n ! | Python program to find sum of the series . ; Function to calculate required series ; Drivers code | def factorial ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def calculateSeries ( n ) : NEW_LINE INDENT return factorial ( n + 1 ) - 1 NEW_LINE DEDENT n = 3 NEW_LINE print ( calculateSeries ( n ) ) NEW_LINE |
Sum of series 1 * 1 * 2 ! + 2 * 2 * 3 ! + β¦β¦ . . + n * n * ( n + 1 ) ! | Python program to find sum of the series . ; Function to calculate required series ; Driver code | import math NEW_LINE def factorial ( n ) : NEW_LINE INDENT res = 1 NEW_LINE i = 2 NEW_LINE for i in ( n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def calculateSeries ( n ) : NEW_LINE INDENT return ( 2 + ( n * n + n - 2 ) * math . factorial ( n + 1 ) ) NEW_LINE DEDENT n = 3 NEW_LINE print ( calculateSeries ( n ) ) NEW_LINE |
Aspiring Number | Function to calculate sum of all proper divisors ; 1 is a proper divisor ; Note that this loop runs till square root of n ; If divisors are equal , take only one of them ; Otherwise take both ; Calculate sum of all proper divisors only ; Function to get last number of Aliquot Sequence . ; Calculate next term from previous term ; Returns true if n is perfect ; To store sum of divisors ; Find all divisors and add them ; If sum of divisors is equal to n , then n is a perfect number ; Returns true if n is aspiring else returns false ; Checking condition for aspiring ; Driver Code | def getSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , int ( ( n ) ** ( 1 / 2 ) ) + 1 ) : NEW_LINE INDENT if not n % i : NEW_LINE if n // i == i : NEW_LINE INDENT sum += i NEW_LINE DEDENT else : NEW_LINE INDENT sum += i NEW_LINE sum += ( n // i ) NEW_LINE DEDENT DEDENT return sum - n NEW_LINE DEDENT def getAliquot ( n ) : NEW_LINE INDENT s = set ( ) NEW_LINE s . add ( n ) NEW_LINE next = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT n = getSum ( n ) NEW_LINE if n not in s : NEW_LINE return n NEW_LINE s . add ( n ) NEW_LINE DEDENT return 0 NEW_LINE DEDENT def isPerfect ( n ) : NEW_LINE INDENT sum = 1 NEW_LINE for i in range ( 2 , int ( ( n ** ( 1 / 2 ) ) ) + 1 ) : NEW_LINE INDENT if not n % i : NEW_LINE sum += ( i + n // i ) NEW_LINE DEDENT if sum == n and n != 1 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def isAspiring ( n ) : NEW_LINE INDENT alq = getAliquot ( n ) NEW_LINE if ( isPerfect ( alq ) and not isPerfect ( n ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = 25 NEW_LINE if ( isAspiring ( n ) ) : NEW_LINE INDENT print ( " Aspiring " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Aspiring " ) NEW_LINE DEDENT |
Forming smallest array with given constraints | Return the size of smallest array with given constraint . ; Drivers code | def minimumLength ( x , y , z ) : NEW_LINE INDENT return ( 1 + abs ( x - y ) + abs ( y - z ) ) NEW_LINE DEDENT x = 3 NEW_LINE y = 1 NEW_LINE z = 2 NEW_LINE print ( minimumLength ( x , y , z ) ) NEW_LINE |
Find the other | function to find the other - end point of diameter ; find end point for x coordinates ; find end point for y coordinates ; Driven Program | def endPointOfDiameterofCircle ( x1 , y1 , c1 , c2 ) : NEW_LINE INDENT print ( " x2 β = " , ( 2 * c1 - x1 ) , end = " β " ) NEW_LINE print ( " y2 β = " , ( 2 * c2 - y1 ) ) NEW_LINE DEDENT x1 = - 4 NEW_LINE y1 = - 1 NEW_LINE c1 = 3 NEW_LINE c2 = 5 NEW_LINE endPointOfDiameterofCircle ( x1 , y1 , c1 , c2 ) NEW_LINE |
Newton 's Divided Difference Interpolation Formula | Function to find the product term ; Function for calculating divided difference table ; Function for applying Newton 's divided difference formula ; Function for displaying divided difference table ; number of inputs given ; y [ ] [ ] is used for divided difference table where y [ ] [ 0 ] is used for input ; calculating divided difference table ; displaying divided difference table ; value to be interpolated ; printing the value | def proterm ( i , value , x ) : NEW_LINE INDENT pro = 1 ; NEW_LINE for j in range ( i ) : NEW_LINE INDENT pro = pro * ( value - x [ j ] ) ; NEW_LINE DEDENT return pro ; NEW_LINE DEDENT def dividedDiffTable ( x , y , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( n - i ) : NEW_LINE INDENT y [ j ] [ i ] = ( ( y [ j ] [ i - 1 ] - y [ j + 1 ] [ i - 1 ] ) / ( x [ j ] - x [ i + j ] ) ) ; NEW_LINE DEDENT DEDENT return y ; NEW_LINE DEDENT def applyFormula ( value , x , y , n ) : NEW_LINE INDENT sum = y [ 0 ] [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT sum = sum + ( proterm ( i , value , x ) * y [ 0 ] [ i ] ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def printDiffTable ( y , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n - i ) : NEW_LINE INDENT print ( round ( y [ i ] [ j ] , 4 ) , " TABSYMBOL " , end = " β " ) ; NEW_LINE DEDENT print ( " " ) ; NEW_LINE DEDENT DEDENT n = 4 ; NEW_LINE y = [ [ 0 for i in range ( 10 ) ] for j in range ( 10 ) ] ; NEW_LINE x = [ 5 , 6 , 9 , 11 ] ; NEW_LINE y [ 0 ] [ 0 ] = 12 ; NEW_LINE y [ 1 ] [ 0 ] = 13 ; NEW_LINE y [ 2 ] [ 0 ] = 14 ; NEW_LINE y [ 3 ] [ 0 ] = 16 ; NEW_LINE y = dividedDiffTable ( x , y , n ) ; NEW_LINE printDiffTable ( y , n ) ; NEW_LINE value = 7 ; NEW_LINE print ( " Value at " , β value , β " is " , round ( applyFormula ( value , x , y , n ) , 2 ) ) NEW_LINE |
Centered heptagonal number | Function to find Centered heptagonal number ; Formula to calculate nth Centered heptagonal number ; Driver Code | def centered_heptagonal_num ( n ) : NEW_LINE INDENT return ( 7 * n * n - 7 * n + 2 ) // 2 NEW_LINE DEDENT n = 5 NEW_LINE print ( " % sth β Centered β heptagonal β number β : β " % n , centered_heptagonal_num ( n ) ) NEW_LINE |
Sum of square | Function to find sum of sum of square of first n natural number ; Driven Program | def findSum ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ = ( summ + ( ( i * ( i + 1 ) * ( 2 * i + 1 ) ) / 6 ) ) NEW_LINE DEDENT return summ NEW_LINE DEDENT n = 3 NEW_LINE print ( int ( findSum ( n ) ) ) NEW_LINE |
Check if a given matrix is Hankel or not | Python 3 Program to check if given matrix is Hankel Matrix or not . ; Function to check if given matrix is Hankel Matrix or not . ; for each row ; for each column ; checking if i + j is less than n ; checking if the element is equal to the corresponding diagonal constant ; checking if the element is equal to the corresponding diagonal constant ; Drivers code | N = 4 NEW_LINE def checkHankelMatrix ( n , m ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( i + j < n ) : NEW_LINE INDENT if ( m [ i ] [ j ] != m [ i + j ] [ 0 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( m [ i ] [ j ] != m [ i + j - n + 1 ] [ n - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT DEDENT return True NEW_LINE DEDENT n = 4 NEW_LINE m = [ [ 1 , 2 , 3 , 5 , ] , [ 2 , 3 , 5 , 8 , ] , [ 3 , 5 , 8 , 0 , ] , [ 5 , 8 , 0 , 9 ] ] NEW_LINE ( print ( " Yes " ) if checkHankelMatrix ( n , m ) else print ( " No " ) ) NEW_LINE |
Check if a number can be expressed as power | Set 2 ( Using Log ) | Python3 program to find if a number can be expressed as x raised to power y . ; Find Log n in different bases and check if the value is an integer ; Driver code | import math NEW_LINE def isPower ( n ) : NEW_LINE INDENT for x in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT f = math . log ( n ) / math . log ( x ) ; NEW_LINE if ( ( f - int ( f ) ) == 0.0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT for i in range ( 2 , 100 ) : NEW_LINE INDENT if ( isPower ( i ) ) : NEW_LINE INDENT print ( i , end = " β " ) ; NEW_LINE DEDENT DEDENT |
Queries on sum of odd number digit sums of all the factors of a number | Python Program to answer queries on sum of sum of odd number digits of all the factors of a number ; finding sum of odd digit number in each integer . ; for each number ; using previous number sum , finding the current number num of odd digit also , adding last digit if it is odd . ; finding sum of sum of odd digit of all the factors of a number . ; for each possible factor ; adding the contribution . ; Wrapper def ; Driver Code | N = 100 NEW_LINE digitSum = [ 0 ] * N NEW_LINE factorDigitSum = [ 0 ] * N NEW_LINE def sumOddDigit ( ) : NEW_LINE INDENT global N , digitSum , factorDigitSum NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT digitSum [ i ] = ( digitSum [ int ( i / 10 ) ] + int ( i & 1 ) * ( i % 10 ) ) NEW_LINE DEDENT DEDENT def sumFactor ( ) : NEW_LINE INDENT global N , digitSum , factorDigitSum NEW_LINE j = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT j = i NEW_LINE while ( j < N ) : NEW_LINE INDENT factorDigitSum [ j ] = ( factorDigitSum [ j ] + digitSum [ i ] ) NEW_LINE j = j + i NEW_LINE DEDENT DEDENT DEDENT def wrapper ( q , n ) : NEW_LINE INDENT global N , digitSum , factorDigitSum NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT digitSum [ i ] = 0 NEW_LINE factorDigitSum [ i ] = 0 NEW_LINE DEDENT sumOddDigit ( ) NEW_LINE sumFactor ( ) NEW_LINE for i in range ( 0 , q ) : NEW_LINE INDENT print ( " { } β " . format ( factorDigitSum [ n [ i ] ] ) , end = " " ) NEW_LINE DEDENT DEDENT q = 2 NEW_LINE n = [ 10 , 36 ] NEW_LINE wrapper ( q , n ) NEW_LINE |
Number of digits in the nth number made of given four digits | Efficient function to calculate number of digits in the nth number constructed by using 6 , 1 , 4 and 9 as digits in the ascending order . ; Number of digits increase after every i - th number where i increases in powers of 4. ; Driver Code | def number_of_digits ( n ) : NEW_LINE INDENT i = 4 NEW_LINE res = 1 NEW_LINE sum = 0 NEW_LINE while ( True ) : NEW_LINE INDENT i *= 4 NEW_LINE res += 1 NEW_LINE sum += i NEW_LINE if ( sum >= n ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT n = 21 NEW_LINE print ( number_of_digits ( n ) ) NEW_LINE |
Print prime numbers from 1 to N in reverse order | Python3 program to print all primes between 1 to N in reverse order using Sieve of Eratosthenes ; 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 ; Print all prime numbers in reverse order ; static input ; to display | def Reverseorder ( n ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( ( p * 2 ) , ( n + 1 ) , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT p += 1 ; NEW_LINE DEDENT for p in range ( n , 1 , - 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT print ( p , end = " β " ) ; NEW_LINE DEDENT DEDENT DEDENT N = 25 ; NEW_LINE print ( " Prime β number β in β reverse β order " ) ; NEW_LINE if ( N == 1 ) : NEW_LINE INDENT print ( " No β prime β no β exist β in β this β range " ) ; NEW_LINE DEDENT else : NEW_LINE |
Vantieghems Theorem for Primality Test | Python3 code to verify Vantieghem 's Theorem ; Check if above condition is satisfied ; Product of previous powers of 2 ; Driver code | def checkVantieghemsTheorem ( limit ) : NEW_LINE INDENT prod = 1 NEW_LINE for n in range ( 2 , limit ) : NEW_LINE INDENT if n == 2 : NEW_LINE INDENT print ( 2 , " is β prime " ) NEW_LINE DEDENT if ( ( ( prod - n ) % ( ( 1 << n ) - 1 ) ) == 0 ) : NEW_LINE INDENT print ( n , " is β prime " ) NEW_LINE DEDENT prod *= ( ( 1 << n ) - 1 ) NEW_LINE DEDENT DEDENT checkVantieghemsTheorem ( 10 ) NEW_LINE |
Count numbers formed by given two digit with sum having given digits | Python 3 program to count the number of numbers formed by digits a and b exactly of a length N such that the sum of the digits of the number thus formed is of digits a and b . ; function to check if sum of digits is made of a and b ; sum of digits is 0 ; if any of digits in sum is other than a and b ; calculate the modInverse V of a number in O ( log n ) ; q is quotient ; m is remainder now , process same as Euclid 's algo ; Update y and x ; Make x positive ; function to pregenerate factorials ; function to pre calculate the modInverse of factorials ; calculates the modInverse of the last factorial ; precalculates the modInverse of all factorials by formulae ; function that returns the value of nCi ; function that returns the count of numbers ; function call to pre - calculate the factorials and modInverse of factorials ; if a and b are same ; Driver Code | mod = 1000000007 NEW_LINE N = 1000005 NEW_LINE fact = [ 0 ] * N NEW_LINE invfact = [ 0 ] * N NEW_LINE def check ( x , a , b ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( x ) : NEW_LINE INDENT if ( x % 10 != a and x % 10 != b ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT x //= 10 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def modInverse ( a , m ) : NEW_LINE INDENT m0 = m NEW_LINE y = 0 NEW_LINE x = 1 NEW_LINE if ( m == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( a > 1 ) : NEW_LINE INDENT q = a // m NEW_LINE t = m NEW_LINE m = a % m NEW_LINE a = t NEW_LINE t = y NEW_LINE y = x - q * y NEW_LINE x = t NEW_LINE DEDENT if ( x < 0 ) : NEW_LINE INDENT x += m0 NEW_LINE DEDENT return x NEW_LINE DEDENT def pregenFact ( ) : NEW_LINE INDENT fact [ 0 ] = fact [ 1 ] = 1 NEW_LINE for i in range ( 1 , 1000001 ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i % mod NEW_LINE DEDENT DEDENT def pregenInverse ( ) : NEW_LINE INDENT invfact [ 0 ] = invfact [ 1 ] = 1 NEW_LINE invfact [ 1000000 ] = modInverse ( fact [ 1000000 ] , mod ) NEW_LINE for i in range ( 999999 , 0 , - 1 ) : NEW_LINE INDENT invfact [ i ] = ( ( invfact [ i + 1 ] * ( i + 1 ) ) % mod ) NEW_LINE DEDENT DEDENT def comb ( big , small ) : NEW_LINE INDENT return ( fact [ big ] * invfact [ small ] % mod * invfact [ big - small ] % mod ) NEW_LINE DEDENT def count ( a , b , n ) : NEW_LINE INDENT pregenFact ( ) NEW_LINE pregenInverse ( ) NEW_LINE if ( a == b ) : NEW_LINE INDENT return ( check ( a * n , a , b ) ) NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( check ( i * a + ( n - i ) * b , a , b ) ) : NEW_LINE INDENT ans = ( ans + comb ( n , i ) ) % mod NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 3 NEW_LINE b = 4 NEW_LINE n = 11028 NEW_LINE print ( count ( a , b , n ) ) NEW_LINE DEDENT |
Finding n | Function to generate a fixed number ; Driver Code | def magicOfSequence ( N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT sum += ( i * i * i + i * 2 ) NEW_LINE DEDENT return sum ; NEW_LINE DEDENT N = 4 NEW_LINE print ( magicOfSequence ( N ) ) NEW_LINE |
Expressing a number as sum of consecutive | Set 2 ( Using odd factors ) | returns the number of odd factors ; If i is an odd factor and n is a perfect square ; If n is not perfect square ; N as sum of consecutive numbers | def countOddFactors ( n ) : NEW_LINE INDENT odd_factors = 0 NEW_LINE i = 1 NEW_LINE while ( ( 1 * i * i ) <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( 1 * i * i == n ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT odd_factors = odd_factors + 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( ( i & 1 ) ) : NEW_LINE INDENT odd_factors = odd_factors + 1 NEW_LINE DEDENT factor = int ( n / i ) NEW_LINE if ( factor & 1 ) : NEW_LINE INDENT odd_factors = odd_factors + 1 NEW_LINE DEDENT DEDENT DEDENT i = i + 1 NEW_LINE DEDENT return odd_factors - 1 NEW_LINE DEDENT N = 15 NEW_LINE print ( countOddFactors ( N ) ) NEW_LINE N = 10 NEW_LINE print ( countOddFactors ( N ) ) NEW_LINE |
Making zero array by decrementing pairs of adjacent | Python3 program to find if it is possible to make all array elements 0 by decrement operations . ; used for storing the sum of even and odd position element in array . ; if position is odd , store sum value of odd position in odd ; if position is even , store sum value of even position in even ; Driver Code | def isPossibleToZero ( a , n ) : NEW_LINE INDENT even = 0 ; NEW_LINE odd = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT odd += a [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT even += a [ i ] ; NEW_LINE DEDENT DEDENT return ( odd == even ) ; NEW_LINE DEDENT arr = [ 0 , 1 , 1 , 0 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE if ( isPossibleToZero ( arr , n ) ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE DEDENT |
Program for sum of cos ( x ) series | Python3 program to find the sum of cos ( x ) series ; here x is in degree . we have to convert it to radian for using it with series formula , as in series expansion angle is in radian ; Driver Code | PI = 3.142 ; NEW_LINE def cosXSertiesSum ( x , n ) : NEW_LINE INDENT x = x * ( PI / 180.0 ) ; NEW_LINE res = 1 ; NEW_LINE sign = 1 ; NEW_LINE fact = 1 ; NEW_LINE pow = 1 ; NEW_LINE for i in range ( 1 , 5 ) : NEW_LINE INDENT sign = sign * ( - 1 ) ; NEW_LINE fact = fact * ( 2 * i - 1 ) * ( 2 * i ) ; NEW_LINE pow = pow * x * x ; NEW_LINE res = res + sign * pow / fact ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT x = 50 ; NEW_LINE n = 5 ; NEW_LINE print ( round ( cosXSertiesSum ( x , 5 ) , 6 ) ) ; NEW_LINE |
Sum of digits written in different bases from 2 to n | def to calculate sum of digit for a given base ; Sum of digits ; Calculating the number ( n ) by taking mod with the base and adding remainder to the result and parallelly reducing the num value . ; returning the result ; def calling for multiple bases ; Driver code | def solve ( n , base ) : NEW_LINE INDENT result = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT remainder = n % base NEW_LINE result = result + remainder NEW_LINE n = int ( n / base ) NEW_LINE DEDENT return result NEW_LINE DEDENT def printSumsOfDigits ( n ) : NEW_LINE INDENT for base in range ( 2 , n ) : NEW_LINE INDENT print ( solve ( n , base ) , end = " β " ) NEW_LINE DEDENT DEDENT n = 8 NEW_LINE printSumsOfDigits ( n ) NEW_LINE |
Possible two sets from first N natural numbers difference of sums as D | Function returns true if it is possible to split into two sets otherwise returns false ; Driver code | def check ( N , D ) : NEW_LINE INDENT temp = N * ( N + 1 ) // 2 + D NEW_LINE return ( bool ( temp % 2 == 0 ) ) NEW_LINE DEDENT N = 5 NEW_LINE M = 7 NEW_LINE if check ( N , M ) : NEW_LINE INDENT print ( " yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " no " ) NEW_LINE DEDENT |
Minimum digits to remove to make a number Perfect Square | C ++ program to find required minimum digits need to remove to make a number perfect square ; function to check minimum number of digits should be removed to make this number a perfect square ; size of the string ; our final answer ; to store string which is perfect square . ; We make all possible subsequences ; to check jth bit is set or not . ; we do not consider a number with leading zeros ; convert our temporary string into integer ; checking temp is perfect square or not . ; taking maximum sized string ; print PerfectSquare ; Driver code | import math NEW_LINE def perfectSquare ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = - 1 NEW_LINE num = " " NEW_LINE for i in range ( 1 , ( 1 << n ) ) : NEW_LINE INDENT str = " " NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( ( i >> j ) & 1 ) : NEW_LINE INDENT str = str + s [ j ] NEW_LINE DEDENT DEDENT if ( str [ 0 ] != '0' ) : NEW_LINE INDENT temp = 0 ; NEW_LINE for j in range ( 0 , len ( str ) ) : NEW_LINE INDENT temp = ( temp * 10 + ( ord ( str [ j ] ) - ord ( '0' ) ) ) NEW_LINE DEDENT k = int ( math . sqrt ( temp ) ) NEW_LINE if ( k * k == temp ) : NEW_LINE INDENT if ( ans < len ( str ) ) : NEW_LINE INDENT ans = len ( str ) NEW_LINE num = str NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( ans == - 1 ) : NEW_LINE INDENT return ans NEW_LINE DEDENT else : NEW_LINE INDENT print ( " { } β " . format ( num ) , end = " " ) NEW_LINE return n - ans NEW_LINE DEDENT DEDENT print ( perfectSquare ( "8314" ) ) NEW_LINE print ( perfectSquare ( "753" ) ) ; NEW_LINE |
Lagrange 's four square theorem | Prints all the possible combinations 4 numbers whose sum of squares is equal to the given no . ; loops checking the sum of squares ; if sum of four squares equals the given no . ; printing the numbers ; Driver Code ; 74 = 0 * 0 + 0 * 0 + 5 * 5 + 7 * 7 74 = 0 * 0 + 1 * 1 + 3 * 3 + 8 * 8 74 = 0 * 0 + 3 * 3 + 4 * 4 + 7 * 7 74 = 1 * 1 + 1 * 1 + 6 * 6 + 6 * 6 74 = 2 * 2 + 3 * 3 + 5 * 5 + 6 * 6 | def printFourSquares ( a ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i * i <= a ) : NEW_LINE INDENT j = i NEW_LINE while ( j * j <= a ) : NEW_LINE INDENT k = j NEW_LINE while ( k * k <= a ) : NEW_LINE INDENT l = k NEW_LINE while ( l * l <= a ) : NEW_LINE INDENT if ( i * i + j * j + k * k + l * l == a ) : NEW_LINE INDENT print ( " { } β = β { } * { } β + β { } * { } β + " . format ( a , i , i , j , j ) , end = " β " ) NEW_LINE print ( " { } * { } β + β { } * { } " . format ( k , k , l , l ) , end = " " ) NEW_LINE DEDENT l = l + 1 NEW_LINE DEDENT k = k + 1 NEW_LINE DEDENT j = j + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT DEDENT a = 74 NEW_LINE printFourSquares ( a ) NEW_LINE |
Hardy | Python3 program to count all prime factors ; A function to count prime factors of a given number n ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; This condition is to handle the case when n is a prime number greater than 2 ; Driver Code | import math NEW_LINE def exactPrimeFactorCount ( n ) : NEW_LINE INDENT count = 0 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = int ( n / 2 ) NEW_LINE DEDENT DEDENT i = 3 NEW_LINE while ( i <= int ( math . sqrt ( n ) ) ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n = int ( n / i ) NEW_LINE DEDENT DEDENT i = i + 2 NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT n = 51242183 NEW_LINE print ( " The β number β of β distinct β prime β factors β is / are β { } " . format ( exactPrimeFactorCount ( n ) , end = " " ) ) NEW_LINE print ( " The β value β of β log ( log ( n ) ) β is β { 0 : . 4f } " . format ( math . log ( math . log ( n ) ) ) ) NEW_LINE |
Number of Digits in a ^ b | Python Program to calculate no . of digits in a ^ b ; function to calculate number of digits in a ^ b ; Driver Program | import math NEW_LINE def no_of_digit ( a , b ) : NEW_LINE INDENT return ( ( int ) ( b * math . log10 ( a ) ) + 1 ) NEW_LINE DEDENT a = 2 NEW_LINE b = 100 NEW_LINE print ( " no β of β digits β = β " , no_of_digit ( a , b ) ) NEW_LINE |
Check whether a number is Emirpimes or not | Checking whether a number is semi - prime or not ; Increment count of prime numbers ; If number is still greater than 1 , after exiting the add it to the count variable as it indicates the number is a prime number ; Return '1' if count is equal to '2' else return '0 ; Checking whether a number is emirpimes or not ; Number itself is not semiprime . ; Finding reverse of n . ; The definition of emirpimes excludes palindromes , hence we do not check further , if the number entered is a palindrome ; Checking whether the reverse of the semi prime number entered is also a semi prime number or not ; Driver Code | def checkSemiprime ( num ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE i = 2 ; NEW_LINE while ( cnt < 2 and ( i * i ) <= num ) : NEW_LINE INDENT while ( num % i == 0 ) : NEW_LINE INDENT num /= i ; NEW_LINE cnt += 1 ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT if ( num > 1 ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT return cnt == 2 ; NEW_LINE DEDENT def isEmirpimes ( n ) : NEW_LINE INDENT if ( checkSemiprime ( n ) == False ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT r = 0 ; NEW_LINE t = n ; NEW_LINE while ( t != 0 ) : NEW_LINE INDENT r = r * 10 + t % 10 ; NEW_LINE t = t / n ; NEW_LINE DEDENT if ( r == n ) : NEW_LINE INDENT return false ; NEW_LINE DEDENT return ( checkSemiprime ( r ) ) ; NEW_LINE DEDENT n = 15 ; NEW_LINE if ( isEmirpimes ( n ) ) : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT |
Connell Sequence | Function to generate a fixed number of even or odd terms . The size of r decides whether numbers to be generated even or odd . ; Generating the first ' n ' terms of Connell Sequence ; A dummy 0 is inserted at the beginning for consistency ; Calling function gen ( ) to generate ' k ' number of terms ; Checking if ' n ' terms are already generated ; Removing the previously inserted dummy 0 ; Driver Code | def gen ( n , r ) : NEW_LINE INDENT a = r [ - 1 ] NEW_LINE a += 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT r . append ( a ) NEW_LINE a += 2 NEW_LINE DEDENT return r NEW_LINE DEDENT def conell ( n ) : NEW_LINE INDENT res = [ ] NEW_LINE k = 1 NEW_LINE res . append ( 0 ) NEW_LINE while 1 : NEW_LINE INDENT res = gen ( k , res ) NEW_LINE k += 1 NEW_LINE j = len ( res ) - 1 NEW_LINE while j != n and j + k > n : NEW_LINE INDENT k -= 1 NEW_LINE DEDENT if j >= n : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT res . remove ( res [ 0 ] ) NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 NEW_LINE print ( " The β first β % d β terms β are " % n ) NEW_LINE res = conell ( n ) NEW_LINE for i in range ( len ( res ) ) : NEW_LINE INDENT print ( res [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT |
Generate a list of n consecutive composite numbers ( An interesting method ) | function to find factorial of given number ; Prints n consecutive numbers . ; Driver Code | def factorial ( n ) : NEW_LINE INDENT res = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res *= i ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def printNComposite ( n ) : NEW_LINE INDENT fact = factorial ( n + 1 ) ; NEW_LINE for i in range ( 2 , n + 2 ) : NEW_LINE INDENT print ( fact + i , end = " β " ) ; NEW_LINE DEDENT DEDENT n = 4 ; NEW_LINE printNComposite ( n ) ; NEW_LINE |
Frugal Number | Finding primes upto entered number ; Finding primes by Sieve of Eratosthenes method ; If prime [ i ] is not changed , then it is prime ; Update all multiples of p ; Forming array of the prime numbers found ; Returns number of digits in n ; Checking whether a number is Frugal or not ; Finding number of digits in prime factorization of the number ; Exponent for current factor ; Counting number of times this prime factor divides ( Finding exponent ) ; Finding number of digits in the exponent Avoiding exponents of value 1 ; Checking condition for frugal number ; Driver Code | def primes ( n ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) ; NEW_LINE i = 2 ; NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( prime [ i ] == True ) : NEW_LINE INDENT j = i * 2 ; NEW_LINE while ( j <= n ) : NEW_LINE INDENT prime [ j ] = False ; NEW_LINE j += i ; NEW_LINE DEDENT DEDENT i += 1 ; NEW_LINE DEDENT arr = [ ] ; NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT arr . append ( i ) ; NEW_LINE DEDENT DEDENT return arr ; NEW_LINE DEDENT def countDigits ( n ) : NEW_LINE INDENT temp = n ; NEW_LINE c = 0 ; NEW_LINE while ( temp != 0 ) : NEW_LINE INDENT temp = int ( temp / 10 ) ; NEW_LINE c += 1 ; NEW_LINE DEDENT return c ; NEW_LINE DEDENT def frugal ( n ) : NEW_LINE INDENT r = primes ( n ) ; NEW_LINE t = n ; NEW_LINE s = 0 ; NEW_LINE for i in range ( len ( r ) ) : NEW_LINE INDENT if ( t % r [ i ] == 0 ) : NEW_LINE INDENT k = 0 ; NEW_LINE while ( t % r [ i ] == 0 ) : NEW_LINE INDENT t = int ( t / r [ i ] ) ; NEW_LINE k += 1 ; NEW_LINE DEDENT if ( k == 1 ) : NEW_LINE INDENT s = s + countDigits ( r [ i ] ) ; NEW_LINE DEDENT elif ( k != 1 ) : NEW_LINE INDENT s = ( s + countDigits ( r [ i ] ) + countDigits ( k ) ) ; NEW_LINE DEDENT DEDENT DEDENT return ( countDigits ( n ) > s and s != 0 ) ; NEW_LINE DEDENT n = 343 ; NEW_LINE if ( frugal ( n ) ) : NEW_LINE INDENT print ( " A β Frugal β number " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β a β frugal β number " ) ; NEW_LINE DEDENT |
N | program to find n - th number which is both square and cube . ; Driver code | def nthSquareCube ( n ) : NEW_LINE INDENT return n * n * n * n * n * n NEW_LINE DEDENT n = 5 NEW_LINE print ( nthSquareCube ( n ) ) NEW_LINE |
Squared triangular number ( Sum of cubes ) | Function to find if the given number is sum of the cubes of first n natural numbers ; Start adding cubes of the numbers from 1 ; If sum becomes equal to s return n ; Driver code | def findS ( s ) : NEW_LINE INDENT _sum = 0 NEW_LINE n = 1 NEW_LINE while ( _sum < s ) : NEW_LINE INDENT _sum += n * n * n NEW_LINE n += 1 NEW_LINE DEDENT n -= 1 NEW_LINE if _sum == s : NEW_LINE INDENT return n NEW_LINE DEDENT return - 1 NEW_LINE DEDENT s = 9 NEW_LINE n = findS ( s ) NEW_LINE if n == - 1 : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( n ) NEW_LINE DEDENT |
Number with even sum of digits | Function to find kth good number . ; Find the last digit of n . ; If last digit is between 0 to 4 then return 2 * n . ; If last digit is between 5 to 9 then return 2 * n + 1. ; Driver code | def findKthGoodNo ( n ) : NEW_LINE INDENT lastDig = n % 10 NEW_LINE if ( lastDig >= 0 and lastDig <= 4 ) : NEW_LINE INDENT return n << 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( n << 1 ) + 1 NEW_LINE DEDENT DEDENT n = 10 NEW_LINE print ( findKthGoodNo ( n ) ) NEW_LINE |
Nicomachu 's Theorem | Python3 program to verify Nicomachu 's Theorem ; Compute sum of cubes ; Check if sum is equal to given formula . ; Driver Code | def NicomachuTheorum_sum ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for k in range ( 1 , n + 1 ) : NEW_LINE INDENT sum += k * k * k ; NEW_LINE DEDENT triNo = n * ( n + 1 ) / 2 ; NEW_LINE if ( sum == triNo * triNo ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT n = 5 ; NEW_LINE NicomachuTheorum_sum ( n ) ; NEW_LINE |
Largest even digit number not greater than N | function to check if all digits are even of a given number ; iterate for all digits ; if digit is odd ; all digits are even ; function to return the largest number with all digits even ; Iterate till we find a number with all digits even ; Driver Code | def checkDigits ( n ) : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT if ( ( n % 10 ) % 2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT n = int ( n / 10 ) ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def largestNumber ( n ) : NEW_LINE INDENT for i in range ( n , - 1 , - 1 ) : NEW_LINE INDENT if ( checkDigits ( i ) ) : NEW_LINE INDENT return i ; NEW_LINE DEDENT DEDENT DEDENT N = 23 ; NEW_LINE print ( largestNumber ( N ) ) ; NEW_LINE |
Largest even digit number not greater than N | Python3 program to print the largest integer not greater than N with all even digits ; function to return the largest number with all digits even ; convert the number to a string for easy operations ; find first odd digit ; if no digit , then N is the answer ; till first odd digit , add all even numbers ; decrease 1 from the odd digit ; add 0 in the rest of the digits ; Driver Code | import math as mt NEW_LINE def largestNumber ( n ) : NEW_LINE INDENT s = " " NEW_LINE duplicate = n NEW_LINE while ( n > 0 ) : NEW_LINE INDENT s = chr ( n % 10 + 48 ) + s NEW_LINE n = n // 10 NEW_LINE DEDENT index = - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( ( ord ( s [ i ] ) - ord ( '0' ) ) % 2 & 1 ) : NEW_LINE INDENT index = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( index == - 1 ) : NEW_LINE INDENT return duplicate NEW_LINE DEDENT num = 0 NEW_LINE for i in range ( index ) : NEW_LINE INDENT num = num * 10 + ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT num = num * 10 + ( ord ( s [ index ] ) - ord ( '0' ) - 1 ) NEW_LINE for i in range ( index + 1 , len ( s ) ) : NEW_LINE INDENT num = num * 10 + 8 NEW_LINE DEDENT return num NEW_LINE DEDENT N = 24578 NEW_LINE print ( largestNumber ( N ) ) NEW_LINE |
Number of digits in 2 raised to power n | Python3 program to find number of digits in 2 ^ n ; Function to find number of digits in 2 ^ n ; Driver code | import math NEW_LINE def countDigits ( n ) : NEW_LINE INDENT return int ( n * math . log10 ( 2 ) + 1 ) ; NEW_LINE DEDENT n = 5 ; NEW_LINE print ( countDigits ( n ) ) ; NEW_LINE |
Smallest even digits number not less than N | function to check if all digits are even of a given number ; iterate for all digits ; if digit is odd ; all digits are even ; function to return the smallest number with all digits even ; iterate till we find a number with all digits even ; Driver Code | def check_digits ( n ) : NEW_LINE INDENT while ( n ) : NEW_LINE INDENT if ( ( n % 10 ) % 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT n = int ( n / 10 ) NEW_LINE DEDENT return 1 NEW_LINE DEDENT def smallest_number ( n ) : NEW_LINE INDENT for i in range ( n , 2401 ) : NEW_LINE INDENT if ( check_digits ( i ) == 1 ) : NEW_LINE INDENT return ( i ) NEW_LINE DEDENT DEDENT DEDENT N = 2397 NEW_LINE print ( str ( smallest_number ( N ) ) ) NEW_LINE |
Smallest triangular number larger than p | Python 3 code to find the bucket to choose for picking flowers out of it ; Driver code | import math NEW_LINE def findBucketNo ( p ) : NEW_LINE INDENT return math . ceil ( ( math . sqrt ( 8 * p + 1 ) - 1 ) / 2 ) NEW_LINE DEDENT p = 10 NEW_LINE print ( findBucketNo ( p ) ) NEW_LINE |
LCM of factorial and its neighbors | Function to calculate the factorial ; returning the factorial of the largest number in the given three consecutive numbers ; Driver code | def factorial ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return n * factorial ( n - 1 ) NEW_LINE DEDENT def LCMOfNeighbourFact ( n ) : NEW_LINE INDENT return factorial ( n + 1 ) NEW_LINE DEDENT N = 5 NEW_LINE print ( LCMOfNeighbourFact ( N ) ) NEW_LINE |
Expressing factorial n as sum of consecutive numbers | Python 3 program to count number of ways we can express a factorial as sum of consecutive numbers ; sieve of Eratosthenes to compute the prime numbers ; Store all prime numbers ; function to calculate the largest power of a prime in a number ; Modular multiplication to avoid the overflow of multiplication Please see below for details https : www . geeksforgeeks . org / how - to - avoid - overflow - in - modular - multiplication / ; Returns count of ways to express n ! as sum of consecutives . ; We skip 2 ( First prime ) as we need to consider only odd primes ; compute the largest power of prime ; if the power of current prime number is zero in N ! , power of primes greater than current prime number will also be zero , so break out from the loop ; multiply the result at every step ; subtract 1 to exclude the case of 1 being an odd divisor ; Driver Code | MAX = 50002 ; NEW_LINE primes = [ ] NEW_LINE def sieve ( ) : NEW_LINE INDENT isPrime = [ True ] * ( MAX ) NEW_LINE p = 2 NEW_LINE while p * p < MAX : NEW_LINE INDENT if ( isPrime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , MAX , p ) : NEW_LINE INDENT isPrime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , MAX ) : NEW_LINE INDENT if ( isPrime [ p ] ) : NEW_LINE INDENT primes . append ( p ) NEW_LINE DEDENT DEDENT DEDENT def power ( x , y ) : NEW_LINE INDENT count = 0 NEW_LINE z = y NEW_LINE while ( x >= z ) : NEW_LINE INDENT count += ( x // z ) NEW_LINE z *= y NEW_LINE DEDENT return count NEW_LINE DEDENT def modMult ( a , b , mod ) : NEW_LINE INDENT res = 0 NEW_LINE a = a % mod NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( b % 2 == 1 ) : NEW_LINE INDENT res = ( res + a ) % mod NEW_LINE DEDENT a = ( a * 2 ) % mod NEW_LINE b //= 2 NEW_LINE DEDENT return res % mod NEW_LINE DEDENT def countWays ( n , m ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , len ( primes ) ) : NEW_LINE INDENT powers = power ( n , primes [ i ] ) NEW_LINE if ( powers == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT ans = modMult ( ans , powers + 1 , m ) % m NEW_LINE DEDENT if ( ( ( ans - 1 ) % m ) < 0 ) : NEW_LINE INDENT return ( ans - 1 + m ) % m NEW_LINE DEDENT else : NEW_LINE INDENT return ( ans - 1 ) % m NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT sieve ( ) NEW_LINE n = 4 NEW_LINE m = 7 NEW_LINE print ( countWays ( n , m ) ) NEW_LINE DEDENT |
Check if the given two numbers are friendly pair or not | Check if the given two number are friendly pair or not . ; Returns sum of all factors of n . ; Traversing through all prime factors . ; THE BELOW STATEMENT MAKES IT BETTER THAN ABOVE METHOD AS WE REDUCE VALUE OF n . ; This condition is to handle the case when n is a prime number greater than 2. ; Function to return gcd of a and b ; Function to check if the given two number are friendly pair or not . ; Finding the sum of factors of n and m ; Finding gcd of n and sum of its factors . ; Finding gcd of m and sum of its factors . ; checking is numerator and denominator of abundancy index of both number are equal or not . ; Driver code | import math NEW_LINE def sumofFactors ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT count = 0 ; curr_sum = 1 ; curr_term = 1 NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE n = n // i NEW_LINE curr_term *= i NEW_LINE curr_sum += curr_term NEW_LINE DEDENT res *= curr_sum NEW_LINE DEDENT if ( n >= 2 ) : NEW_LINE INDENT res *= ( 1 + n ) NEW_LINE DEDENT return res NEW_LINE DEDENT 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 checkFriendly ( n , m ) : NEW_LINE INDENT sumFactors_n = sumofFactors ( n ) NEW_LINE sumFactors_m = sumofFactors ( m ) NEW_LINE gcd_n = gcd ( n , sumFactors_n ) NEW_LINE gcd_m = gcd ( m , sumFactors_m ) NEW_LINE if ( n // gcd_n == m // gcd_m and sumFactors_n // gcd_n == sumFactors_m // gcd_m ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = 6 ; m = 28 NEW_LINE if ( checkFriendly ( n , m ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Find n | Python3 program to find n - th Fortunate number ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to Find primorial of order n ( product of first n prime numbers ) . ; Function to find next prime number greater than n ; Note that difference ( or m ) should be greater than 1. ; loop continuously until isPrime returns true for a number above n ; Ignoring the prime number that is 1 greater than n ; Returns n - th Fortunate number ; Driver Code | def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : return False NEW_LINE if ( n <= 3 ) : return True NEW_LINE if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def primorial ( n ) : NEW_LINE INDENT p = 2 ; n -= 1 ; i = 3 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( isPrime ( i ) ) : NEW_LINE INDENT p = p * i NEW_LINE n -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return p NEW_LINE DEDENT def findNextPrime ( n ) : NEW_LINE INDENT nextPrime = n + 2 NEW_LINE while ( True ) : NEW_LINE INDENT if ( isPrime ( nextPrime ) ) : NEW_LINE INDENT break NEW_LINE DEDENT nextPrime += 1 NEW_LINE DEDENT return nextPrime NEW_LINE DEDENT def fortunateNumber ( n ) : NEW_LINE INDENT p = primorial ( n ) NEW_LINE return findNextPrime ( p ) - p NEW_LINE DEDENT n = 5 NEW_LINE print ( fortunateNumber ( n ) ) NEW_LINE |