text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Number of n digit numbers that do not contain 9 | function to find number of n digit numbers possible ; driver function
def totalNumber ( n ) : NEW_LINE INDENT return 8 * pow ( 9 , n - 1 ) ; NEW_LINE DEDENT n = 3 NEW_LINE print ( totalNumber ( n ) ) NEW_LINE
Count ways to express even number â €˜ nâ €™ as sum of even integers | Initialize mod variable as constant ; 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 ; Return number...
MOD = 1e9 + 7 NEW_LINE def power ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( 1 * res * x ) % p NEW_LINE DEDENT x = ( 1 * x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def countEvenWays ( n ) : NEW_LINE INDENT return power ( 2 , n / 2 - 1 , MOD ) NEW_...
Number of steps to convert to prime factors | Python 3 program to count number of steps required to convert an integer array to array of factors . ; array to store prime factors ; function to generate all prime factors of numbers from 1 to 10 ^ 6 ; Initializes all the positions with their value . ; Initializes all mult...
MAX = 1000001 NEW_LINE factor = [ 0 ] * MAX NEW_LINE def cal_factor ( ) : 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 ...
Subsequences of size three in an array whose sum is divisible by m | Python program to find count of subsequences of size three divisible by M . ; Three nested loop to find all the sub sequences of length three in the given array A [ ] . ; checking if the sum of the chosen three number is divisible by m . ; Driver code
def coutSubSeq ( A , N , M ) : NEW_LINE INDENT sum = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT for k in range ( j + 1 , N ) : NEW_LINE INDENT sum = A [ i ] + A [ j ] + A [ k ] NEW_LINE if ( sum % M == 0 ) : NEW_LINE INDENT ans = ans + 1 NEW_LIN...
Subsequences of size three in an array whose sum is divisible by m | Python program to find count of subsequences of size three divisible by M . ; Storing frequencies of all remainders when divided by M . ; including i and j in the sum rem calculate the remainder required to make the sum divisible by M ; if the require...
def countSubSeq ( A , N , M ) : NEW_LINE INDENT ans = 0 NEW_LINE h = [ 0 ] * M NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT A [ i ] = A [ i ] % M NEW_LINE h [ A [ i ] ] = h [ A [ i ] ] + 1 NEW_LINE DEDENT for i in range ( 0 , M ) : NEW_LINE INDENT for j in range ( i , M ) : NEW_LINE INDENT rem = ( M - ( i + j ) ...
Find n | utility function ; since first element of the series is 7 , we initialise a variable with 7 ; Using iteration to find nth term ; driver function
def findTerm ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return n NEW_LINE DEDENT else : NEW_LINE INDENT term = 7 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT term = term * 2 + ( i - 1 ) ; NEW_LINE DEDENT DEDENT return term ; NEW_LINE DEDENT print ( findTerm ( 5 ) ) NEW_LINE
Find n | Returns n - th number in sequence 1 , 1 , 2 , 1 , 2 , 3 , 1 , 2 , 4 , ... ; One by one subtract counts elements in different blocks ; Driver code
def findNumber ( n ) : NEW_LINE INDENT n -= 1 NEW_LINE i = 1 NEW_LINE while n >= 0 : NEW_LINE INDENT n -= i NEW_LINE i += 1 NEW_LINE DEDENT return ( n + i ) NEW_LINE DEDENT n = 3 NEW_LINE print ( findNumber ( n ) ) NEW_LINE
Program to find correlation coefficient | Python Program to find correlation coefficient . ; function that returns correlation coefficient . ; sum of elements of array X . ; sum of elements of array Y . ; sum of X [ i ] * Y [ i ] . ; sum of square of array elements . ; use formula for calculating correlation coefficien...
import math NEW_LINE def correlationCoefficient ( X , Y , n ) : NEW_LINE INDENT sum_X = 0 NEW_LINE sum_Y = 0 NEW_LINE sum_XY = 0 NEW_LINE squareSum_X = 0 NEW_LINE squareSum_Y = 0 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT sum_X = sum_X + X [ i ] NEW_LINE sum_Y = sum_Y + Y [ i ] NEW_LINE sum_XY = sum_XY + X [...
Find the number of spectators standing in the stadium at time t | Python program to find number of spectators standing at a time ; If the time is less than k then we can print directly t time . ; If the time is n then k spectators are standing . ; Otherwise we calculate the spectators standing . ; Stores the value of n...
def result ( n , k , t ) : NEW_LINE INDENT if ( t <= k ) : NEW_LINE INDENT print ( t ) NEW_LINE DEDENT elif ( t <= n ) : NEW_LINE INDENT print ( k ) NEW_LINE DEDENT else : NEW_LINE INDENT temp = t - n NEW_LINE temp = k - temp NEW_LINE print ( temp ) NEW_LINE DEDENT DEDENT n = 10 NEW_LINE k = 5 NEW_LINE t = 12 NEW_LINE ...
Program for weighted mean of natural numbers . | Function to calculate weighted mean . ; Take num array and corresponding weight array and initialize it . ; Calculate the size of array . ; Check the size of both array is equal or not .
def weightedMean ( X , W , n ) : NEW_LINE INDENT sum = 0 NEW_LINE numWeight = 0 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT numWeight = numWeight + X [ i ] * W [ i ] NEW_LINE sum = sum + W [ i ] NEW_LINE i = i + 1 NEW_LINE DEDENT return ( float ) ( numWeight / sum ) NEW_LINE DEDENT X = [ 1 , 2 , 3 , 4 , 5 , 6...
Program to find GCD of floating point numbers | Python code for finding the GCD of two floating numbers . ; Recursive function to return gcd of a and b ; base case ; Driver Function .
import math NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if ( a < b ) : NEW_LINE INDENT return gcd ( b , a ) NEW_LINE DEDENT if ( abs ( b ) < 0.001 ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return ( gcd ( b , a - math . floor ( a / b ) * b ) ) NEW_LINE DEDENT DEDENT a = 1.20 NEW_LINE b = 22.5 ...
Program for harmonic mean of numbers | Function that returns harmonic mean . ; Declare sum variables and initialize with zero . ; Driver code
def harmonicMean ( arr , n ) : NEW_LINE INDENT sm = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sm = sm + ( 1 ) / arr [ i ] ; NEW_LINE DEDENT return n / sm NEW_LINE DEDENT arr = [ 13.5 , 14.5 , 14.8 , 15.2 , 16.1 ] ; NEW_LINE n = len ( arr ) NEW_LINE print ( harmonicMean ( arr , n ) ) NEW_LINE
Program for harmonic mean of numbers | Function that returns harmonic mean . ; Driver code
def harmonicMean ( arr , freq , n ) : NEW_LINE INDENT sm = 0 NEW_LINE frequency_sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sm = sm + freq [ i ] / arr [ i ] NEW_LINE frequency_sum = frequency_sum + freq [ i ] NEW_LINE DEDENT return ( round ( frequency_sum / sm , 4 ) ) NEW_LINE DEDENT num = [ 13 , 14 , 1...
First collision point of two series | Function to calculate the colliding point of two series ; Iterating through n terms of the first series ; x is i - th term of first series ; d is first element of second series and c is common difference for second series . ; If no term of first series is found ; Driver code
def point ( a , b , c , d , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT x = b + i * a NEW_LINE if ( x - d ) % c == 0 and x - d >= 0 : NEW_LINE INDENT print x NEW_LINE return NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print " No ▁ collision ▁ point " NEW_LINE DEDENT DEDENT a = 20 NEW_LINE b = 2 NEW_L...
Armstrong Numbers between two integers | PYTHON program to find Armstrong numbers in a range ; Prints Armstrong Numbers in given range ; number of digits calculation ; compute sum of nth power of ; checks if number i is equal to the sum of nth power of its digits ; Driver code
import math NEW_LINE def findArmstrong ( low , high ) : NEW_LINE INDENT for i in range ( low + 1 , high ) : NEW_LINE INDENT x = i NEW_LINE n = 0 NEW_LINE while ( x != 0 ) : NEW_LINE INDENT x = x / 10 NEW_LINE n = n + 1 NEW_LINE DEDENT pow_sum = 0 NEW_LINE x = i NEW_LINE while ( x != 0 ) : NEW_LINE INDENT digit = x % 10...
Lucas Primality Test | Python3 program for Lucas Primality Test ; Function to generate prime factors of n ; If 2 is a factor ; If prime > 2 is factor ; This function produces power modulo some number . It can be optimized to using ; Base cases ; Generating and storing factors of n - 1 ; Array for random generator . Thi...
import random NEW_LINE import math NEW_LINE def primeFactors ( n , factors ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT factors . append ( 2 ) NEW_LINE DEDENT while ( n % 2 == 0 ) : NEW_LINE INDENT n = n // 2 NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT if ( n % ...
Pair with maximum GCD from two arrays | Find the maximum GCD pair with maximum sum ; array to keep a count of existing elements ; first [ i ] and second [ i ] are going to store maximum multiples of i in a [ ] and b [ ] respectively . ; traverse through the first array to mark the elements in cnt ; Find maximum multipl...
def gcdMax ( a , b , n , N ) : NEW_LINE INDENT cnt = [ 0 ] * N NEW_LINE first = [ 0 ] * N NEW_LINE second = [ 0 ] * N NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt [ a [ i ] ] = 1 NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( i , N , i ) : NEW_LINE INDENT if ( cnt [ j ] ) : NEW_LINE ...
Pierpont Prime | Python3 program to print Pierpont prime numbers smaller than n . ; Finding all numbers having factor power of 2 and 3 Using sieve ; Storing number of the form 2 ^ i . 3 ^ k + 1. ; Finding prime number using sieve of Eratosthenes . Reusing same array as result of above computations in v . ; Printing n p...
def printPierpont ( n ) : NEW_LINE INDENT arr = [ False ] * ( n + 1 ) ; NEW_LINE two = 1 ; NEW_LINE three = 1 ; NEW_LINE while ( two + 1 < n ) : NEW_LINE INDENT arr [ two ] = True ; NEW_LINE while ( two * three + 1 < n ) : NEW_LINE INDENT arr [ three ] = True ; NEW_LINE arr [ two * three ] = True ; NEW_LINE three *= 3 ...
Woodall Number | Python program to check if a number is Woodball or not . ; If number is even , return false . ; If x is 1 , return true . ; While x is divisible by 2 ; Divide x by 2 ; Count the power ; If at any point power and x became equal , return true . ; Driven Program
def isWoodall ( x ) : NEW_LINE INDENT if ( x % 2 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( x == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT p = 0 NEW_LINE while ( x % 2 == 0 ) : NEW_LINE INDENT x = x / 2 NEW_LINE p = p + 1 NEW_LINE if ( p == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDEN...
Print k numbers where all pairs are divisible by m | function to generate k numbers whose difference is divisible by m ; Using an adjacency list like representation to store numbers that lead to same remainder . ; stores the modulus when divided by m ; If we found k elements which have same remainder . ; If we could no...
def print_result ( a , n , k , m ) : NEW_LINE INDENT v = [ [ ] for i in range ( m ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT rem = a [ i ] % m NEW_LINE v [ rem ] . append ( a [ i ] ) NEW_LINE if ( len ( v [ rem ] ) == k ) : NEW_LINE INDENT for j in range ( 0 , k ) : NEW_LINE INDENT print ( v [ rem ] [ j ] ...
Largest number less than N whose each digit is prime number | Number is given as string . ; We stop traversing digits , once it become smaller than current number . For that purpose we use small variable . ; Array indicating if index i ( represents a digit ) is prime or not . ; Store largest ; If there is only one char...
def PrimeDigitNumber ( N , size ) : NEW_LINE INDENT ans = [ " " ] * size NEW_LINE ns = 0 ; NEW_LINE small = 0 ; NEW_LINE p = [ 0 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 0 , 0 ] NEW_LINE prevprime = [ 0 , 0 , 0 , 2 , 3 , 3 , 5 , 5 , 7 , 7 ] NEW_LINE if ( size == 1 ) : NEW_LINE INDENT ans [ 0 ] = prevprime [ ord ( N [ 0 ] ) - ord ...
Smallest x such that 1 * n , 2 * n , ... x * n have all digits from 1 to 9 | Returns smallest value x such that 1 * n , 2 * n , 3 * n ... x * n have all digits from 1 to 9 at least once ; taking temporary array and variable . ; iterate till we get all the 10 digits at least once ; checking all the digits ; Driver code
def smallestX ( n ) : NEW_LINE INDENT temp = [ 0 ] * 10 NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT count = 0 NEW_LINE x = 1 NEW_LINE while ( count < 10 ) : NEW_LINE INDENT y = x * n NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( temp [ y % 10 ] == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE temp...
Find a number x such that sum of x and its digits is equal to given n . | utility function for digit sum ; function for finding x ; iterate from 1 to n . For every no . check if its digit sum with it isequal to n . ; if no such i found return - 1 ; Driver Code
def digSum ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE rem = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT rem = n % 10 ; NEW_LINE sum = sum + rem ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def findX ( n ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT if ( i + digSum ( i ) =...
9 's complement of a decimal number | Python3 program to find 9 's complement of a number. ; Driver code
def complement ( number ) : NEW_LINE INDENT for i in range ( 0 , len ( number ) ) : NEW_LINE INDENT if ( number [ i ] != ' . ' ) : NEW_LINE INDENT a = 9 - int ( number [ i ] ) NEW_LINE number = ( number [ : i ] + str ( a ) + number [ i + 1 : ] ) NEW_LINE DEDENT DEDENT print ( "9 ' s ▁ complement ▁ is ▁ : ▁ " , number )...
Ways to express a number as product of two different factors | To count number of ways in which number expressed as product of two different numbers ; To store count of such pairs ; Counting number of pairs upto sqrt ( n ) - 1 ; To return count of pairs ; Driver program to test countWays ( )
def countWays ( n ) : NEW_LINE INDENT count = 0 NEW_LINE i = 1 NEW_LINE while ( ( i * i ) < n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT n = 12 NEW_LINE print ( countWays ( n ) ) NEW_LINE
Count divisors of n that have at | Python3 program to count divisors of n that have at least one digit common with n ; Function to return true if any digit of m is present in hash [ ] . ; check till last digit ; if number is also present in original number then return true ; if no number matches then return 1 ; Count t...
import math NEW_LINE def isDigitPresent ( m , Hash ) : NEW_LINE INDENT while ( m ) : NEW_LINE INDENT if ( Hash [ m % 10 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT m = m // 10 NEW_LINE DEDENT return False NEW_LINE DEDENT def countDivisibles ( n ) : NEW_LINE INDENT Hash = [ False for i in range ( 10 ) ] NEW_LINE m...
Doolittle Algorithm : LU Decomposition | Python3 Program to decompose a matrix into lower and upper triangular matrix ; Decomposing matrix into Upper and Lower triangular matrix ; Upper Triangular ; Summation of L ( i , j ) * U ( j , k ) ; Evaluating U ( i , k ) ; Lower Triangular ; lower [ i ] [ i ] = 1 Diagonal as 1 ...
MAX = 100 NEW_LINE def luDecomposition ( mat , n ) : NEW_LINE INDENT lower = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE upper = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for k in range ( i , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range...
Divide number into two parts divisible by given numbers | method prints divisible parts if possible , otherwise prints 'Not possible ; creating arrays to store reminder ; looping over all suffix and storing reminder with f ; getting suffix reminder from previous suffix reminder ; looping over all prefix and storing rem...
' NEW_LINE def printTwoDivisibleParts ( num , f , s ) : NEW_LINE INDENT N = len ( num ) ; NEW_LINE prefixReminder = [ 0 ] * ( N + 1 ) ; NEW_LINE suffixReminder = [ 0 ] * ( N + 1 ) ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT suffixReminder [ i ] = ( suffixReminder [ i - 1 ] * 10 + ( ord ( num [ i - 1 ] ) - 48 ...
Count of numbers satisfying m + sum ( m ) + sum ( sum ( m ) ) = N | function that returns sum of digits in a number ; initially sum of digits is 0 ; loop runs till all digits have been extracted ; last digit from backside ; sums up the digits ; the number is reduced to the number removing the last digit ; returns the s...
def sum ( n ) : NEW_LINE INDENT rem = 0 NEW_LINE sum_of_digits = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT rem = n % 10 NEW_LINE sum_of_digits += rem NEW_LINE n = n // 10 NEW_LINE DEDENT return sum_of_digits NEW_LINE DEDENT def count ( n ) : NEW_LINE INDENT c = 0 NEW_LINE for i in range ( n - 97 , n + 1 ) : NEW_LINE...
Check if a number is power of k using base changing method | Python program to check if a number can be raised to k ; loop to change base n to base = k ; Find current digit in base k ; If digit is neither 0 nor 1 ; Make sure that only one 1 is present . ; Driver code
def isPowerOfK ( n , k ) : NEW_LINE INDENT oneSeen = False NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit = n % k NEW_LINE if ( digit > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( digit == 1 ) : NEW_LINE INDENT if ( oneSeen ) : NEW_LINE INDENT return False NEW_LINE DEDENT oneSeen = True NEW_LINE DEDENT n ...
Check if number is palindrome or not in Octal | Python3 program to check if octal representation of a number is prime ; Function to Check no is in octal or not ; Function To check no is palindrome or not ; If number is already in octal , we traverse digits using repeated division with 10. Else we traverse digits using ...
MAX_DIGITS = 20 ; NEW_LINE def isOctal ( n ) : NEW_LINE INDENT while ( n ) : NEW_LINE INDENT if ( ( n % 10 ) >= 8 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT n = int ( n / 10 ) NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isPalindrome ( n ) : NEW_LINE INDENT divide = 8 if ( isOctal...
Find all factorial numbers less than or equal to n | Python3 program to find all factorial numbers smaller than or equal to n . ; Compute next factorial using previous ; Driver code
def printFactorialNums ( n ) : NEW_LINE INDENT fact = 1 NEW_LINE x = 2 NEW_LINE while fact <= n : NEW_LINE INDENT print ( fact , end = " ▁ " ) NEW_LINE fact = fact * x NEW_LINE x += 1 NEW_LINE DEDENT DEDENT n = 100 NEW_LINE printFactorialNums ( n ) NEW_LINE
Happy Numbers | Returns sum of squares of digits of a number n . For example for n = 12 it returns 1 + 4 = 5 ; Returns true if n is Happy number else returns false . ; A set to store numbers during repeated square sum process ; Keep replacing n with sum of squares of digits until we either reach 1 or we endup in a cycl...
def sumDigitSquare ( n ) : NEW_LINE INDENT sq = 0 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT digit = n % 10 NEW_LINE sq += digit * digit NEW_LINE n = n // 10 NEW_LINE DEDENT return sq ; NEW_LINE DEDENT def isHappy ( n ) : NEW_LINE INDENT s = set ( ) NEW_LINE s . add ( n ) NEW_LINE while ( True ) : NEW_LINE INDENT if...
Check whether a number has exactly three distinct factors or not | Python 3 program to check whether number has exactly three distinct factors or not ; Utility function to check whether a number is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to check wh...
from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT k = int ( sqrt ( n ) ) + 1 NEW_LINE for i in range ( ...
Find the last digit when factorial of A divides factorial of B | Function which computes the last digit of resultant of B ! / A ! ; if ( A == B ) : If A = B , B ! = A ! and B ! / A ! = 1 ; If difference ( B - A ) >= 5 , answer = 0 ; If non of the conditions are true , we iterate from A + 1 to B and multiply them . We a...
def computeLastDigit ( A , B ) : NEW_LINE INDENT variable = 1 NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( ( B - A ) >= 5 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( A + 1 , B + 1 ) : NEW_LINE INDENT variable = ( variable * ( i % 10 ) ) % 10 NEW_LINE DEDENT return variable % ...
Program for sum of arithmetic series | Function to find sum of series . ; Driver function
def sumOfAP ( a , d , n ) : NEW_LINE INDENT sum = 0 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT sum = sum + a NEW_LINE a = a + d NEW_LINE i = i + 1 NEW_LINE DEDENT 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
Product of factors of number | Python program to calculate product of factors of number ; function to product the factors ; If factors are equal , multiply only once ; Otherwise multiply both ; Driver Code
M = 1000000007 NEW_LINE def multiplyFactors ( n ) : NEW_LINE INDENT prod = 1 NEW_LINE i = 1 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n / i == i ) : NEW_LINE INDENT prod = ( prod * i ) % M NEW_LINE DEDENT else : NEW_LINE INDENT prod = ( prod * i ) % M NEW_LINE prod = ( prod * ...
Product of factors of number | Python program to calculate product of factors of number ; Iterative Function to calculate ( x ^ y ) in O ( log y ) ; function to count the factors ; If factors are equal , count only once ; Otherwise count both ; Calculate product of factors ; If numFactor is odd return power ( n , numFa...
M = 1000000007 NEW_LINE def power ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y % 2 == 1 ) : NEW_LINE INDENT res = ( res * x ) % M NEW_LINE DEDENT y = ( y >> 1 ) % M NEW_LINE x = ( x * x ) % M NEW_LINE DEDENT return res NEW_LINE DEDENT def countFactors ( n ) : NEW_LINE INDENT cou...
Tribonacci Numbers | A space optimized based Python 3 program to print first n Tribinocci numbers . ; Initialize first three numbers ; Loop to add previous three numbers for each number starting from 3 and then assign first , second , third to second , third , and curr to third respectively ; Driver code
def printTrib ( n ) : NEW_LINE INDENT if ( n < 1 ) : NEW_LINE INDENT return NEW_LINE DEDENT first = 0 NEW_LINE second = 0 NEW_LINE third = 1 NEW_LINE print ( first , " ▁ " , end = " " ) NEW_LINE if ( n > 1 ) : NEW_LINE INDENT print ( second , " ▁ " , end = " " ) NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT print ( se...
Prime Number of Set Bits in Binary Representation | Set 2 | Function to create an array of prime numbers upto number 'n ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , ...
' NEW_LINE import math as m NEW_LINE def SieveOfEratosthenes ( n ) : NEW_LINE INDENT prime = [ True for i in range ( 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 D...
Count trailing zeroes present in binary representation of a given number using XOR | Python3 implementation of the above approach ; Function to print count of trailing zeroes present in binary representation of N ; Count set bits in ( N ^ ( N - 1 ) ) ; If res < 0 , return 0 ; Driver Code ; Function call to print the co...
from math import log2 NEW_LINE def countTrailingZeroes ( N ) : NEW_LINE INDENT res = int ( log2 ( N ^ ( N - 1 ) ) ) NEW_LINE return res if res >= 0 else 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE print ( countTrailingZeroes ( N ) ) NEW_LINE DEDENT
Maximum sum of Bitwise XOR of elements with their respective positions in a permutation of size N | Function to generate all the possible permutation and get the max score ; If arr [ ] length is equal to N process the permutation ; Generating the permutations ; If the current element is chosen ; Mark the current elemen...
def getMax ( arr , ans , chosen , N ) : NEW_LINE INDENT if len ( arr ) == N : NEW_LINE INDENT ans = max ( ans , calcScr ( arr ) ) NEW_LINE return ans NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if chosen [ i ] : NEW_LINE INDENT continue NEW_LINE DEDENT chosen [ i ] = True NEW_LINE arr . append ( i ) NEW_LINE...
Additive Congruence method for generating Pseudo Random Numbers | Function to generate random numbers ; Initialize the seed state ; Traverse to generate required numbers of random numbers ; Follow the linear congruential method ; Driver Code ; Seed value ; Modulus parameter ; Multiplier term ; Number of Random numbers ...
def additiveCongruentialMethod ( Xo , m , c , randomNums , noOfRandomNums ) : NEW_LINE INDENT randomNums [ 0 ] = Xo NEW_LINE for i in range ( 1 , noOfRandomNums ) : NEW_LINE INDENT randomNums [ i ] = ( randomNums [ i - 1 ] + c ) % m NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Xo = 3 NEW_LIN...
Number of ways to change the Array such that largest element is LCM of array | Modulo ; Fenwick tree to find number of indexes greater than x ; Function to compute x ^ y % MOD ; Loop to compute the x ^ y % MOD ; Function to update the Binary Indexed Tree ; Loop to update the BIT ; Function to find prefix sum upto idx ;...
MOD = int ( 1e9 ) + 9 NEW_LINE MAXN = int ( 1e5 ) + 5 NEW_LINE BIT = [ 0 for _ in range ( MAXN ) ] NEW_LINE def power ( x , y ) : NEW_LINE INDENT if x == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 1 NEW_LINE while y > 0 : NEW_LINE INDENT if y % 2 == 1 : NEW_LINE INDENT ans = ( ans * x ) % MOD NEW_LINE DEDENT x ...
Second decagonal numbers | Function to find N - th term in the series ; Driver Code
def findNthTerm ( n ) : NEW_LINE INDENT print ( n * ( 4 * n + 3 ) ) NEW_LINE DEDENT N = 4 ; NEW_LINE findNthTerm ( N ) ; NEW_LINE
65537 | Function to find the nth 65537 - gon Number ; Driver Code
def gonNum65537 ( n ) : NEW_LINE INDENT return ( 65535 * n * n - 65533 * n ) // 2 ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( gonNum65537 ( n ) ) ; NEW_LINE
Hexacontatetragon numbers | Function to Find the Nth Hexacontatetragon Number ; Driver Code
def HexacontatetragonNum ( n ) : NEW_LINE INDENT return ( 62 * n * n - 60 * n ) / 2 ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( HexacontatetragonNum ( n ) ) ; NEW_LINE
Icosikaipentagon Number | Function to find the N - th icosikaipentagon number ; Driver code
def icosikaipentagonNum ( N ) : NEW_LINE INDENT return ( 23 * N * N - 21 * N ) // 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( "3rd ▁ icosikaipentagon ▁ Number ▁ is ▁ " , icosikaipentagonNum ( n ) ) NEW_LINE
Chiliagon Number | Finding the nth chiliagon Number ; Driver Code
def chiliagonNum ( n ) : NEW_LINE INDENT return ( 998 * n * n - 996 * n ) // 2 ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( "3rd ▁ chiliagon ▁ Number ▁ is ▁ = ▁ " , chiliagonNum ( n ) ) ; NEW_LINE
Pentacontagon number | Finding the nth pentacontagon Number ; Driver Code
def pentacontagonNum ( n ) : NEW_LINE INDENT return ( 48 * n * n - 46 * n ) // 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( "3rd ▁ pentacontagon ▁ Number ▁ is ▁ = ▁ " , pentacontagonNum ( n ) ) NEW_LINE
Array value by repeatedly replacing max 2 elements with their absolute difference | Python3 program to find the array value by repeatedly replacing max 2 elements with their absolute difference ; Function that return last value of array ; Build a binary max_heap . ; Multipying by - 1 for max heap ; For max 2 elements ;...
from queue import PriorityQueue NEW_LINE def lastElement ( arr ) : NEW_LINE INDENT pq = PriorityQueue ( ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT pq . put ( - 1 * arr [ i ] ) NEW_LINE DEDENT m1 = 0 NEW_LINE m2 = 0 NEW_LINE while not pq . empty ( ) : NEW_LINE INDENT if pq . qsize ( ) == 1 : NEW_LINE IN...
Number formed by adding product of its max and min digit K times | Function to find the formed number ; K -= 1 M ( 1 ) = N ; Check if minimum digit is 0 ; Function that returns the product of maximum and minimum digit of N number . ; Find the last digit . ; Moves to next digit ; Driver Code
def formed_no ( N , K ) : NEW_LINE INDENT if ( K == 1 ) : NEW_LINE INDENT return N NEW_LINE DEDENT answer = N NEW_LINE while ( K != 0 ) : NEW_LINE INDENT a_current = prod_of_max_min ( answer ) NEW_LINE if ( a_current == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT answer += a_current NEW_LINE K -= 1 NEW_LINE DEDENT retu...
Logarithm tricks for Competitive Programming | Python3 implementation count the number of digits in a number ; Function to count the number of digits in a number ; Driver code
import math NEW_LINE def countDigit ( n ) : NEW_LINE INDENT return ( math . floor ( math . log10 ( n ) + 1 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 80 NEW_LINE print ( countDigit ( n ) ) NEW_LINE DEDENT
Program to find the sum of the series 1 + x + x ^ 2 + x ^ 3 + . . + x ^ n | Function to find the sum of the series and print N terms of the given series ; First Term ; Loop to print the N terms of the series and find their sum ; Driver code
def sum ( x , n ) : NEW_LINE INDENT total = 1.0 NEW_LINE multi = x NEW_LINE print ( 1 , end = " ▁ " ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT total = total + multi NEW_LINE print ( ' % .1f ' % multi , end = " ▁ " ) NEW_LINE multi = multi * x NEW_LINE DEDENT print ( ' ' ) NEW_LINE return total ; NEW_LINE DED...
Find the remainder when N is divided by 4 using Bitwise AND operator | Function to find the remainder ; Bitwise AND with 3 ; Return x ; Driver code
def findRemainder ( n ) : NEW_LINE INDENT x = n & 3 NEW_LINE return x NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 43 NEW_LINE ans = findRemainder ( N ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Find all Autobiographical Numbers with given number of digits | Python implementation to find Autobiographical numbers with length N ; Function to return if the number is autobiographical or not ; Converting the integer number to string ; Extracting each character from each index one by one and converting into an integ...
from math import pow NEW_LINE def isAutoBio ( num ) : NEW_LINE INDENT autoStr = str ( num ) NEW_LINE for i in range ( 0 , len ( autoStr ) ) : NEW_LINE INDENT index = int ( autoStr [ i ] ) NEW_LINE cnt = 0 NEW_LINE for j in range ( 0 , len ( autoStr ) ) : NEW_LINE INDENT number = int ( autoStr [ j ] ) NEW_LINE if number...
Check whether the number can be made palindromic after adding K | Function to check whether a number is a palindrome or not ; Convert num to stringing ; Comparing kth character from the beginning and N - kth character from the end . If all the characters match , then the number is a palindrome ; If all the above condit...
def checkPalindrome ( num ) : NEW_LINE INDENT string = str ( num ) NEW_LINE l = 0 NEW_LINE r = len ( string ) - 1 ; NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( string [ l ] != string [ r ] ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return ; NEW_LINE DEDENT l = l + 1 ; NEW_LINE r = r - 1 ; NEW_LINE DEDENT print (...
Count of subsets with sum equal to X using Recursion | Recursive function to return the count of subsets with sum equal to the given value ; The recursion is stopped at N - th level where all the subsets of the given array have been checked ; Incrementing the count if sum is equal to 0 and returning the count ; Recursi...
def subsetSum ( arr , n , i , sum , count ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( sum == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT count = subsetSum ( arr , n , i + 1 , sum - arr [ i ] , count ) NEW_LINE count = subsetSum ( arr , n , i + 1 , sum , count ) NEW_LINE re...
Distinct Prime Factors of an Array | Function to return an array of prime numbers upto n using Sieve of Eratosthenes ; Function to return distinct prime factors from the given array ; Creating an empty array to store distinct prime factors ; Iterating through all the prime numbers and check if any of the prime numbers ...
def sieve ( n ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) NEW_LINE p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT allPrimes = [ x for x in ran...
Sum of the count of number of adjacent squares in an M X N grid | function to calculate the sum of all cells adjacent value ; Driver Code
def summ ( m , n ) : NEW_LINE INDENT return 8 * m * n - 6 * m - 6 * n + 4 NEW_LINE DEDENT m = 3 NEW_LINE n = 2 NEW_LINE print ( summ ( m , n ) ) NEW_LINE
Count pairs in an array such that the absolute difference between them is ÃƒÆ ’ à † â €™ Ã⠀ à ¢ â ‚¬ â „¢ ÃƒÆ ’ à ¢ â ‚¬ à ¢ à ¢ â € š ¬ Ã ¢ â € ž ¢ ÃƒÆ ’ à † â €™ à ¢ à ¢ â € š ¬ ÃƒÆ ’¢ à ¢ à ¢ â ‚¬ Å ¡¬ à ¢ à ¢ â ‚¬ Å ¾¢ ÃƒÆ ’ à † â €™ Ã⠀ à ¢ â ‚¬ â „¢ ÃƒÆ ’¢ à ¢ à ¢ â ‚¬ Å ¡¬ ÃƒÆ ’ à † â €™¢ ÃƒÆ ’¢ à ¢ Ã...
def count ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE cnt = 0 ; NEW_LINE DEDENT i = 0 ; j = 1 ; NEW_LINE INDENT while ( i < n and j < n ) : NEW_LINE if j <= i : NEW_LINE j = i + 1 NEW_LINE else : NEW_LINE j = j NEW_LINE while ( j < n and ( arr [ j ] - arr [ i ] ) < k ) : NEW_LINE j += 1 ; NEW_LINE cnt +...
Find the volume of rectangular right wedge | Function to return the volume of the rectangular right wedge ; Driver code
def volumeRec ( a , b , e , h ) : NEW_LINE INDENT return ( ( ( b * h ) / 6 ) * ( 2 * a + e ) ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 2 ; b = 5 ; e = 5 ; h = 6 ; NEW_LINE print ( " Volume ▁ = ▁ " , volumeRec ( a , b , e , h ) ) ; NEW_LINE DEDENT
Count squares with odd side length in Chessboard | Function to return the count of odd length squares possible ; To store the required count ; For all odd values of i ; Add the count of possible squares of length i ; Return the required count ; Driver code
def count_square ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( 1 , n + 1 , 2 ) : NEW_LINE INDENT k = n - i + 1 ; NEW_LINE count += ( k * k ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT N = 8 ; NEW_LINE print ( count_square ( N ) ) ; NEW_LINE
Count of elements whose absolute difference with the sum of all the other elements is greater than k | Function to return the number of anomalies ; To store the count of anomalies ; To store the Sum of the array elements ; Find the Sum of the array elements ; Count the anomalies ; Driver code
def countAnomalies ( arr , n , k ) : NEW_LINE INDENT cnt = 0 NEW_LINE i , Sum = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( abs ( arr [ i ] - ( Sum - arr [ i ] ) ) > k ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NE...
Find the number of integers x in range ( 1 , N ) for which x and x + 1 have same number of divisors | Python3 implementation of the above approach ; To store number of divisors and Prefix sum of such numbers ; Function to find the number of integers 1 < x < N for which x and x + 1 have the same number of positive divis...
from math import sqrt ; NEW_LINE N = 100005 NEW_LINE d = [ 0 ] * N NEW_LINE pre = [ 0 ] * N NEW_LINE def Positive_Divisors ( ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( 1 , int ( sqrt ( i ) ) + 1 ) : NEW_LINE INDENT if ( i % j == 0 ) : NEW_LINE INDENT if ( j * j == i ) : NEW_LINE INDENT ...
Length of the smallest number which is divisible by K and formed by using 1 's only | Function to return length of the resultant number ; If K is a multiple of 2 or 5 ; Generate all possible numbers 1 , 11 , 111 , 111 , ... , K 1 's ; If number is divisible by k then return the length ; Driver code
def numLen ( K ) : NEW_LINE INDENT if ( K % 2 == 0 or K % 5 == 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT number = 0 ; NEW_LINE len = 1 ; NEW_LINE for len in range ( 1 , K + 1 ) : NEW_LINE INDENT number = number * 10 + 1 ; NEW_LINE if ( ( number % K == 0 ) ) : NEW_LINE INDENT return len ; NEW_LINE DEDENT DEDENT...
Find if the given number is present in the infinite sequence or not | Function that returns true if the sequence will contain B ; Driver code
def doesContainB ( a , b , c ) : NEW_LINE INDENT if ( a == b ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ( b - a ) * c > 0 and ( b - a ) % c == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a , b , c = 1 , 7 , 3 NEW_LINE if ( do...
Find a permutation of 2 N numbers such that the result of given expression is exactly 2 K | Function to find the required permutation of first 2 * N natural numbers ; Iterate in blocks of 2 ; We need more increments , so print in reverse order ; We have enough increments , so print in same order ; Driver Code
def printPermutation ( n , k ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT x = 2 * i - 1 ; NEW_LINE y = 2 * i ; NEW_LINE if ( i <= k ) : NEW_LINE INDENT print ( y , x , end = " ▁ " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( x , y , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ =...
Maximize the sum of products of the degrees between any two vertices of the tree | Function to return the maximum possible sum ; Initialize degree for node u to 2 ; If u is the leaf node or the root node ; Initialize degree for node v to 2 ; If v is the leaf node or the root node ; Update the sum ; Driver code
def maxSum ( N ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for u in range ( 1 , N + 1 ) : NEW_LINE INDENT for v in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( u == v ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT degreeU = 2 ; NEW_LINE if ( u == 1 or u == N ) : NEW_LINE INDENT degreeU = 1 ; NEW_LINE DEDENT degreeV = 2 ; NEW_...
Find integers that divides maximum number of elements of the array | Function to print the integers that divide the maximum number of elements from the array ; Initialize two lists to store rank and factors ; Start from 2 till the maximum element in arr ; Initialize a variable to count the number of elements it is a fa...
def maximumFactor ( arr ) : NEW_LINE INDENT rank , factors = [ ] , [ ] NEW_LINE for i in range ( 2 , max ( arr ) + 1 ) : NEW_LINE INDENT count = 0 NEW_LINE for j in arr : NEW_LINE INDENT if j % i == 0 : count += 1 NEW_LINE DEDENT rank . append ( count ) NEW_LINE factors . append ( i ) NEW_LINE DEDENT m = max ( rank ) N...
Natural Numbers | Returns sum of first n natural numbers ; Driver code
def findSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE x = 1 NEW_LINE while x <= n : NEW_LINE INDENT sum = sum + x NEW_LINE x = x + 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 5 NEW_LINE print findSum ( n ) NEW_LINE
Median | Function for calculating median ; First we sort the array ; check for even case ; Driver program
def findMedian ( a , n ) : NEW_LINE INDENT sorted ( a ) NEW_LINE if n % 2 != 0 : NEW_LINE INDENT return float ( a [ n // 2 ] ) NEW_LINE DEDENT return float ( ( a [ int ( ( n - 1 ) / 2 ) ] + a [ int ( n / 2 ) ] ) / 2.0 ) NEW_LINE DEDENT a = [ 1 , 3 , 4 , 2 , 7 , 5 , 8 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( " Medi...
Mean | Function for calculating mean ; Driver program
def findMean ( a , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT return float ( sum / n ) NEW_LINE DEDENT a = [ 1 , 3 , 4 , 2 , 7 , 5 , 8 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( " Mean ▁ = " , findMean ( a , n ) ) NEW_LINE
Check if the array has an element which is equal to product of remaining elements | Python3 implementation of the above approach ; Function to Check if the array has an element which is equal to product of all the remaining elements ; Storing frequency in map ; Calculate the product of all the elements ; If the prod is...
import math NEW_LINE def CheckArray ( arr , n ) : NEW_LINE INDENT prod = 1 NEW_LINE freq = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq . append ( arr [ i ] ) NEW_LINE prod *= arr [ i ] NEW_LINE DEDENT root = math . sqrt ( prod ) NEW_LINE if ( root * root == prod ) : NEW_LINE INDENT if root in freq : NEW_LI...
Find minimum area of rectangle with given set of coordinates | ''Python Implementation of above approach ; function to find minimum area of Rectangle ; creating empty columns ; fill columns with coordinates ; check if rectangle can be formed ; Driver code
import collections NEW_LINE def minAreaRect ( A ) : NEW_LINE INDENT columns = collections . defaultdict ( list ) NEW_LINE for x , y in A : NEW_LINE INDENT columns [ x ] . append ( y ) NEW_LINE DEDENT lastx = { } NEW_LINE ans = float ( ' inf ' ) NEW_LINE for x in sorted ( columns ) : NEW_LINE INDENT column = columns [ x...
Check whether a number has consecutive 0 's in the given base or not | We first convert to given base , then check if the converted number has two consecutive 0 s or not ; Function to convert N into base K ; Weight of each digit ; Function to check for consecutive 0 ; Flag to check if there are consecutive zero or not ...
def hasConsecutiveZeroes ( N , K ) : NEW_LINE INDENT z = toK ( N , K ) NEW_LINE if ( check ( z ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT def toK ( N , K ) : NEW_LINE INDENT w = 1 NEW_LINE s = 0 NEW_LINE while ( N != 0 ) : NEW_LINE INDENT r = N...
Sum of every Kâ €™ th prime number in an array | Python3 implementation of the approach ; 0 and 1 are not prime numbers ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; compute the answer ; count of primes ; sum of the primes ; traverse the array ; if the number is a prime ; increase t...
MAX = 100000 ; NEW_LINE prime = [ True ] * ( MAX + 1 ) ; NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime [ 1 ] = False ; NEW_LINE prime [ 0 ] = False ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= MAX ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT i = p * 2 ; NEW_LINE while ( i <= MAX ) : NEW_LINE ...
Find the super power of a given Number | Python3 for finding super power of n ; global hash for prime ; sieve method for storing a list of prime ; function to return super power ; find the super power ; Driver Code
MAX = 100000 ; NEW_LINE prime = [ True ] * 100002 ; NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT p = 2 ; NEW_LINE while ( p * p <= MAX ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT i = p * 2 ; NEW_LINE while ( i <= MAX ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE i += p ; NEW_LINE DED...
Count of Prime Nodes of a Singly Linked List | Function to check if a number is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Link list node ; Push a new node on the front of the list . ; Function to find count of prime nodes in a linked list ; If current node is prime ;...
def isPrime ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if n <= 3 : NEW_LINE INDENT return True NEW_LINE DEDENT if n % 2 == 0 or n % 3 == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while i * i <= n : NEW_LINE INDENT if n % i == 0 or n % ( i + 2 ) == 0 : NEW_LINE...
Smallest prime divisor of a number | Function to find the smallest divisor ; if divisible by 2 ; iterate from 3 to sqrt ( n ) ; Driver Code
def smallestDivisor ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return 2 ; NEW_LINE DEDENT i = 3 ; NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return i ; NEW_LINE DEDENT i += 2 ; NEW_LINE DEDENT return n ; NEW_LINE DEDENT n = 31 ; NEW_LINE print ( smallestDivisor ...
Count Number of animals in a zoo from given number of head and legs | Function that calculates Rabbits ; Driver code
def countRabbits ( Heads , Legs ) : NEW_LINE INDENT count = 0 NEW_LINE count = ( Legs ) - 2 * ( Heads ) NEW_LINE count = count / 2 NEW_LINE return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Heads = 100 NEW_LINE Legs = 300 NEW_LINE Rabbits = countRabbits ( Heads , Legs ) NEW_LINE print ( " R...
Program to evaluate the expression ( ÃƒÆ ’ à † â €™ Ã⠀ à ¢ â ‚¬ â „¢ ÃƒÆ ’ à ¢ â ‚¬ à ¢ à ¢ â € š ¬ Ã ¢ â € ž ¢ ÃƒÆ ’ à † â €™ à ¢ à ¢ â € š ¬ ÃƒÆ ’¢ à ¢ à ¢ â ‚¬ Å ¡¬ à ¢ à ¢ â ‚¬ Å ¾¢ ÃƒÆ ’ à † â €™ Ã⠀ à ¢ â ‚¬ â „¢ ÃƒÆ ’¢ à ¢ à ¢ â ‚¬ Å ¡¬ ÃƒÆ ’ à † â €™¢ ÃƒÆ ’¢ à ¢ à ¢ â € š ¬ Ã …¡¬ ÃƒÆ ’¢ à ¢ à ¢ â € ...
import math NEW_LINE def calculateSum ( n ) : NEW_LINE INDENT a = int ( n ) NEW_LINE return ( 2 * ( pow ( n , 6 ) + 15 * pow ( n , 4 ) + 15 * pow ( n , 2 ) + 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 1.4142 NEW_LINE DEDENT print ( math . ceil ( calculateSum ( n ) ) ) NEW_LINE
Find the sum of series 3 , | calculate sum upto N term of series ; Driver code
def Sum_upto_nth_Term ( n ) : NEW_LINE INDENT return ( 1 - pow ( - 2 , n ) ) NEW_LINE DEDENT N = 5 NEW_LINE print ( Sum_upto_nth_Term ( N ) ) NEW_LINE
Count numbers whose XOR with N is equal to OR with N | Function to calculate count of numbers with XOR equals OR ; variable to store count of unset bits ; Driver code
def xorEqualsOrCount ( N ) : NEW_LINE INDENT count = 0 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT bit = N % 2 NEW_LINE if bit == 0 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT N //= 2 NEW_LINE DEDENT return int ( pow ( 2 , count ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 NEW_LINE print ...
Program to find sum of 1 + x / 2 ! + x ^ 2 / 3 ! + ... + x ^ n / ( n + 1 ) ! | Method to find the factorial of a number ; Method to compute the sum ; Iterate the loop till n and compute the formula ; Driver code ; Get x and n ; Print output
def fact ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return n * fact ( n - 1 ) NEW_LINE DEDENT DEDENT def sum ( x , n ) : NEW_LINE INDENT total = 1.0 NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT total = total + ( pow ( x , i ) / fact ( i + 1 ) ) NEW...
Find Sum of Series 1 ^ 2 | Function to find sum of series ; If i is even ; If i is odd ; return the result ; Driver Code ; Get n ; Find the sum ; Get n ; Find the sum
def sum_of_series ( n ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT result = result - pow ( i , 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT result = result + pow ( i , 2 ) NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == " _ ...
Program to find the sum of the series 23 + 45 + 75 + ... . . upto N terms | calculate Nth term of series ; Driver Function ; Get the value of N ; Get the sum of the series
def findSum ( N ) : NEW_LINE INDENT return ( 2 * N * ( N + 1 ) * ( 4 * N + 17 ) + 54 * N ) / 6 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE print ( findSum ( N ) ) NEW_LINE DEDENT
Program to find the value of sin ( nÃƒÆ ’ à † â €™ Ã⠀ à ¢ â ‚¬ â „¢ ÃƒÆ ’ à ¢ â ‚¬¦½ ÃƒÆ ’ à † â €™ à ¢ à ¢ â € 𠬹 ÃƒÆ ’ à ¢ â ‚¬¦ à ¢ à ¢ â € š ¬ Ã … â € œ ) | ''Python3 program to find the value of sin(n-theta) ; ''Function to calculate the binomial coefficient upto 15 ; '' use simple DP to find coefficient...
import math NEW_LINE MAX = 16 NEW_LINE nCr = [ [ 0 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE def binomial ( ) : NEW_LINE for i in range ( MAX ) : for j in range ( 0 , i + 1 ) : if j == 0 or j == i : NEW_LINE INDENT nCr [ i ] [ j ] = 1 NEW_LINE DEDENT else : nCr [ i ] [ j ] = nCr [ i - 1 ] [ j ] + nCr [...
Program to find Nth term of series 9 , 23 , 45 , 75 , 113. . . | Python program to find N - th term of the series : 9 , 23 , 45 , 75 , 113. . . ; calculate Nth term of series ; Get the value of N ; Find the Nth term and print it
def nthTerm ( N ) : NEW_LINE INDENT return ( ( 2 * N + 3 ) * ( 2 * N + 3 ) - 2 * N ) ; NEW_LINE DEDENT n = 4 NEW_LINE print ( nthTerm ( n ) ) NEW_LINE
Program to Find the value of cos ( nÃƒÆ ’ à † â €™ Ã⠀ à ¢ â ‚¬ â „¢ ÃƒÆ ’ à ¢ â ‚¬¦½ ÃƒÆ ’ à † â €™ à ¢ à ¢ â € 𠬹 ÃƒÆ ’ à ¢ â ‚¬¦ à ¢ à ¢ â € š ¬ Ã … â € œ ) | ''Python3 program to find the value of cos(n-theta) ; ''Function to calculate the binomial coefficient upto 15 ; '' use simple DP to find coefficient ; ...
import math NEW_LINE MAX = 16 NEW_LINE nCr = [ [ 0 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE def binomial ( ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE for j in range ( 0 , i + 1 ) : NEW_LINE if j == 0 or j == i : NEW_LINE DEDENT nCr [ i ] [ j ] = 1 NEW_LINE INDENT else : NEW_LINE nCr [ i ] [...
Find sum of the series 1 + 22 + 333 + 4444 + ... ... upto n terms | Function to calculate sum ; Return sum ; driver code
def solve_sum ( n ) : NEW_LINE INDENT return ( pow ( 10 , n + 1 ) * ( 9 * n - 1 ) + 10 ) / pow ( 9 , 3 ) - n * ( n + 1 ) / 18 NEW_LINE DEDENT n = 3 NEW_LINE print ( int ( solve_sum ( n ) ) ) NEW_LINE
Find sum of the series 1 | Function to calculate sum ; when n is odd ; when n is not odd ; Driver code
def solve_sum ( n ) : NEW_LINE INDENT if ( n % 2 == 1 ) : NEW_LINE INDENT return ( n + 1 ) / 2 NEW_LINE DEDENT return - n / 2 NEW_LINE DEDENT n = 8 NEW_LINE print ( int ( solve_sum ( n ) ) ) NEW_LINE
Check if a number can be expressed as a ^ b | Set 2 | Python 3 Program to check if a number can be expressed as a ^ b ; Driver Code
from math import * NEW_LINE def isPower ( a ) : NEW_LINE INDENT if a == 1 : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 2 , int ( sqrt ( a ) ) + 1 ) : NEW_LINE INDENT val = log ( a ) / log ( i ) NEW_LINE if ( round ( ( val - int ( val ) ) , 8 ) < 0.00000001 ) : NEW_LINE INDENT return True NEW_LINE DEDE...
Program to calculate Root Mean Square | Python3 program to calculate Root Mean Square ; Function that Calculate Root Mean Square ; Calculate square ; Calculate Mean ; Calculate Root ; Driver code
import math NEW_LINE def rmsValue ( arr , n ) : NEW_LINE INDENT square = 0 NEW_LINE mean = 0.0 NEW_LINE root = 0.0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT square += ( arr [ i ] ** 2 ) NEW_LINE DEDENT mean = ( square / ( float ) ( n ) ) NEW_LINE root = math . sqrt ( mean ) NEW_LINE return root NEW_LINE DEDEN...
Program to find the quantity after mixture replacement | Function to calculate the Remaining amount . ; calculate Right hand Side ( RHS ) . ; calculate Amount left by multiply it with original value . ; Driver Code
def Mixture ( X , Y , Z ) : NEW_LINE INDENT result = 0.0 NEW_LINE result1 = 0.0 NEW_LINE result1 = ( ( X - Y ) / X ) NEW_LINE result = pow ( result1 , Z ) NEW_LINE result = result * X NEW_LINE return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 10 NEW_LINE Y = 2 NEW_LINE Z = 2 NEW_LINE p...
Sum of sum of all subsets of a set formed by first N natural numbers | modulo value ; 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 the result ; y must be even now y = y >> 1 y = y / 2 ; function to find ff ( n ) ; In f...
mod = ( int ) ( 1e9 + 7 ) NEW_LINE 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 check ( n ) : NEW_LINE INDENT n = n - 1 NEW_LINE ans = n * n NEW_LINE if ( ...
Program to find LCM of 2 numbers without using GCD | Python 3 program to find LCM of 2 numbers without using GCD ; Function to return LCM of two numbers ; Driver Code
import sys NEW_LINE def findLCM ( a , b ) : NEW_LINE INDENT lar = max ( a , b ) NEW_LINE small = min ( a , b ) NEW_LINE i = lar NEW_LINE while ( 1 ) : NEW_LINE INDENT if ( i % small == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT i += lar NEW_LINE DEDENT DEDENT a = 5 NEW_LINE b = 7 NEW_LINE print ( " LCM ▁ of ▁ " , a...
Smarandache | Python program to print the first ' n ' terms of the Smarandache - Wellin Sequence ; Function to collect first ' n ' prime numbers ; List to store first ' n ' primes ; Function to generate Smarandache - Wellin Sequence ; Storing the first ' n ' prime numbers in a list ; Driver Method
from __future__ import print_function NEW_LINE def primes ( n ) : NEW_LINE INDENT i , j = 2 , 0 NEW_LINE result = [ ] NEW_LINE while j < n : NEW_LINE INDENT flag = True NEW_LINE for item in range ( 2 , int ( i ** 0.5 ) + 1 ) : NEW_LINE INDENT if i % item == 0 and i != item : NEW_LINE INDENT flag = False NEW_LINE break ...
Pentatope number | Function to calculate Pentatope number ; Formula to calculate nth Pentatope number ; Driver Code
def Pentatope_number ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) * ( n + 2 ) * ( n + 3 ) // 24 ) NEW_LINE DEDENT n = 7 NEW_LINE print ( " % sth ▁ Pentatope ▁ number ▁ : ▁ " % n , Pentatope_number ( n ) ) NEW_LINE n = 12 NEW_LINE print ( " % sth ▁ Pentatope ▁ number ▁ : ▁ " % n , Pentatope_number ( n ) ) NEW_LINE
Program for Centered Icosahedral Number | Function to calculate Centered icosahedral number ; Formula to calculate nth Centered icosahedral number ; Driver Code
def centeredIcosahedralNum ( n ) : NEW_LINE INDENT return ( ( 2 * n + 1 ) * ( 5 * n * n + 5 * n + 3 ) // 3 ) NEW_LINE DEDENT n = 10 NEW_LINE print ( centeredIcosahedralNum ( n ) ) NEW_LINE n = 12 NEW_LINE print ( centeredIcosahedralNum ( n ) ) NEW_LINE