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