text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Smallest number whose sum of digits is square of N | Function to return smallest number whose sum of digits is n ^ 2 ; Driver Code
def smallestNum ( n ) : NEW_LINE INDENT return ( ( n * n % 9 + 1 ) * pow ( 10 , int ( n * n / 9 ) ) - 1 ) NEW_LINE DEDENT N = 4 NEW_LINE print ( smallestNum ( N ) ) NEW_LINE
Second heptagonal numbers | Function to find N - th term in the series ; Driver code ; Function call
def findNthTerm ( n ) : NEW_LINE INDENT print ( n * ( 5 * n + 3 ) // 2 ) NEW_LINE DEDENT N = 4 NEW_LINE findNthTerm ( N ) NEW_LINE
Weakly Prime Numbers | function to check if N is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; function to check if n is a weakly prime Number ; number should be prime ; converting N to string ; loop to change digit at every character one by one . ; loop to store every d...
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 for i in range ( 5 , int ( n ** 0.5 ) + 1 , 6 ) : NEW_LINE INDENT if ( n % i == 0 or...
Unprimeable Numbers | function to check if N is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; function to check if n is a unprimeable Number ; number should be composite ; converting N to string ; loop to change digit at every character one by one . ; loop to store every...
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 for i in range ( 5 , int ( n ** 0.5 ) + 1 , 6 ) : NEW_LINE INDENT if ( n % i == 0 or...
Find the Nth row in Pascal 's Triangle | Function to find the elements of rowIndex in Pascal 's Triangle ; 1 st element of every row is 1 ; Check if the row that has to be returned is the first row ; Generate the previous row ; Generate the elements of the current row by the help of the previous row ; Return the row ; ...
def getRow ( rowIndex ) : NEW_LINE INDENT currow = [ ] NEW_LINE currow . append ( 1 ) NEW_LINE if ( rowIndex == 0 ) : NEW_LINE INDENT return currow NEW_LINE DEDENT prev = getRow ( rowIndex - 1 ) NEW_LINE for i in range ( 1 , len ( prev ) ) : NEW_LINE INDENT curr = prev [ i - 1 ] + prev [ i ] NEW_LINE currow . append ( ...
All possible values of floor ( N / K ) for all values of K | Function to print all possible values of floor ( N / K ) ; Iterate from 1 to N + 1 ; Driver code
def allQuotients ( N ) : NEW_LINE INDENT s = set ( ) NEW_LINE for k in range ( 1 , N + 2 ) : NEW_LINE INDENT s . add ( N // k ) NEW_LINE DEDENT for it in s : NEW_LINE INDENT print ( it , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE allQuotients ( N ) NEW_LINE DED...
Greatest odd factor of an even number | Python3 program for the above approach ; Function to print greatest odd factor ; Initialize i with 1 ; Iterate till i <= pow_2 ; find the pow ( 2 , i ) ; If factor is odd , then print the number and break ; Given Number ; Function Call
import math NEW_LINE def greatestOddFactor ( n ) : NEW_LINE INDENT pow_2 = int ( math . log ( n , 2 ) ) NEW_LINE i = 1 NEW_LINE while i <= pow_2 : NEW_LINE INDENT fac_2 = ( 2 ** i ) NEW_LINE if ( n % fac_2 == 0 ) : NEW_LINE if ( ( n // fac_2 ) % 2 == 1 ) : NEW_LINE INDENT print ( n // fac_2 ) NEW_LINE break NEW_LINE DE...
Find the element in a linked list with frequency at least N / 3 | Structure of a node for the linked list ; Function to find and return the element with frequency of at least N / 3 ; Candidates for being the required majority element ; Store the frequencies of the respective candidates ; Iterate all nodes ; Increase fr...
class Node : NEW_LINE INDENT def __init__ ( self , s ) : NEW_LINE INDENT self . i = s NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def Majority_in_linklist ( head ) : NEW_LINE INDENT s , t = " " , " " NEW_LINE p , q = 0 , 0 NEW_LINE ptr = None NEW_LINE while head != None : NEW_LINE INDENT if s == head . i : NEW_L...
Form smallest number using indices of numbers chosen from Array with sum less than S | Function to find the minimum number which have maximum length ; Find Maximum length of number ; Find minimum number WHich have maximum length ; Driver Code
def max_number ( arr , sum ) : NEW_LINE INDENT frac = [ 0 ] * 9 NEW_LINE maxi = - 10 ** 9 NEW_LINE pos = 0 NEW_LINE for i in range ( 9 ) : NEW_LINE INDENT frac [ i ] = sum // arr [ i ] NEW_LINE if ( frac [ i ] > maxi ) : NEW_LINE INDENT pos = i NEW_LINE maxi = frac [ i ] NEW_LINE DEDENT DEDENT an = str ( ( pos + 1 ) ) ...
Check if given intervals can be made non | Function to check if two intervals overlap with each other ; Condition to check if the intervals overlap ; Function to check if there is a existing overlapping intervals ; Path compression ; Union of two intervals Returns True if there is a overlapping with the same another in...
def checkOverlapping ( a , b ) : NEW_LINE INDENT a , b = max ( a , b ) , min ( a , b ) NEW_LINE if b [ 0 ] <= a [ 0 ] <= b [ 1 ] : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def find ( a , i ) : NEW_LINE INDENT if a [ i ] == i : NEW_LINE INDENT return i NEW_LINE DEDENT a [ i ] = find ( a ,...
Number formed after K times repeated addition of smallest divisor of N | Python3 program to find the Kth number formed after repeated addition of smallest divisor of N ; If N is even ; If N is odd ; Add smallest divisor to N ; Updated N is even ; Driver code
import math NEW_LINE def FindValue ( N , K ) : NEW_LINE INDENT if ( N % 2 == 0 ) : NEW_LINE INDENT N = N + 2 * K NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 2 , ( int ) ( math . sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT N = N + i NEW_LINE N = N + 2...
Find last digit in factorial | Python3 program to find last digit in factorial n . ; Explicitly handle all numbers less than or equal to 4 ; For all numbers greater than 4 the last digit is 0 ; Driver code
def lastDigitFactorial ( n ) : NEW_LINE INDENT if ( n == 0 ) : return 1 NEW_LINE elif ( n <= 2 ) : return n NEW_LINE elif ( n == 3 ) : return 6 NEW_LINE elif ( n == 4 ) : return 4 NEW_LINE else : return 0 NEW_LINE DEDENT print ( lastDigitFactorial ( 6 ) ) NEW_LINE
Program to convert Hexa | Function to convert Haxadecimal to BCD ; Iterating through the digits ; Conversion into equivalent BCD ; Driver code ; Function call
def HexaDecimaltoBCD ( str ) : NEW_LINE INDENT for i in range ( len ( str ) ) : NEW_LINE INDENT print ( " { 0:04b } " . format ( int ( str [ i ] , 16 ) ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT str = "11F " NEW_LINE HexaDecimaltoBCD ( str ) NEW_LINE
Find the sum of the first Nth Heptadecagonal Number | Function to find the N - th heptadecagonal number ; Formula to calculate nth heptadecagonal number ; Function to find the sum of the first N heptadecagonal numbers ; Variable to store the sum ; Iterate from 1 to N ; Finding the sum ; Driver code
def heptadecagonal_num ( n ) : NEW_LINE INDENT return ( ( 15 * n * n ) - 13 * n ) // 2 NEW_LINE DEDENT def sum_heptadecagonal_num ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT summ += heptadecagonal_num ( i ) NEW_LINE DEDENT return summ NEW_LINE DEDENT if __name__ == ' _ _ mai...
Program to check if N is a Centered Pentagonal Number or not | Python3 program for the above approach ; Function to check if number N is a centered pentagonal number ; Condition to check if N is a centered pentagonal number ; Given Number ; Function call
import numpy as np NEW_LINE def isCenteredpentagonal ( N ) : NEW_LINE INDENT n = ( 5 + np . sqrt ( 40 * N - 15 ) ) / 10 NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT N = 6 NEW_LINE if ( isCenteredpentagonal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_...
Program to check if N is a Dodecagonal Number | Python3 program for the above approach ; Function to check if number N is a dodecagonal number or not ; Condition to check if the N is a dodecagonal number ; Given Number ; Function call
import numpy as np NEW_LINE def isdodecagonal ( N ) : NEW_LINE INDENT n = ( 4 + np . sqrt ( 20 * N + 16 ) ) / 10 NEW_LINE return ( n - int ( n ) ) == 0 NEW_LINE DEDENT N = 12 NEW_LINE if ( isdodecagonal ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Logarithm tricks for Competitive Programming | Python3 implementation to find the previous and next power of K ; Function to return the highest power of k less than or equal to n ; Function to return the smallest power of k greater than or equal to n ; Driver Code
from math import log NEW_LINE def prevPowerofK ( n , k ) : NEW_LINE INDENT p = ( int ) ( log ( n ) / log ( k ) ) ; NEW_LINE return pow ( k , p ) ; NEW_LINE DEDENT def nextPowerOfK ( n , k ) : NEW_LINE INDENT return prevPowerofK ( n , k ) * k ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 NEW_...
Sum of all composite numbers lying in the range [ L , R ] for Q queries | Prefix array to precompute the sum of all composite number ; Function that return number num if num is composite else return 0 ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to precompute the sum...
pref = [ 0 ] * 100001 NEW_LINE def isComposite ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n...
Probability of getting a perfect square when a random number is chosen in a given range | Python3 implementation to find the probability of getting a perfect square number ; Function to return the probability of getting a perfect square number in a range ; Count of perfect squares ; Total numbers in range l to r ; Calc...
import math NEW_LINE def findProb ( l , r ) : NEW_LINE INDENT countOfPS = ( math . floor ( math . sqrt ( r ) ) - math . ceil ( math . sqrt ( l ) ) + 1 ) NEW_LINE total = r - l + 1 NEW_LINE prob = countOfPS / total NEW_LINE return prob NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 16 NEW_LINE R =...
Check whether two strings can be made equal by increasing prefixes | check whether the first string can be converted to the second string by increasing the ASCII value of prefix string of first string ; length of two strings ; If lengths are not equal ; store the difference of ASCII values ; difference of first element...
def find ( s1 , s2 ) : NEW_LINE INDENT len__ = len ( s1 ) NEW_LINE len_1 = len ( s2 ) NEW_LINE if ( len__ != len_1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT d = [ 0 for i in range ( len__ ) ] NEW_LINE d [ 0 ] = ord ( s2 [ 0 ] ) - ord ( s1 [ 0 ] ) NEW_LINE for i in range ( 1 , len__ , 1 ) : NEW_LINE INDENT if ( s...
Find the length of factorial of a number in any given base | A optimised program to find the number of digits in a factorial in base b ; Returns the number of digits present in n ! in base b Since the result can be large long long is used as return type ; factorial of - ve number doesn 't exists ; base case ; Use Kamen...
from math import log10 , floor NEW_LINE def findDigits ( n , b ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT M_PI = 3.141592 NEW_LINE M_E = 2.7182 NEW_LINE if ( n <= 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT x = ( ( n * log10 ( n / M_E ) + log10 ( 2 * M_PI * n ) / 2.0 ) ) / ( log10 ( ...
Sum of all Non | Python3 implementation to find the sum of all non - fibonacci numbers in a range from L to R ; Array to precompute the sum of non - fibonacci numbers ; Function to find if a number is a perfect square ; Function that returns N if N is non - fibonacci number ; N is Fibinacci if one of 5 * n * n + 4 or 5...
from math import sqrt NEW_LINE pref = [ 0 ] * 100010 NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT s = int ( sqrt ( x ) ) NEW_LINE if ( s * s == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def isNonFibonacci ( n ) : NEW_LINE INDENT x = 5 * n * n NEW_LINE if ( isPerfectSquare ( ...
Count twin prime pairs in an Array | Python 3 program to count Twin Prime pairs in array ; A utility function to check if the number n is prime or not ; Base Cases ; Check to skip middle five numbers in below loop ; If n is divisible by i and i + 2 then it is not prime ; A utility function that check if n1 and n2 are T...
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 for i in range ( 5 , int ( sqrt ( n ) ) + 1 , 6 ) : N...
Fill the missing numbers in the array of N natural numbers such that arr [ i ] not equal to i | Function to fill the position with arr [ i ] = 0 ; Inserting all elements in missing [ ] set from 1 to N ; Inserting unfilled positions ; Removing allocated_elements ; Loop for filling the positions with arr [ i ] != i ; Che...
def solve ( arr , n ) : NEW_LINE INDENT unfilled_indices = { } NEW_LINE missing = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT missing [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT unfilled_indices [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT del...
Find Kth number from sorted array formed by multiplying any two numbers in the array | Function to find number of pairs ; Negative and Negative ; Add Possible Pairs ; Positive and Positive ; Add Possible pairs ; Negative and Positive ; Add Possible pairs ; Function to find the kth element in the list ; Separate Positiv...
def check ( x , pos , neg , k ) : NEW_LINE INDENT pairs = 0 NEW_LINE p = len ( neg ) - 1 NEW_LINE nn = len ( neg ) - 1 NEW_LINE pp = len ( pos ) - 1 NEW_LINE for i in range ( len ( neg ) ) : NEW_LINE INDENT while ( p >= 0 and neg [ i ] * neg [ p ] <= x ) : NEW_LINE INDENT p -= 1 NEW_LINE DEDENT pairs += min ( nn - p , ...
Find root of a number using Newton 's method | Function to return the square root of a number using Newtons method ; Assuming the sqrt of n as n only ; To count the number of iterations ; Calculate more closed x ; Check for closeness ; Update root ; Driver code
def squareRoot ( n , l ) : NEW_LINE INDENT x = n NEW_LINE count = 0 NEW_LINE while ( 1 ) : NEW_LINE INDENT count += 1 NEW_LINE root = 0.5 * ( x + ( n / x ) ) NEW_LINE if ( abs ( root - x ) < l ) : NEW_LINE INDENT break NEW_LINE DEDENT x = root NEW_LINE DEDENT return root NEW_LINE DEDENT if __name__ == " _ _ main _ _ " ...
Count the occurrence of Nth term in first N terms of Van Eck 's sequence | Python3 program to count the occurrence of nth term in first n terms of Van Eck 's sequence ; Utility function to compute Van Eck 's sequence ; Loop to generate sequence ; Check if sequence [ i ] has occured previously or is new to sequence ; ...
MAX = 10000 NEW_LINE sequence = [ 0 ] * ( MAX + 1 ) ; NEW_LINE def vanEckSequence ( ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( sequence [ j ] == sequence [ i ] ) : NEW_LINE INDENT sequence [ i + 1 ] = i - j ; NEW_LINE break ; NEW_LINE DEDENT ...
Count the occurrence of Nth term in first N terms of Van Eck 's sequence | Python3 program to count the occurrence of nth term in first n terms of Van Eck 's sequence ; Utility function to compute Van Eck 's sequence ; Loop to generate sequence ; Check if sequence [ i ] has occured previously or is new to sequence ; ...
MAX = 10000 NEW_LINE sequence = [ 0 ] * ( MAX + 1 ) ; NEW_LINE def vanEckSequence ( ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( sequence [ j ] == sequence [ i ] ) : NEW_LINE INDENT sequence [ i + 1 ] = i - j ; NEW_LINE break ; NEW_LINE DEDENT ...
Goldbach 's Weak Conjecture for Odd numbers | Function to check if a number can be represent as as a sum of 3 prime ; Driver code
def check ( n ) : NEW_LINE INDENT if n % 2 == 1 and n > 5 : NEW_LINE INDENT print ( ' YES ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' NO ' ) NEW_LINE DEDENT DEDENT def main ( ) : NEW_LINE INDENT a = 3 NEW_LINE b = 7 NEW_LINE check ( a ) NEW_LINE check ( b ) NEW_LINE DEDENT main ( ) NEW_LINE
Number of ways to reach ( X , Y ) in a matrix starting from the origin | Python3 implementation of the approach ; To store the factorial and factorial mod inverse of the numbers ; Function to find ( a ^ m1 ) % mod ; Function to find the factorial of all the numbers ; Function to find the factorial modinverse of all the...
N = 1000005 NEW_LINE mod = ( int ) ( 1e9 + 7 ) NEW_LINE factorial = [ 0 ] * N ; NEW_LINE modinverse = [ 0 ] * N ; NEW_LINE def power ( a , m1 ) : NEW_LINE INDENT if ( m1 == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( m1 == 1 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT elif ( m1 == 2 ) : NEW_LINE INDENT r...
Find Nth even length palindromic number formed using digits X and Y | Python3 program to find nth even palindromic number of only even length composing of 4 ' s ▁ and ▁ 5' s . ; Utility function to compute n 'th palindrome number ; Calculate the length from above formula as discussed above ; Calculate rank for length ...
from math import ceil , log2 NEW_LINE def solve ( n , x , y ) : NEW_LINE INDENT length = ceil ( log2 ( n + 2 ) ) - 1 ; NEW_LINE rank = n - ( 1 << length ) + 1 ; NEW_LINE left = " " ; right = " " ; NEW_LINE for i in range ( length - 1 , - 1 , - 1 ) : NEW_LINE INDENT mask = ( 1 << i ) ; NEW_LINE bit = ( mask & rank ) ; N...
Maximum of all the integers in the given level of Pascal triangle | Function for the binomial coefficient ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to return the maximum value in the nth level of the Pascal 's triangle ; Driver...
def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ [ 0 for i in range ( k + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT C [ ...
Length of the smallest sub | Python 3 program to find the length of the smallest substring consisting of maximum distinct characters ; Find maximum distinct characters in any string ; Initialize all character 's count with 0 ; Increase the count in array if a character is found ; size of given string ; Find maximum di...
NO_OF_CHARS = 256 NEW_LINE def max_distinct_char ( str , n ) : NEW_LINE INDENT count = [ 0 ] * NO_OF_CHARS NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ ord ( str [ i ] ) ] += 1 NEW_LINE DEDENT max_distinct = 0 NEW_LINE for i in range ( NO_OF_CHARS ) : NEW_LINE INDENT if ( count [ i ] != 0 ) : NEW_LINE INDENT...
Find two co | Python3 implementation of the approach ; Function to find the required numbers ; GCD of the given numbers ; Printing the required numbers ; Driver code
from math import gcd NEW_LINE def findNumbers ( a , b ) : NEW_LINE INDENT __gcd = gcd ( a , b ) ; NEW_LINE print ( ( a // __gcd ) , ( b // __gcd ) ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 12 ; b = 16 ; NEW_LINE findNumbers ( a , b ) ; NEW_LINE DEDENT
Find the remaining balance after the transaction | Function to find the balance ; Check if the transaction can be successful or not ; Transaction is successful ; Transaction is unsuccessful ; Driver Code
def findBalance ( x , bal ) : NEW_LINE INDENT if ( x % 10 == 0 and ( x + 1.50 ) <= bal ) : NEW_LINE INDENT print ( round ( bal - x - 1.50 , 2 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( round ( bal , 2 ) ) NEW_LINE DEDENT DEDENT x = 50 NEW_LINE bal = 100.50 NEW_LINE findBalance ( x , bal ) NEW_LINE
Count number of pairs in array having sum divisible by K | SET 2 | Python Program to count pairs whose sum divisible by 'K ; Program to count pairs whose sum divisible by ' K ' ; Create a frequency array to count occurrences of all remainders when divided by K ; To store count of pairs . ; Traverse the array , compute ...
' NEW_LINE def countKdivPairs ( A , n , K ) : NEW_LINE INDENT freq = [ 0 for i in range ( K ) ] NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT rem = A [ i ] % K NEW_LINE ans += freq [ ( K - rem ) % K ] NEW_LINE freq [ rem ] += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ...
Minimum number of Bottles visible when a bottle can be enclosed inside another Bottle | Python3 code for the above approach ; Driver code ; Find the solution
def min_visible_bottles ( arr , n ) : NEW_LINE INDENT m = dict ( ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ arr [ i ] ] = m . get ( arr [ i ] , 0 ) + 1 NEW_LINE ans = max ( ans , m [ arr [ i ] ] ) NEW_LINE DEDENT print ( " Minimum ▁ number ▁ of " , " Visible ▁ Bottles ▁ are : ▁ " , ans ) NEW...
Number of even substrings in a string of digits | Return the even number substrings . ; If current digit is even , add count of substrings ending with it . The count is ( i + 1 ) ; Driven Program
def evenNumSubstring ( str ) : NEW_LINE INDENT length = len ( str ) NEW_LINE count = 0 NEW_LINE for i in range ( 0 , length , 1 ) : NEW_LINE INDENT temp = ord ( str [ i ] ) - ord ( '0' ) NEW_LINE if ( temp % 2 == 0 ) : NEW_LINE INDENT count += ( i + 1 ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ ==...
Find the final sequence of the array after performing given operations | Function that generates the array b [ ] when n is even ; Fill the first half of the final array with reversed sequence ; Fill the second half ; Function that generates the array b [ ] when n is odd ; Fill the first half of the final array with rev...
def solveEven ( n , arr , b ) : NEW_LINE INDENT left = n - 1 NEW_LINE for i in range ( ( n // 2 ) ) : NEW_LINE INDENT b [ i ] = arr [ left ] NEW_LINE left = left - 2 NEW_LINE if ( left < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT right = 0 NEW_LINE for i in range ( n // 2 , n , 1 ) : NEW_LINE INDENT b [ i ] = a...
Find the sum of the first half and second half elements of an array | Function to find the sum of the first half elements and second half elements of an array ; Add elements in first half sum ; Add elements in the second half sum ; Driver Code ; Function call
def sum_of_elements ( arr , n ) : NEW_LINE INDENT sumfirst = 0 ; NEW_LINE sumsecond = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i < n // 2 ) : NEW_LINE INDENT sumfirst += arr [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT sumsecond += arr [ i ] ; NEW_LINE DEDENT DEDENT print ( " Sum ▁ of ▁ first ▁ half ▁...
Sequence with sum K and minimum sum of absolute differences between consecutive elements | Function to return the minimized sum ; If k is divisible by n then the answer will be 0 ; Else the answer will be 1 ; Driver code
def minimum_sum ( n , k ) : NEW_LINE INDENT if ( k % n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT return 1 NEW_LINE DEDENT n = 3 NEW_LINE k = 56 NEW_LINE print ( minimum_sum ( n , k ) ) NEW_LINE
Print first N terms of Lower Wythoff sequence | Python3 implementation of the approach ; Function to print the first n terms of the lower Wythoff sequence ; Calculate value of phi ; Find the numbers ; a ( n ) = floor ( n * phi ) ; Print the nth numbers ; Driver code
from math import sqrt , floor NEW_LINE def lowerWythoff ( n ) : NEW_LINE INDENT phi = ( 1 + sqrt ( 5 ) ) / 2 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = floor ( i * phi ) ; NEW_LINE print ( ans , end = " " ) ; NEW_LINE if ( i != n ) : NEW_LINE INDENT print ( " , ▁ " , end = " " ) ; NEW_LINE DEDENT D...
Create new linked list from two given linked list with greater element at each node | Node class ; Function to insert node in a linked list ; Function which returns new linked list ; Compare for greater node ; Driver Code ; First linked list ; Second linked list
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def insert ( root , item ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . data = item NEW_LINE temp . next = None NEW_LINE if ( root == None ) : NEW_LINE INDENT root = t...
Count of quadruplets from range [ L , R ] having GCD equal to K | Python 3 implementation of the approach ; Function to return the count of quadruplets having gcd = k ; To store the required count ; Check every quadruplet pair whether its gcd is k ; Return the required count ; Driver code
from math import gcd NEW_LINE def countQuadruplets ( l , r , k ) : NEW_LINE INDENT count = 0 NEW_LINE for u in range ( l , r + 1 , 1 ) : NEW_LINE INDENT for v in range ( l , r + 1 , 1 ) : NEW_LINE INDENT for w in range ( l , r + 1 , 1 ) : NEW_LINE INDENT for x in range ( l , r + 1 , 1 ) : NEW_LINE INDENT if ( gcd ( gcd...
Find an index such that difference between product of elements before and after it is minimum | Function to return the index i such that the absolute difference between product of elements up to that index and the product of rest of the elements of the array is minimum ; To store the required index ; Prefix product arr...
def findIndex ( a , n ) : NEW_LINE INDENT res , min_diff = None , float ( ' inf ' ) NEW_LINE prod = [ None ] * n NEW_LINE prod [ 0 ] = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prod [ i ] = prod [ i - 1 ] * a [ i ] NEW_LINE DEDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT curr_diff = abs ( ( prod...
Print all numbers whose set of prime factors is a subset of the set of the prime factors of X | Python3 program to implement the above approach ; Function to print all the numbers ; Iterate for every element in the array ; Find the gcd ; Iterate till gcd is 1 of number and x ; Divide the number by gcd ; Find the new gc...
from math import gcd NEW_LINE def printNumbers ( a , n , x ) : NEW_LINE INDENT flag = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT num = a [ i ] NEW_LINE g = gcd ( num , x ) NEW_LINE while ( g != 1 ) : NEW_LINE INDENT num //= g NEW_LINE g = gcd ( num , x ) NEW_LINE DEDENT if ( num == 1 ) : NEW_LINE INDENT flag...
Find the final radiations of each Radiated Stations | Function to print the final radiations ; Function to create the array of the resultant radiations ; Resultant radiations ; Declaring index counter for left and right radiation ; Effective radiation for left and right case ; Radiation for i - th station ; Radiation i...
def printf ( rStation , n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT print ( rStation [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE DEDENT def radiated_Station ( station , n ) : NEW_LINE INDENT rStation = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in ran...
An in | A utility function to reverse string str [ low . . high ] ; Cycle leader algorithm to move all even positioned elements at the end . ; odd index ; even index ; keep the back - up of element at new position ; The main function to transform a string . This function mainly uses cycleLeader ( ) to transform ; Step ...
def Reverse ( string : list , low : int , high : int ) : NEW_LINE INDENT while low < high : NEW_LINE INDENT string [ low ] , string [ high ] = string [ high ] , string [ low ] NEW_LINE low += 1 NEW_LINE high -= 1 NEW_LINE DEDENT DEDENT def cycleLeader ( string : list , shift : int , len : int ) : NEW_LINE INDENT i = 1 ...
Program to find the maximum difference between the index of any two different numbers | Function to return the maximum difference ; Iteratively check from back ; Different numbers ; Iteratively check from the beginning ; Different numbers ; Driver code
def findMaximumDiff ( a , n ) : NEW_LINE INDENT ind1 = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ 0 ] != a [ i ] ) : NEW_LINE INDENT ind1 = i NEW_LINE break NEW_LINE DEDENT DEDENT ind2 = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( a [ n - 1 ] != a [ i ] ) : NEW_LINE INDENT...
Find the Kth node in the DFS traversal of a given subtree in a Tree | Python3 program to find the Kth node in the DFS traversal of the subtree of given vertex V in a Tree ; To store nodes ; To store the current index of vertex in DFS ; To store the starting index and ending index of vertex in the DFS traversal array ; ...
N = 100005 NEW_LINE n = 10 NEW_LINE tree = [ [ ] for i in range ( N ) ] NEW_LINE static int n ; NEW_LINE static ArrayList tree = new ArrayList ( ) ; NEW_LINE currentIdx = 0 NEW_LINE startIdx = [ 0 for i in range ( n ) ] NEW_LINE endIdx = [ 0 for i in range ( n ) ] NEW_LINE p = [ 0 for i in range ( n ) ] NEW_LINE def Ad...
Sum of the series Kn + ( K ( n | Function to return sum ; Driver code
def sum ( k , n ) : NEW_LINE INDENT sum = ( pow ( k , n + 1 ) - pow ( k - 1 , n + 1 ) ) ; NEW_LINE return sum ; NEW_LINE DEDENT n = 3 ; NEW_LINE K = 3 ; NEW_LINE print ( sum ( K , n ) ) ; NEW_LINE
Check whether factorial of N is divisible by sum of first N natural numbers | Function to check whether a number is prime or not . ; Count variable to store the number of factors of 'num ; Counting the number of factors ; If number is prime return true ; Function to check for divisibility ; if ' n ' equals 1 then divis...
def is_prime ( num ) : NEW_LINE ' NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , num + 1 ) : NEW_LINE INDENT if i * i > num : NEW_LINE INDENT break NEW_LINE DEDENT if ( ( num ) % i == 0 ) : NEW_LINE INDENT if ( i * i != ( num ) ) : NEW_LINE INDENT count += 2 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NE...
Number of subarrays having sum of the form k ^ m , m >= 0 | Python3 implementation of the above approach ; Function to count number of sub - arrays whose sum is k ^ p where p >= 0 ; If m [ a + b ] = c , then add c to the current sum . ; Increase count of prefix sum . ; If m [ a + b ] = c , then add c to the current sum...
from collections import defaultdict NEW_LINE MAX = 100005 NEW_LINE def partial_sum ( prefix_sum , arr , n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT prefix_sum [ i ] = ( prefix_sum [ i - 1 ] + arr [ i - 1 ] ) NEW_LINE DEDENT return prefix_sum NEW_LINE DEDENT def countSubarrays ( arr , n , k ) : ...
Given two binary strings perform operation until B > 0 and print the result | Python 3 implementation of the approach ; Function to return the required result ; Reverse the strings ; Count the number of set bits in b ; To store the powers of 2 ; power [ i ] = pow ( 2 , i ) % mod ; To store the final answer ; Add power ...
mod = 1000000007 NEW_LINE def BitOperations ( a , n , b , m ) : NEW_LINE INDENT a = a [ : : - 1 ] NEW_LINE b = b [ : : - 1 ] NEW_LINE c = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( b [ i ] == '1' ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT power = [ None ] * n NEW_LINE power [ 0 ] = 1 NEW_LINE for i i...
Sum of sides of largest and smallest child polygons possible from a given polygon | Function to find the sum of largest and smallest secondary polygons if possible ; Count edges of primary polygon ; Calculate edges present in the largest secondary polygon ; Driver Code ; Given Exterior Angle
def secondary_polygon ( Angle ) : NEW_LINE INDENT edges_primary = 360 // Angle NEW_LINE if edges_primary >= 6 : NEW_LINE INDENT edges_max_secondary = edges_primary // 2 NEW_LINE return edges_max_secondary + 3 NEW_LINE DEDENT else : NEW_LINE INDENT return " Not ▁ Possible " NEW_LINE DEDENT DEDENT if __name__ == ' _ _ ma...
Print prime numbers with prime sum of digits in an array | Python3 implementation of the above approach ; Function to store the primes ; Function to return the sum of digits ; Function to print additive primes ; If the number is prime ; Check if it 's digit sum is prime ; Driver code
from math import sqrt NEW_LINE def sieve ( maxEle , prime ) : NEW_LINE INDENT prime [ 0 ] , prime [ 1 ] = 1 , 1 NEW_LINE for i in range ( 2 , int ( sqrt ( maxEle ) ) + 1 ) : NEW_LINE INDENT if ( not prime [ i ] ) : NEW_LINE INDENT for j in range ( 2 * i , maxEle + 1 , i ) : NEW_LINE INDENT prime [ j ] = 1 NEW_LINE DEDE...
Find the Nth term of the series 9 , 45 , 243 , 1377 | Function to return the nth term of the given series ; nth term ; Driver code
def nthterm ( n ) : NEW_LINE INDENT An = ( 1 ** n + 2 ** n ) * ( 3 ** n ) NEW_LINE return An ; NEW_LINE DEDENT n = 3 NEW_LINE print ( nthterm ( n ) ) NEW_LINE
Count the numbers < N which have equal number of divisors as K | Function to return the count of the divisors of a number ; Count the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ; While i divides n ; This condition is to handle the case when n is a prime number > 2 ; Count the...
def countDivisors ( n ) : NEW_LINE INDENT x , ans = 0 , 1 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT x += 1 NEW_LINE n = n / 2 NEW_LINE DEDENT ans = ans * ( x + 1 ) NEW_LINE for i in range ( 3 , int ( n ** 1 / 2 ) + 1 , 2 ) : NEW_LINE INDENT x = 0 NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT x += 1 NEW_LINE n =...
Find the nth term of the series 0 , 8 , 64 , 216 , 512 , . . . | Function to return the nth term of the given series ; Common difference ; First term ; nth term ; nth term of the given series ; Driver code
def term ( n ) : NEW_LINE INDENT d = 2 NEW_LINE a1 = 0 NEW_LINE An = a1 + ( n - 1 ) * d NEW_LINE An = An ** 3 NEW_LINE return An ; NEW_LINE DEDENT n = 5 NEW_LINE print ( term ( n ) ) NEW_LINE
Find the type of triangle from the given sides | Function to find the type of triangle with the help of sides ; Driver Code ; Function Call
def checkTypeOfTriangle ( a , b , c ) : NEW_LINE INDENT sqa = pow ( a , 2 ) NEW_LINE sqb = pow ( b , 2 ) NEW_LINE sqc = pow ( c , 2 ) NEW_LINE if ( sqa == sqa + sqb or sqb == sqa + sqc or sqc == sqa + sqb ) : NEW_LINE INDENT print ( " Right - angled ▁ Triangle " ) NEW_LINE DEDENT elif ( sqa > sqc + sqb or sqb > sqa + s...
Count the number of intervals in which a given value lies | Python3 program to count the number of intervals in which a given value lies ; Function to count the number of intervals in which a given value lies ; Variables to store overall minimumimum and maximumimum of the intervals ; Frequency array to keep track of ho...
MAX_VAL = 200000 NEW_LINE def countIntervals ( arr , V , N ) : NEW_LINE INDENT minimum = float ( " inf " ) NEW_LINE maximum = 0 NEW_LINE freq = [ 0 ] * ( MAX_VAL ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT li = arr [ i ] [ 0 ] NEW_LINE freq [ li ] = freq [ li ] + 1 NEW_LINE ri = arr [ i ] [ 1 ] NEW_LINE freq ...
Check whether the triangle is valid or not if angles are given | Function to check if sum of the three angles is 180 or not ; Check condition ; Driver code ; function calling and print output
def Valid ( a , b , c ) : NEW_LINE INDENT if ( ( a + b + c == 180 ) and a != 0 and b != 0 and c != 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 60 NEW_LINE b = 40 NEW_LINE c = 80 NEW_LINE if ( Valid ( a...
Split N ^ 2 numbers into N groups of equal sum | Function to print N groups of equal sum ; No . of Groups ; n / 2 pairs ; Driver code
def printGroups ( n ) : NEW_LINE INDENT x = 1 NEW_LINE y = n * n NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n // 2 + 1 ) : NEW_LINE INDENT print ( " { " , x , " , " , y , " } " , end = " ▁ " ) NEW_LINE x += 1 NEW_LINE y -= 1 NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ ...
Program to find the Break Even Point | Python 3 program to find Break Even Point ; Function to calculate Break Even Point ; Calculating number of articles to be sold ; Driver Code
import math NEW_LINE def breakEvenPoint ( exp , S , M ) : NEW_LINE INDENT earn = S - M NEW_LINE if res != 0 : NEW_LINE res = math . ceil ( exp / earn ) NEW_LINE else : NEW_LINE res = float ( ' inf ' ) NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT exp = 3550 NEW_LINE S = 90 NEW_LI...
Minimize the value of N by applying the given operations | function to return the product of distinct prime factors of a numberdef minSteps ( str ) : ; find distinct prime ; Driver code
def minimum ( n ) : NEW_LINE INDENT product = 1 NEW_LINE i = 2 NEW_LINE while i * i <= n : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT while n % i == 0 : NEW_LINE INDENT n = n / i NEW_LINE DEDENT product = product * i NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT if n >= 2 : NEW_LINE INDENT product = product * n NEW_LI...
N digit numbers divisible by 5 formed from the M digits | Function to find the count of all possible N digit numbers which are divisible by 5 formed from M digits ; If it is not possible to form n digit number from the given m digits without repetition ; If both zero and five exists ; Remaining N - 1 iterations ; Remai...
def numbers ( n , arr , m ) : NEW_LINE INDENT isZero = 0 NEW_LINE isFive = 0 NEW_LINE result = 0 NEW_LINE if ( m < n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT isZero = 1 NEW_LINE DEDENT if ( arr [ i ] == 5 ) : NEW_LINE INDENT isFive = 1...
Program to find the smallest element among three elements | Python implementation to find the smallest of three elements
a , b , c = 5 , 7 , 10 NEW_LINE if ( a <= b and a <= c ) : NEW_LINE INDENT print ( a , " is ▁ the ▁ smallest " ) NEW_LINE DEDENT elif ( b <= a and b <= c ) : NEW_LINE INDENT print ( b , " is ▁ the ▁ smallest " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( c , " is ▁ the ▁ smallest " ) NEW_LINE DEDENT
Find subsequences with maximum Bitwise AND and Bitwise OR | Function to find the maximum sum ; Maximum AND is maximum element ; Maximum OR is bitwise OR of all . ; Driver code
def maxSum ( a , n ) : NEW_LINE INDENT maxAnd = max ( a ) NEW_LINE maxOR = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxOR |= a [ i ] NEW_LINE DEDENT print ( maxAnd + maxOR ) NEW_LINE DEDENT n = 4 NEW_LINE a = [ 3 , 5 , 6 , 1 ] NEW_LINE maxSum ( a , n ) NEW_LINE
Count Magic squares in a grid | Python3 program to count magic squares ; function to check is subgrid is Magic Square ; Elements of grid must contain all numbers from 1 to 9 , sum of all rows , columns and diagonals must be same , i . e . , 15. ; Function to count total Magic square subgrids ; if condition true skip ch...
R = 3 NEW_LINE C = 4 NEW_LINE def magic ( a , b , c , d , e , f , g , h , i ) : NEW_LINE INDENT s1 = set ( [ a , b , c , d , e , f , g , h , i ] ) NEW_LINE s2 = set ( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] ) NEW_LINE if ( s1 == s2 and ( a + b + c ) == 15 and ( d + e + f ) == 15 and ( g + h + i ) == 15 and ( a + d + g ) ...
Sum of minimum elements of all subarrays | Function to return required minimum sum ; getting number of element strictly larger than A [ i ] on Left . ; get elements from stack until element greater than A [ i ] found ; getting number of element larger than A [ i ] on Right . ; get elements from stack until element grea...
def sumSubarrayMins ( A , n ) : NEW_LINE INDENT left , right = [ None ] * n , [ None ] * n NEW_LINE s1 , s2 = [ ] , [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT cnt = 1 NEW_LINE while len ( s1 ) > 0 and s1 [ - 1 ] [ 0 ] > A [ i ] : NEW_LINE INDENT cnt += s1 [ - 1 ] [ 1 ] NEW_LINE s1 . pop ( ) NEW_LINE DEDENT...
Minimum and Maximum element of an array which is divisible by a given number k | Python 3 implementation of the above approach ; Function to find the minimum element ; Function to find the maximum element ; Driver code
import sys NEW_LINE def getMin ( arr , n , k ) : NEW_LINE INDENT res = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % k == 0 ) : NEW_LINE INDENT res = min ( res , arr [ i ] ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def getMax ( arr , n , k ) : NEW_LINE INDENT res = 0 NEW_LINE f...
Print a number containing K digits with digital root D | Function to find a number ; If d is 0 , k has to be 1 ; Print k - 1 zeroes ; Driver code
def printNumberWithDR ( k , d ) : NEW_LINE INDENT if d == 0 and k != 1 : NEW_LINE INDENT print ( - 1 , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( d , end = " " ) NEW_LINE k -= 1 NEW_LINE while k : NEW_LINE INDENT print ( 0 , end = " " ) NEW_LINE k -= 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ ...
Count number of integers less than or equal to N which has exactly 9 divisors | Function to count numbers having exactly 9 divisors ; Sieve array , initially prime [ i ] = i ; use sieve concept to store the first prime factor of every number ; mark all factors of i ; check for all numbers if they can be expressed in fo...
def countNumbers ( n ) : NEW_LINE INDENT c = 0 NEW_LINE limit = int ( n ** ( 0.5 ) ) NEW_LINE prime = [ i for i in range ( limit + 1 ) ] NEW_LINE i = 2 NEW_LINE while i * i <= limit : NEW_LINE INDENT if prime [ i ] == i : NEW_LINE INDENT for j in range ( i * i , limit + 1 , i ) : NEW_LINE INDENT if prime [ j ] == j : N...
Interprime | Utility 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 given number is interprime or not ; Smallest Interprime is 4 So the number less than 4 can not be a Interprime ; Calculate first prime numb...
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...
Find the unit place digit of sum of N factorials | Function to find the unit 's place digit ; Let us write for cases when N is smaller than or equal to 4. ; We know following ( 1 ! + 2 ! + 3 ! + 4 ! ) % 10 = 3 ; Driver code
def get_unit_digit ( N ) : NEW_LINE INDENT if ( N == 0 or N == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( N == 2 ) : NEW_LINE INDENT return 3 NEW_LINE DEDENT elif ( N == 3 ) : NEW_LINE INDENT return 9 NEW_LINE DEDENT else : NEW_LINE INDENT return 3 NEW_LINE DEDENT DEDENT N = 1 NEW_LINE for N in range ( 11 ) ...
Sum of squares of Fibonacci numbers | Python3 program to find sum of squares of Fibonacci numbers in O ( Log n ) time . ; Create an array for memoization ; Returns n 'th Fibonacci number using table f[] ; Base cases ; If fib ( n ) is already computed ; Applying above formula [ Note value n & 1 is 1 if n is odd , else 0...
MAX = 1000 NEW_LINE f = [ 0 for i in range ( MAX ) ] NEW_LINE def fib ( n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n == 1 or n == 2 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if f [ n ] : NEW_LINE INDENT return f [ n ] NEW_LINE DEDENT if n & 1 : NEW_LINE INDENT k = ( n + 1 ) // 2 NEW_...
Number of solutions for the equation x + y + z <= n | function to find the number of solutions for the equation x + y + z <= n , such that 0 <= x <= X , 0 <= y <= Y , 0 <= z <= Z . ; to store answer ; for values of x ; for values of y ; maximum possible value of z ; if z value greater than equals to 0 then only it is v...
def NumberOfSolutions ( x , y , z , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( x + 1 ) : NEW_LINE INDENT for j in range ( y + 1 ) : NEW_LINE INDENT temp = n - i - j NEW_LINE if temp >= 0 : NEW_LINE INDENT temp = min ( temp , z ) NEW_LINE ans += temp + 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DED...
Program to find the Nth term of series 5 , 12 , 21 , 32 , 45. ... . . | calculate Nth term of series ; Driver code
def nthTerm ( n ) : NEW_LINE INDENT return n ** 2 + 4 * n ; NEW_LINE DEDENT N = 4 NEW_LINE print ( nthTerm ( N ) ) NEW_LINE
Numbers less than N which are product of exactly two distinct prime numbers | Python 3 program to find numbers that are product of exactly two distinct prime numbers ; Function to check whether a number is a PerfectSquare or not ; Function to check if a number is a product of exactly two distinct primes ; Function to f...
import math NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sr = math . sqrt ( x ) NEW_LINE return ( ( sr - math . floor ( sr ) ) == 0 ) NEW_LINE DEDENT def isProduct ( num ) : NEW_LINE INDENT cnt = 0 NEW_LINE i = 2 NEW_LINE while cnt < 2 and i * i <= num : NEW_LINE INDENT while ( num % i == 0 ) : NEW_LINE INDENT ...
Program to find the Nth term of the series 3 , 20 , 63 , 144 , 230 , Γ’ €¦ Γ’ €¦ | calculate Nth term of series ; return final sum ; Driver code
def nthTerm ( n ) : NEW_LINE INDENT return 2 * pow ( n , 3 ) + pow ( n , 2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE print ( nthTerm ( N ) ) NEW_LINE DEDENT
Find Nth number of the series 1 , 6 , 15 , 28 , 45 , ... . . | Function for calculating Nth term of series ; Driver code ; Taking n as 4 ; Printing the nth term
def NthTerm ( N ) : NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE print ( NthTerm ( N ) ) NEW_LINE DEDENT
Program to print the Sum of series | 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 ( ( N * ( N + 1 ) * ( 2 * N - 5 ) + 4 * N ) / 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE print ( findSum ( N ) ) NEW_LINE DEDENT
Program to find the Nth term of series | Python3 program to find N - th term of the series : 9 , 23 , 45 , 75 , 113 , 159. . ... . ; calculate Nth term of series ; Driver Code ; Get the value of N ; Find the Nth term and print it
def nthTerm ( N ) : NEW_LINE INDENT return ( ( 3 * N * N ) - ( 6 * N ) + 2 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE print ( nthTerm ( n ) ) NEW_LINE DEDENT
Program to find the value of tan ( 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 ; Function to find the value of cos ( n - theta ) ; store required answer ; use to toggle sign in sequence . ; calculate numerat...
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 INDENT for j in range ( 0 , i + 1 ) : NEW_LINE INDENT if j == 0 or j == i : NEW_LINE INDENT nCr [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LI...
Pizza cut problem ( Or Circle Division by Lines ) | Function for finding maximum pieces with n cuts . ; Driver code
def findMaximumPieces ( n ) : NEW_LINE INDENT return int ( 1 + n * ( n + 1 ) / 2 ) NEW_LINE DEDENT print ( findMaximumPieces ( 3 ) ) NEW_LINE
Optimum location of point to minimize total distance | A Python3 program to find optimum location and total cost ; Class defining a point ; Class defining a line of ax + by + c = 0 form ; Method to get distance of point ( x , y ) from point p ; Utility method to compute total distance all points when choose point on gi...
import math NEW_LINE class Optimum_distance : NEW_LINE INDENT class Point : NEW_LINE INDENT def __init__ ( self , x , y ) : NEW_LINE INDENT self . x = x NEW_LINE self . y = y NEW_LINE DEDENT DEDENT class Line : NEW_LINE INDENT def __init__ ( self , a , b , c ) : NEW_LINE INDENT self . a = a NEW_LINE self . b = b NEW_LI...
Program to find Sum of the series 1 * 3 + 3 * 5 + ... . | Python program to find sum of first n terms ; Sn = n * ( 4 * n * n + 6 * n - 1 ) / 3 ; number of terms to be included in the sum ; find the Sn
def calculateSum ( n ) : NEW_LINE INDENT return ( n * ( 4 * n * n + 6 * n - 1 ) / 3 ) ; NEW_LINE DEDENT n = 4 NEW_LINE print ( " Sum ▁ = " , calculateSum ( n ) ) NEW_LINE
Find all duplicate and missing numbers in given permutation array of 1 to N | Function to find the duplicate and the missing elements over the range [ 1 , N ] ; Stores the missing and duplicate numbers in the array arr [ ] ; Traverse the given array arr [ ] ; Check if the current element is not same as the element at i...
def findElements ( arr , N ) : NEW_LINE INDENT i = 0 ; NEW_LINE missing = [ ] ; NEW_LINE duplicate = set ( ) ; NEW_LINE while ( i != N ) : NEW_LINE INDENT if ( arr [ i ] != arr [ arr [ i ] - 1 ] ) : NEW_LINE INDENT t = arr [ i ] NEW_LINE arr [ i ] = arr [ arr [ i ] - 1 ] NEW_LINE arr [ t - 1 ] = t NEW_LINE DEDENT else ...
Triplet with no element divisible by 3 and sum N | Function to print a , b and c ; first loop ; check for 1 st number ; second loop ; check for 2 nd number ; third loop ; Check for 3 rd number ; Driver Code
def printCombination ( n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( i % 3 != 0 ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE INDENT if ( j % 3 != 0 ) : NEW_LINE INDENT for k in range ( 1 , n ) : NEW_LINE INDENT if ( k % 3 != 0 and ( i + j + k ) == n ) : NEW_LINE INDENT print ( i , j ,...
Program to find the percentage of difference between two numbers | Function to calculate the percentage ; Driver code ; Function calling
def percent ( a , b ) : NEW_LINE INDENT result = int ( ( ( b - a ) * 100 ) / a ) NEW_LINE return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a , b = 20 , 25 NEW_LINE print ( percent ( a , b ) , " % " ) NEW_LINE DEDENT
Numbers with sum of digits equal to the sum of digits of its all prime factor | maximum size of number ; array to store smallest prime factor of number ; array to store sum of digits of a number ; boolean array to check given number is countable for required answer or not . ; prefix array to store answer ; Calculating ...
MAXN = 100005 NEW_LINE spf = [ 0 ] * MAXN NEW_LINE sum_digits = [ 0 ] * MAXN NEW_LINE isValid = [ 0 ] * MAXN NEW_LINE ans = [ 0 ] * MAXN NEW_LINE def Smallest_prime_factor ( ) : NEW_LINE INDENT for i in range ( 1 , MAXN ) : NEW_LINE INDENT spf [ i ] = i NEW_LINE DEDENT for i in range ( 4 , MAXN , 2 ) : NEW_LINE INDENT ...
Count numbers which can be represented as sum of same parity primes | ; Function to calculate count ; Driver Code
/ * Python program to Count numbers NEW_LINE which can be represented as NEW_LINE sum of same parity primes * / NEW_LINE def calculate ( array , size ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( array [ i ] % 2 == 0 and array [ i ] != 0 and array [ i ] != 2 ) : NEW_LINE INDENT c...
N | Python3 program to answer queries for N - th prime factor of a number ; 2 - D vector that stores prime factors ; Function to pre - store prime factors of all numbers till 10 ^ 6 ; calculate unique prime factors for every number till 10 ^ 6 ; find prime factors ; store if prime factor ; Function that returns answer ...
from math import sqrt , ceil NEW_LINE N = 10001 NEW_LINE v = [ [ ] for i in range ( N ) ] NEW_LINE def preprocess ( ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT num = i NEW_LINE for j in range ( 2 , ceil ( sqrt ( num ) ) + 1 ) : NEW_LINE INDENT if ( num % j == 0 ) : NEW_LINE INDENT v [ i ] . append ( ...
Program to find HCF ( Highest Common Factor ) of 2 Numbers | Recursive function to return gcd of a and b ; Driver program to test above function
def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT a = 98 NEW_LINE b = 56 NEW_LINE if ( gcd ( a , b ) ) : NEW_LINE INDENT print ( ' GCD ▁ of ' , a , ' and ' , b , ' is ' , gcd ( a , b ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' ...
Largest number with maximum trailing nines which is less than N and greater than N | function to count no of digits ; function to implement above approach ; if difference between power and n doesn 't exceed d ; loop to build a number from the appropriate no of digits containing only 9 ; if the build number is same as o...
def dig ( a ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( a > 0 ) : NEW_LINE INDENT a /= 10 NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def required_number ( num , n , d ) : NEW_LINE INDENT flag = 0 NEW_LINE power = 0 NEW_LINE a = 0 NEW_LINE for i in range ( num , 0 , - 1 ) : NEW_LINE INDENT pow...
Egg Dropping Puzzle with 2 Eggs and K Floors | Python3 program to find optimal number of trials for k floors and 2 eggs . ; Driver Code
import math as mt NEW_LINE def twoEggDrop ( k ) : NEW_LINE INDENT return mt . ceil ( ( - 1.0 + mt . sqrt ( 1 + 8 * k ) ) / 2 ) NEW_LINE DEDENT k = 100 NEW_LINE print ( twoEggDrop ( k ) ) NEW_LINE
Program to find the Area and Volume of Icosahedron | Python3 program to find the Area and volume of Icosahedron ; Function to find area of Icosahedron ; Formula to calculate area ; Function to find volume of Icosahedron ; Formula to calculate volume ; Driver Code ; Function call to find area of Icosahedron . ; Function...
from math import sqrt NEW_LINE def findArea ( a ) : NEW_LINE INDENT area = 5 * sqrt ( 3 ) * a * a NEW_LINE return area NEW_LINE DEDENT def findVolume ( a ) : NEW_LINE INDENT volume = ( ( 5 / 12 ) * ( 3 + sqrt ( 5 ) ) * a * a * a ) NEW_LINE return volume NEW_LINE DEDENT a = 5 NEW_LINE print ( " Area : ▁ " , findArea ( a...
Total number of ways to place X and Y at n places such that no two X are together | Function to return number of ways ; for n = 1 ; for n = 2 ; iterate to find Fibonacci term ; total number of places
def ways ( n ) : NEW_LINE INDENT first = 2 ; NEW_LINE second = 3 ; NEW_LINE res = 0 ; NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT res = first + second ; NEW_LINE first = second ; NEW_LINE second = res ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT n = 7 ; NEW_LINE print ( " Total ▁ ways ▁ are : ▁ " , ways (...
Number of digits in N factorial to the power N | python3 program to find count of digits in N factorial raised to N ; we take sum of logarithms as explained in the approach ; multiply the result with n ; Driver Code
import math NEW_LINE def countDigits ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans += math . log10 ( i ) NEW_LINE DEDENT ans = ans * n NEW_LINE return 1 + math . floor ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE print ( countDigi...
Program to convert centimeter into meter and kilometer | Python3 program to convert centimeter into meter and kilometer ; Converting centimeter into meter and kilometer ; Driver Code
cm = 1000 ; NEW_LINE meter = cm / 100.0 ; NEW_LINE kilometer = cm / 100000.0 ; NEW_LINE print ( " Length ▁ in ▁ meter ▁ = ▁ " , meter , " m " ) ; NEW_LINE print ( " Length ▁ in ▁ Kilometer ▁ = ▁ " , kilometer , " km " ) ; NEW_LINE