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 digit one by one at index j ; Driver code
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 n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isWeaklyPrimeNum ( N ) : NEW_LINE INDENT if ( isPrime ( N ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT s = str ( N ) NEW_LINE for j in range ( len ( s ) ) : NEW_LINE INDENT str1 = s NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT c = str ( i ) NEW_LINE str1 = str1 [ : j ] + c + str1 [ j + 1 : ] NEW_LINE Num = int ( str1 ) NEW_LINE if ( str1 [ j ] != s [ j ] and isPrime ( Num ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT n = 294001 NEW_LINE if ( isWeaklyPrimeNum ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 digit one by one at index j ; Driver code ; Function Call
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 n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isUnPrimeableNum ( N ) : NEW_LINE INDENT if ( isPrime ( N ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT s = str ( N ) NEW_LINE for j in range ( len ( s ) ) : NEW_LINE INDENT str1 = s NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT c = str ( i ) NEW_LINE str1 = str1 [ : j ] + c + str1 [ j + 1 : ] NEW_LINE Num = int ( str1 ) NEW_LINE if ( str1 [ j ] != s [ j ] and isPrime ( Num ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT n = 200 NEW_LINE if ( isUnPrimeableNum ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 ; Driver Program
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 ( curr ) NEW_LINE DEDENT currow . append ( 1 ) NEW_LINE return currow NEW_LINE DEDENT n = 3 NEW_LINE arr = getRow ( n ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( i == ( len ( arr ) - 1 ) ) : NEW_LINE INDENT print ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ i ] , end = " , ▁ " ) NEW_LINE DEDENT DEDENT
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 DEDENT
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 DEDENT i += 1 NEW_LINE DEDENT DEDENT N = 8642 NEW_LINE greatestOddFactor ( N ) NEW_LINE
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 frequency of candidate s ; Increase frequency of candidate t ; Set the new sting as candidate for majority ; Set the new sting as second candidate for majority ; Decrease the frequency ; Check the frequency of two final selected candidate linklist ; Increase the frequency of first candidate ; Increase the frequency of second candidate ; Return the string with higher frequency ; Driver code
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_LINE INDENT p = p + 1 NEW_LINE DEDENT else : NEW_LINE INDENT if t == head . i : NEW_LINE INDENT q = q + 1 NEW_LINE DEDENT else : NEW_LINE INDENT if p == 0 : NEW_LINE INDENT s = head . i NEW_LINE p = 1 NEW_LINE DEDENT else : NEW_LINE INDENT if q == 0 : NEW_LINE INDENT t = head . i NEW_LINE q = 1 NEW_LINE DEDENT else : NEW_LINE INDENT p = p - 1 NEW_LINE q = q - 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT head = head . next NEW_LINE DEDENT head = ptr NEW_LINE p = 0 NEW_LINE q = 0 NEW_LINE while head != None : NEW_LINE INDENT if s == head . i : NEW_LINE INDENT p = 1 NEW_LINE DEDENT else : NEW_LINE INDENT if t == head . i : NEW_LINE INDENT q = 1 NEW_LINE DEDENT DEDENT head = head . next NEW_LINE DEDENT if p > q : NEW_LINE INDENT return s NEW_LINE DEDENT else : NEW_LINE INDENT return t NEW_LINE DEDENT DEDENT ptr = None NEW_LINE head = Node ( " geeks " ) NEW_LINE head . next = Node ( " geeks " ) NEW_LINE head . next . next = Node ( " abcd " ) NEW_LINE head . next . next . next = Node ( " game " ) NEW_LINE head . next . next . next . next = Node ( " game " ) NEW_LINE head . next . next . next . next . next = Node ( " knight " ) NEW_LINE head . next . next . next . next . next . next = Node ( " harry " ) NEW_LINE head . next . next . next . next . next . next . next = Node ( " geeks " ) NEW_LINE print ( Majority_in_linklist ( head ) ) NEW_LINE
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 ) ) * maxi NEW_LINE sum -= maxi * arr [ pos ] NEW_LINE ans = [ i for i in an ] NEW_LINE for i in range ( maxi ) : NEW_LINE INDENT for j in range ( 1 , 10 ) : NEW_LINE INDENT if ( sum + arr [ pos ] - arr [ j - 1 ] >= 0 ) : NEW_LINE INDENT ans [ i ] = str ( j ) NEW_LINE sum += arr [ pos ] - arr [ j - 1 ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( maxi == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return " " . join ( ans ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 2 , 4 , 6 , 5 , 4 , 2 , 3 ] NEW_LINE s = 13 NEW_LINE print ( max_number ( arr , s ) ) NEW_LINE DEDENT
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 interval ; Both have same another overlapping interval ; Function to check if the intervals can be added by X to form non - overlapping intervals ; If the intervals overlaps we will union them ; There is no cycle ; Driver Code
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 , a [ i ] ) NEW_LINE return a [ i ] NEW_LINE DEDENT def union ( a , x , y ) : NEW_LINE INDENT xs = find ( a , x ) NEW_LINE ys = find ( a , y ) NEW_LINE if xs == ys : NEW_LINE INDENT return True NEW_LINE DEDENT a [ ys ] = xs NEW_LINE return False NEW_LINE DEDENT def checkNonOverlapping ( arr , n ) : NEW_LINE INDENT dsu = [ i for i in range ( n + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if checkOverlapping ( arr [ i ] , \ arr [ j ] ) : NEW_LINE INDENT if union ( dsu , i , j ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 4 ] , [ 2 , 2 ] , [ 2 , 3 ] ] NEW_LINE n = len ( arr ) NEW_LINE print ( " YES " if checkNonOverlapping ( arr , n ) else " NO " ) NEW_LINE DEDENT
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 * ( K - 1 ) NEW_LINE DEDENT print ( N ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 9 NEW_LINE K = 4 NEW_LINE FindValue ( N , K ) NEW_LINE DEDENT
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__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( sum_heptadecagonal_num ( n ) ) NEW_LINE DEDENT
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_LINE DEDENT
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_LINE K = 2 NEW_LINE print ( prevPowerofK ( N , K ) , end = " ▁ " ) NEW_LINE print ( nextPowerOfK ( N , K ) ) NEW_LINE DEDENT
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 of all composite numbers upto 100000 ; checkcomposite ( ) return the number i if i is composite else return 0 ; Function to print the sum for each query ; Function to prsum of all composite numbers between ; Function that pre computes the sum of all composite numbers ; Iterate over all Queries to print the sum ; Driver code ; Queries ; Function that print the the sum of all composite number in Range [ L , R ]
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 % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def preCompute ( ) : NEW_LINE INDENT for i in range ( 1 , 100001 ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + isComposite ( i ) NEW_LINE DEDENT DEDENT def printSum ( L , R ) : NEW_LINE INDENT print ( pref [ R ] - pref [ L - 1 ] ) NEW_LINE DEDENT def printSumcomposite ( arr , Q ) : NEW_LINE INDENT preCompute ( ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT Q = 2 NEW_LINE arr = [ [ 10 , 13 ] , [ 12 , 21 ] ] NEW_LINE printSumcomposite ( arr , Q ) NEW_LINE DEDENT
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 ; Calculating probability ; Driver code ; Function Call
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 = 25 NEW_LINE print ( findProb ( L , R ) ) NEW_LINE DEDENT
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 ; traverse through the string ; the ASCII value of the second string should be greater than or equal to first string , if it is violated return false . ; store the difference of ASCII values ; the difference of ASCII values should be in descending order ; if the difference array is not in descending order ; if all the ASCII values of characters of first string is less than or equal to the second string and the difference array is in descending order , return true ; Driver code ; create two strings ; check whether the first string can be converted to the second string
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 ( s1 [ i ] > s2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT d [ i ] = ord ( s2 [ i ] ) - ord ( s1 [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len__ - 1 ) : NEW_LINE INDENT if ( d [ i ] < d [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " abcd " NEW_LINE s2 = " bcdd " NEW_LINE if ( find ( s1 , s2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 Kamenetsky formula to calculate the number of digits ; Driver Code ; calling findDigits ( Number , Base )
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 ( b ) ) NEW_LINE return floor ( x ) + 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( findDigits ( 4 , 16 ) ) NEW_LINE print ( findDigits ( 5 , 8 ) ) NEW_LINE print ( findDigits ( 12 , 16 ) ) NEW_LINE print ( findDigits ( 19 , 13 ) ) NEW_LINE DEDENT
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 * n * n - 4 or both are perferct square ; Function to precompute sum of non - fibonacci Numbers ; Function to find the sum of all non - fibonacci numbers in a range ; Pre - computation ; Loop to find the sum for each query
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 ( x + 4 ) or isPerfectSquare ( x - 4 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return n NEW_LINE DEDENT DEDENT def compute ( ) : NEW_LINE INDENT for i in range ( 1 , 100001 ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + isNonFibonacci ( i ) NEW_LINE DEDENT DEDENT def printSum ( L , R ) : NEW_LINE INDENT sum = pref [ R ] - pref [ L - 1 ] NEW_LINE print ( sum , end = " ▁ " ) NEW_LINE DEDENT compute ( ) NEW_LINE Q = 2 NEW_LINE arr = [ [ 1 , 5 ] , [ 6 , 10 ] ] NEW_LINE for i in range ( Q ) : NEW_LINE INDENT printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) NEW_LINE DEDENT
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 Twin Primes or not ; Function to find Twin Prime pairs from the given array ; Iterate through all pairs ; Increment count if twin prime pair ; Driver 's code ; Function call to find Twin Primes pair
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 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def twinPrime ( n1 , n2 ) : NEW_LINE INDENT return ( isPrime ( n1 ) and isPrime ( n2 ) and abs ( n1 - n2 ) == 2 ) NEW_LINE DEDENT def countTwinPairs ( 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 ( twinPrime ( arr [ i ] , arr [ j ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countTwinPairs ( arr , n ) ) NEW_LINE DEDENT
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 ; Checking for any arr [ i ] = i ; Finding the suitable position in the array to swap with found i for which arr [ i ] = i ; Checking if the position is present in unfilled_position ; Swapping arr [ i ] & arr [ pos ] ( arr [ pos ] = pos ) ; Function to Print the array ; Driver Code
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 missing [ arr [ i ] ] NEW_LINE DEDENT DEDENT it2 = list ( missing . keys ( ) ) NEW_LINE m = len ( it2 ) NEW_LINE for it in unfilled_indices : NEW_LINE INDENT arr [ it ] = it2 [ m - 1 ] NEW_LINE m -= 1 NEW_LINE DEDENT pos = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == i ) : NEW_LINE INDENT pos = i NEW_LINE DEDENT DEDENT x = 0 NEW_LINE if ( pos != 0 ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( pos != i ) : NEW_LINE INDENT if i in unfilled_indices : NEW_LINE INDENT x = arr [ i ] NEW_LINE arr [ i ] = pos NEW_LINE arr [ pos ] = x NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT printArray ( arr , n ) NEW_LINE DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 7 , 4 , 0 , 3 , 0 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE solve ( arr , n ) NEW_LINE DEDENT
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 Positive and Negative elements ; Sort the Elements ; Binary search ; Return the required answer ; Driver code ; Function call
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 , nn - i ) NEW_LINE DEDENT p = 0 NEW_LINE for i in range ( len ( pos ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT while ( p < len ( pos ) and pos [ i ] * pos [ p ] <= x ) : NEW_LINE INDENT p += 1 NEW_LINE DEDENT pairs += min ( p , i ) NEW_LINE DEDENT p = len ( pos ) - 1 NEW_LINE for i in range ( len ( neg ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT while ( p >= 0 and neg [ i ] * pos [ p ] <= x ) : NEW_LINE INDENT p -= 1 NEW_LINE DEDENT pairs += pp - p NEW_LINE DEDENT return ( pairs >= k ) NEW_LINE DEDENT def kth_element ( a , n , k ) : NEW_LINE INDENT pos , neg = [ ] , [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] >= 0 ) : NEW_LINE INDENT pos . append ( a [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT neg . append ( a [ i ] ) NEW_LINE DEDENT DEDENT pos = sorted ( pos ) NEW_LINE neg = sorted ( neg ) NEW_LINE l = - 10 ** 18 NEW_LINE ans = 0 NEW_LINE r = 10 ** 18 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = ( l + r ) >> 1 NEW_LINE if ( check ( mid , pos , neg , k ) ) : NEW_LINE INDENT ans = mid NEW_LINE r = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT a = [ - 4 , - 2 , 3 , 3 ] NEW_LINE k = 3 NEW_LINE n = len ( a ) NEW_LINE print ( kth_element ( a , n , k ) ) NEW_LINE
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 _ _ " : NEW_LINE INDENT n = 327 NEW_LINE l = 0.00001 NEW_LINE print ( squareRoot ( n , l ) ) 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 ; If occurrence found then the next term will be how far back this last term occured previously ; Utility function to count the occurrence of nth term in first n terms of the sequence ; Get nth term of the sequence ; Count the occurrence of nth term in first n terms of the sequence ; Return count ; Driver code ; Pre - compute Van Eck 's sequence ; Print count of the occurrence of nth term in first n terms of the sequence ; Print count of the occurrence of nth term in first n terms of the 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 DEDENT DEDENT DEDENT def getCount ( n ) : NEW_LINE INDENT nthTerm = sequence [ n - 1 ] ; NEW_LINE count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( sequence [ i ] == nthTerm ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT vanEckSequence ( ) ; NEW_LINE n = 5 ; NEW_LINE print ( getCount ( n ) ) ; NEW_LINE n = 11 ; NEW_LINE print ( getCount ( n ) ) ; 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 ; If occurrence found then the next term will be how far back this last term occured previously ; Utility function to count the occurrence of nth term in first n terms of the sequence ; Initialize count as 1 ; Increment count if ( i + 1 ) th term is non - zero ; Previous occurrence of sequence [ i ] will be it ( i - sequence [ i + 1 ] ) th position ; Return the count of occurrence ; Driver code ; Pre - compute Van Eck 's sequence ; Print count of the occurrence of nth term in first n terms of the sequence ; Print count of the occurrence of nth term in first n terms of the 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 DEDENT DEDENT DEDENT def getCount ( n ) : NEW_LINE INDENT count = 1 ; NEW_LINE i = n - 1 ; NEW_LINE while ( sequence [ i + 1 ] != 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE i = i - sequence [ i + 1 ] ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT vanEckSequence ( ) ; NEW_LINE n = 5 ; NEW_LINE print ( getCount ( n ) ) ; NEW_LINE n = 11 ; NEW_LINE print ( getCount ( n ) ) ; 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 numbers ; Function to return nCr ; Function to return the number of ways to reach ( X , Y ) in a matrix with the given moves starting from the origin ; Driver code
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 return ( a * a ) % mod ; NEW_LINE DEDENT elif ( m1 & 1 ) : NEW_LINE INDENT return ( a * power ( power ( a , m1 // 2 ) , 2 ) ) % mod ; NEW_LINE DEDENT else : NEW_LINE INDENT return power ( power ( a , m1 // 2 ) , 2 ) % mod ; NEW_LINE DEDENT DEDENT def factorialfun ( ) : NEW_LINE INDENT factorial [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT factorial [ i ] = ( factorial [ i - 1 ] * i ) % mod ; NEW_LINE DEDENT DEDENT def modinversefun ( ) : NEW_LINE INDENT modinverse [ N - 1 ] = power ( factorial [ N - 1 ] , mod - 2 ) % mod ; NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT modinverse [ i ] = ( modinverse [ i + 1 ] * ( i + 1 ) ) % mod ; NEW_LINE DEDENT DEDENT def binomial ( n , r ) : NEW_LINE INDENT if ( r > n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT a = ( factorial [ n ] * modinverse [ n - r ] ) % mod ; NEW_LINE a = ( a * modinverse [ r ] ) % mod ; NEW_LINE return a ; NEW_LINE DEDENT def ways ( x , y ) : NEW_LINE INDENT factorialfun ( ) ; NEW_LINE modinversefun ( ) ; NEW_LINE if ( ( 2 * x - y ) % 3 == 0 and ( 2 * y - x ) % 3 == 0 ) : NEW_LINE INDENT m = ( 2 * x - y ) // 3 ; NEW_LINE n = ( 2 * y - x ) // 3 ; NEW_LINE return binomial ( n + m , n ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 3 ; y = 3 ; NEW_LINE print ( ways ( x , y ) ) ; NEW_LINE DEDENT
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 L ; Mask to check if i 't bit is set or not ; If bit is set append '5' else append '4' ; Driver Code
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 ) ; NEW_LINE if ( bit ) : NEW_LINE INDENT left += y ; NEW_LINE right += y ; NEW_LINE DEDENT else : NEW_LINE INDENT left += x ; NEW_LINE right += x ; NEW_LINE DEDENT DEDENT right = right [ : : - 1 ] ; NEW_LINE res = left + right ; NEW_LINE return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 23 ; NEW_LINE x = '4' ; NEW_LINE y = '5' ; NEW_LINE ans = solve ( n , x , y ) ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT
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 code
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 [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return C [ n ] [ k ] NEW_LINE DEDENT def findMax ( n ) : NEW_LINE INDENT return binomialCoeff ( n , n // 2 ) NEW_LINE DEDENT n = 5 NEW_LINE print ( findMax ( n ) ) NEW_LINE
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 distinct characters in any string ; result ; Brute force approach to find all substrings ; We have to check here both conditions together 1. substring ' s ▁ distinct ▁ characters ▁ is ▁ equal ▁ ▁ to ▁ maximum ▁ distinct ▁ characters ▁ ▁ 2 . ▁ substring ' s length should be minimum ; Driver Code ; Input String
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 max_distinct += 1 NEW_LINE DEDENT DEDENT return max_distinct NEW_LINE DEDENT def smallesteSubstr_maxDistictChar ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE max_distinct = max_distinct_char ( str , n ) NEW_LINE minl = n NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT subs = str [ i : j ] NEW_LINE subs_lenght = len ( subs ) NEW_LINE sub_distinct_char = max_distinct_char ( subs , subs_lenght ) NEW_LINE if ( subs_lenght < minl and max_distinct == sub_distinct_char ) : NEW_LINE INDENT minl = subs_lenght NEW_LINE DEDENT DEDENT DEDENT return minl NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " AABBBCBB " NEW_LINE l = smallesteSubstr_maxDistictChar ( str ) ; NEW_LINE print ( " The ▁ length ▁ of ▁ the ▁ smallest ▁ substring " , " consisting ▁ of ▁ maximum ▁ distinct " , " characters ▁ : " , l ) NEW_LINE DEDENT
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 the remainder and add k - remainder value hash count to ans ; Count number of ( A [ i ] , ( K - rem ) % K ) pairs ; Increment count of remainder in hash map ; Driver code
' 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 _ _ ' : NEW_LINE INDENT A = [ 2 , 2 , 1 , 7 , 5 , 3 ] NEW_LINE n = len ( A ) NEW_LINE K = 4 NEW_LINE print ( countKdivPairs ( A , n , K ) ) NEW_LINE DEDENT
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_LINE DEDENT n = 8 NEW_LINE arr = [ 1 , 1 , 2 , 3 , 4 , 5 , 5 , 4 ] NEW_LINE min_visible_bottles ( arr , n ) NEW_LINE
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__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = [ '1' , '2' , '3' , '4' ] NEW_LINE print ( evenNumSubstring ( str ) ) NEW_LINE DEDENT
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 reversed sequence ; Fill the second half ; Function to find the final array b [ ] after n operations of given type ; Create the array b ; If the array size is even ; Print the final array elements ; Driver code
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 ] = arr [ right ] NEW_LINE right = right + 2 NEW_LINE if ( right > n - 2 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT def solveOdd ( n , arr , b ) : NEW_LINE INDENT left = n - 1 NEW_LINE for i in range ( n // 2 + 1 ) : 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 = 1 NEW_LINE for i in range ( n // 2 + 1 , n , 1 ) : NEW_LINE INDENT b [ i ] = arr [ right ] NEW_LINE right = right + 2 NEW_LINE if ( right > n - 2 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT def solve ( n , arr ) : NEW_LINE INDENT b = [ 0 for i in range ( n ) ] NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT solveEven ( n , arr , b ) NEW_LINE DEDENT else : NEW_LINE INDENT solveOdd ( n , arr , b ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( b [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE solve ( n , arr ) NEW_LINE DEDENT
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 ▁ elements ▁ is " , sumfirst , end = " " ) ; NEW_LINE print ( " Sum ▁ of ▁ second ▁ half ▁ elements ▁ is " , sumsecond , end = " " ) ; NEW_LINE DEDENT arr = [ 20 , 30 , 60 , 10 , 25 , 15 , 40 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE sum_of_elements ( arr , n ) ; NEW_LINE
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 DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; NEW_LINE lowerWythoff ( n ) ; NEW_LINE DEDENT
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 = temp NEW_LINE DEDENT else : NEW_LINE INDENT ptr = root NEW_LINE while ( ptr . next != None ) : NEW_LINE INDENT ptr = ptr . next NEW_LINE DEDENT ptr . next = temp NEW_LINE DEDENT return root NEW_LINE DEDENT def newList ( root1 , root2 ) : NEW_LINE INDENT ptr1 = root1 NEW_LINE ptr2 = root2 NEW_LINE root = None NEW_LINE while ( ptr1 != None ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . next = None NEW_LINE if ( ptr1 . data < ptr2 . data ) : NEW_LINE INDENT temp . data = ptr2 . data NEW_LINE DEDENT else : NEW_LINE INDENT temp . data = ptr1 . data NEW_LINE DEDENT if ( root == None ) : NEW_LINE INDENT root = temp NEW_LINE DEDENT else : NEW_LINE INDENT ptr = root NEW_LINE while ( ptr . next != None ) : NEW_LINE INDENT ptr = ptr . next NEW_LINE DEDENT ptr . next = temp NEW_LINE DEDENT ptr1 = ptr1 . next NEW_LINE ptr2 = ptr2 . next NEW_LINE DEDENT return root NEW_LINE DEDENT def display ( root ) : NEW_LINE INDENT while ( root != None ) : NEW_LINE INDENT print ( root . data , " - > " , end = " ▁ " ) NEW_LINE root = root . next NEW_LINE DEDENT print ( " ▁ " ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = None NEW_LINE root2 = None NEW_LINE root = None NEW_LINE root1 = insert ( root1 , 5 ) NEW_LINE root1 = insert ( root1 , 2 ) NEW_LINE root1 = insert ( root1 , 3 ) NEW_LINE root1 = insert ( root1 , 8 ) NEW_LINE print ( " First ▁ List : ▁ " , end = " ▁ " ) NEW_LINE display ( root1 ) NEW_LINE root2 = insert ( root2 , 1 ) NEW_LINE root2 = insert ( root2 , 7 ) NEW_LINE root2 = insert ( root2 , 4 ) NEW_LINE root2 = insert ( root2 , 5 ) NEW_LINE print ( " Second ▁ List : ▁ " , end = " ▁ " ) NEW_LINE display ( root2 ) NEW_LINE root = newList ( root1 , root2 ) NEW_LINE print ( " New ▁ List : ▁ " , end = " ▁ " ) NEW_LINE display ( root ) NEW_LINE DEDENT
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 ( u , v ) , gcd ( w , x ) ) == k ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l = 1 NEW_LINE r = 10 NEW_LINE k = 2 NEW_LINE print ( countQuadruplets ( l , r , k ) ) NEW_LINE DEDENT
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 array ; Compute the product array ; Iterate the product array to find the index ; Driver code
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 [ n - 1 ] // prod [ i ] ) - prod [ i ] ) NEW_LINE if curr_diff < min_diff : NEW_LINE INDENT min_diff = curr_diff NEW_LINE res = i NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 2 , 5 , 7 , 2 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findIndex ( arr , N ) ) NEW_LINE DEDENT
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 gcdg ; If the number is 1 at the end then print the number ; If no numbers have been there ; Driver Code
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 = True ; NEW_LINE print ( a [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if ( not flag ) : NEW_LINE INDENT print ( " There ▁ are ▁ no ▁ such ▁ numbers " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 60 NEW_LINE a = [ 2 , 5 , 10 , 7 , 17 ] NEW_LINE n = len ( a ) NEW_LINE printNumbers ( a , n , x ) NEW_LINE DEDENT
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 increment for left stations ; Radiation increment for right stations ; Print the resultant radiation for each of the stations ; Driver code ; 1 - based indexing
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 range ( 1 , n + 1 ) : NEW_LINE INDENT li = i - 1 NEW_LINE ri = i + 1 NEW_LINE lRad = station [ i ] - 1 NEW_LINE rRad = station [ i ] - 1 NEW_LINE rStation [ i ] += station [ i ] NEW_LINE while ( li >= 1 and lRad >= 1 ) : NEW_LINE INDENT rStation [ li ] += lRad NEW_LINE lRad -= 1 NEW_LINE li -= 1 NEW_LINE DEDENT while ( ri <= n and rRad >= 1 ) : NEW_LINE INDENT rStation [ ri ] += rRad NEW_LINE rRad -= 1 NEW_LINE ri += 1 NEW_LINE DEDENT DEDENT printf ( rStation , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT station = [ 0 , 7 , 9 , 12 , 2 , 5 ] NEW_LINE n = len ( station ) - 1 NEW_LINE radiated_Station ( station , n ) NEW_LINE DEDENT
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 1 : Find the largest prefix subarray of the form 3 ^ k + 1 ; Step 2 : Apply cycle leader algorithm for the largest subarrau ; Step 4.1 : Reverse the second half of first subarray ; Step 4.2 : Reverse the first half of second sub - string ; Step 4.3 Reverse the second half of first sub - string and first half of second sub - string together ; Increase the length of first subarray ; Driver Code
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 NEW_LINE while i < len : NEW_LINE INDENT j = i NEW_LINE item = string [ j + shift ] NEW_LINE while True : NEW_LINE INDENT if j & 1 : NEW_LINE INDENT j = len // 2 + j // 2 NEW_LINE DEDENT else : NEW_LINE INDENT j //= 2 NEW_LINE DEDENT string [ j + shift ] , item = item , string [ j + shift ] NEW_LINE if j == i : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT i *= 3 NEW_LINE DEDENT DEDENT def moveNumberToSecondHalf ( string : list ) : NEW_LINE INDENT k , lenFirst = 0 , 0 NEW_LINE lenRemaining = len ( string ) NEW_LINE shift = 0 NEW_LINE while lenRemaining : NEW_LINE INDENT k = 0 NEW_LINE while pow ( 3 , k ) + 1 <= lenRemaining : NEW_LINE INDENT k += 1 NEW_LINE DEDENT lenFirst = pow ( 3 , k - 1 ) + 1 NEW_LINE lenRemaining -= lenFirst NEW_LINE cycleLeader ( string , shift , lenFirst ) NEW_LINE Reverse ( string , shift // 2 , shift - 1 ) NEW_LINE Reverse ( string , shift , shift + lenFirst // 2 - 1 ) NEW_LINE Reverse ( string , shift // 2 , shift + lenFirst // 2 - 1 ) NEW_LINE shift += lenFirst NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " a1b2c3d4e5f6g7" NEW_LINE string = list ( string ) NEW_LINE moveNumberToSecondHalf ( string ) NEW_LINE print ( ' ' . join ( string ) ) NEW_LINE DEDENT
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 ind2 = ( n - 1 - i ) NEW_LINE break NEW_LINE DEDENT DEDENT return max ( ind1 , ind2 ) NEW_LINE DEDENT a = [ 1 , 2 , 3 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( findMaximumDiff ( a , n ) ) NEW_LINE
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 ; To store the DFS of vertex 1 ; Function to add edge between two nodes ; Initialize the vectors ; Function to perform DFS of a vertex 1. stores the DFS of the vertex 1 in vector p , 2. store the start index of DFS of every vertex 3. store the end index of DFS of every vertex ; store staring index of node ch ; store ending index ; Function to find the Kth node in DFS of vertex V ; check if kth number exits or not ; number of nodes ; add edges ; store DFS of 1 st node
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 Add_edge ( u , v ) : NEW_LINE INDENT tree [ u ] . append ( v ) NEW_LINE tree [ v ] . append ( u ) NEW_LINE DEDENT def intisalise ( ) : NEW_LINE INDENT pass NEW_LINE DEDENT def Dfs ( ch , par ) : NEW_LINE INDENT global currentIdx NEW_LINE p [ currentIdx ] = ch NEW_LINE startIdx [ ch ] = currentIdx NEW_LINE currentIdx += 1 NEW_LINE for c in tree [ ch ] : NEW_LINE INDENT if ( c != par ) : NEW_LINE INDENT Dfs ( c , ch ) NEW_LINE DEDENT DEDENT endIdx [ ch ] = currentIdx - 1 NEW_LINE DEDENT def findNode ( v , k ) : NEW_LINE INDENT k += startIdx [ v ] - 1 NEW_LINE if ( k <= endIdx [ v ] ) : NEW_LINE INDENT return p [ k ] NEW_LINE DEDENT return - 1 NEW_LINE DEDENT n = 9 NEW_LINE Add_edge ( 1 , 2 ) NEW_LINE Add_edge ( 1 , 3 ) NEW_LINE Add_edge ( 1 , 4 ) NEW_LINE Add_edge ( 3 , 5 ) NEW_LINE Add_edge ( 3 , 7 ) NEW_LINE Add_edge ( 5 , 6 ) NEW_LINE Add_edge ( 5 , 8 ) NEW_LINE Add_edge ( 7 , 9 ) NEW_LINE intisalise ( ) NEW_LINE Dfs ( 1 , 0 ) NEW_LINE v , k = 3 , 4 NEW_LINE print ( findNode ( v , k ) ) NEW_LINE
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 divisibility is possible ; Else check whether ' n + 1' is prime or not ; If ' n + 1' is prime then ' n ! ' is not divisible by 'n*(n+1)/2 ; else divisibility occurs ; Test for n = 3 ; Test for n = 4
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 NEW_LINE DEDENT DEDENT DEDENT if ( count == 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def is_divisible ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return " YES " NEW_LINE DEDENT else : NEW_LINE DEDENT ' NEW_LINE INDENT if ( is_prime ( n + 1 ) ) : NEW_LINE INDENT return " NO " NEW_LINE DEDENT else : NEW_LINE INDENT return " YES " NEW_LINE DEDENT DEDENT n = 3 NEW_LINE print ( is_divisible ( n ) ) NEW_LINE n = 4 NEW_LINE print ( is_divisible ( n ) ) NEW_LINE
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 . ; Increase count of prefix sum . ; b = k ^ p , p >= 0 ; k ^ m can be maximum equal to 10 ^ 14. ; If m [ a + b ] = c , then add c to the current sum . ; Increase count of prefix sum . ; Driver code
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 ) : NEW_LINE INDENT prefix_sum = [ 0 ] * MAX NEW_LINE prefix_sum [ 0 ] = 0 NEW_LINE prefix_sum = partial_sum ( prefix_sum , arr , n ) NEW_LINE if ( k == 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE m = defaultdict ( int ) NEW_LINE for i in range ( n , - 1 , - 1 ) : NEW_LINE INDENT if ( ( prefix_sum [ i ] + 1 ) in m ) : NEW_LINE INDENT sum += m [ prefix_sum [ i ] + 1 ] NEW_LINE DEDENT m [ prefix_sum [ i ] ] += 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT if ( k == - 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE m = defaultdict ( int ) NEW_LINE for i in range ( n , - 1 , - 1 ) : NEW_LINE INDENT if ( ( prefix_sum [ i ] + 1 ) in m ) : NEW_LINE INDENT sum += m [ prefix_sum [ i ] + 1 ] NEW_LINE DEDENT if ( ( prefix_sum [ i ] - 1 ) in m ) : NEW_LINE INDENT sum += m [ prefix_sum [ i ] - 1 ] NEW_LINE DEDENT m [ prefix_sum [ i ] ] += 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT sum = 0 NEW_LINE m = defaultdict ( int ) NEW_LINE for i in range ( n , - 1 , - 1 ) : NEW_LINE INDENT b = 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( b > 100000000000000 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( ( prefix_sum [ i ] + b ) in m ) : NEW_LINE INDENT sum += m [ prefix_sum [ i ] + b ] NEW_LINE DEDENT b *= k NEW_LINE DEDENT m [ prefix_sum [ i ] ] += 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 2 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE print ( countSubarrays ( arr , n , k ) ) NEW_LINE DEDENT
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 [ i ] to the ans after multiplying it with the number of set bits in b ; Divide by 2 means right shift b >> 1 if b has 1 at right most side than number of set bits will get decreased ; If no more set bits in b i . e . b = 0 ; Return the required answer ; Driver code
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 in range ( 1 , n ) : NEW_LINE INDENT power [ i ] = ( power [ i - 1 ] * 2 ) % mod NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( a [ i ] == '1' ) : NEW_LINE INDENT ans += c * power [ i ] NEW_LINE if ( ans >= mod ) : NEW_LINE INDENT ans %= mod NEW_LINE DEDENT DEDENT if ( b [ i ] == '1' ) : NEW_LINE INDENT c -= 1 NEW_LINE DEDENT if ( c == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = "1001" NEW_LINE b = "10101" NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE print ( BitOperations ( a , n , b , m ) ) NEW_LINE DEDENT
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__ == ' _ _ main _ _ ' : NEW_LINE INDENT Angle = 45 NEW_LINE print ( secondary_polygon ( Angle ) ) NEW_LINE DEDENT
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 DEDENT DEDENT DEDENT DEDENT def digitSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( n ) : NEW_LINE INDENT sum += n % 10 NEW_LINE n = n // 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def printAdditivePrime ( arr , n ) : NEW_LINE INDENT maxEle = max ( arr ) NEW_LINE prime = [ 0 ] * ( maxEle + 1 ) NEW_LINE sieve ( maxEle , prime ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( prime [ arr [ i ] ] == 0 ) : NEW_LINE INDENT sum = digitSum ( arr [ i ] ) NEW_LINE if ( prime [ sum ] == 0 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 4 , 6 , 11 , 12 , 18 , 7 ] NEW_LINE n = len ( a ) NEW_LINE printAdditivePrime ( a , n ) NEW_LINE DEDENT
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 total elements that have divisors exactly equal to as that of k 's ; Exclude k from the result if it is smaller than n . ; Driver code
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 = n / i NEW_LINE DEDENT ans = ans * ( x + 1 ) NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT ans = ans * 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT def getTotalCount ( n , k ) : NEW_LINE INDENT k_count = countDivisors ( k ) NEW_LINE count = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( k_count == countDivisors ( i ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( k < n ) : NEW_LINE INDENT count = count - 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n , k = 500 , 6 NEW_LINE print ( getTotalCount ( n , k ) ) NEW_LINE DEDENT
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 + sqc or sqc > sqa + sqb ) : NEW_LINE INDENT print ( " Obtuse - angled ▁ Triangle " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Acute - angled ▁ Triangle " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 2 NEW_LINE b = 2 NEW_LINE c = 2 NEW_LINE checkTypeOfTriangle ( a , b , c ) NEW_LINE DEDENT
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 how many of the given intervals an element lies in ; Constructing the frequency array ; Driver Code ; length of the array
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 [ ri + 1 ] = freq [ ri + 1 ] - 1 NEW_LINE if li < minimum : NEW_LINE INDENT minimum = li NEW_LINE DEDENT if ri > maximum : NEW_LINE INDENT maximum = ri NEW_LINE DEDENT DEDENT for i in range ( minimum , maximum + 1 ) : NEW_LINE INDENT freq [ i ] = freq [ i ] + freq [ i - 1 ] NEW_LINE DEDENT return freq [ V ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 10 ] , [ 5 , 10 ] , [ 15 , 25 ] , [ 7 , 12 ] , [ 20 , 25 ] ] NEW_LINE V = 7 NEW_LINE N = len ( arr ) NEW_LINE print ( countIntervals ( arr , V , N ) ) NEW_LINE DEDENT
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 , b , c ) ) : NEW_LINE INDENT print ( " Valid " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Invalid " ) NEW_LINE DEDENT DEDENT
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__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE printGroups ( n ) NEW_LINE DEDENT
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_LINE M = 65 NEW_LINE print ( int ( breakEvenPoint ( exp , S , M ) ) ) NEW_LINE DEDENT
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_LINE DEDENT return product NEW_LINE DEDENT n = 20 NEW_LINE print ( minimum ( n ) ) NEW_LINE
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 ; Remaining N - 1 iterations ; Driver code
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 NEW_LINE DEDENT DEDENT if ( isZero and isFive ) : NEW_LINE INDENT result = 2 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT m -= 1 NEW_LINE result = result * ( m ) NEW_LINE DEDENT DEDENT elif ( isZero or isFive ) : NEW_LINE INDENT result = 1 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT m -= 1 NEW_LINE result = result * ( m ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT result = - 1 NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE m = 6 NEW_LINE arr = [ 2 , 3 , 5 , 6 , 7 , 9 ] NEW_LINE print ( numbers ( n , arr , m ) ) NEW_LINE DEDENT
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 check ; check for magic square subgrid ; return total magic square ; Driver Code ; Function call to print required answer
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 ) == 15 and ( b + e + h ) == 15 and ( c + f + i ) == 15 and ( a + e + i ) == 15 and ( c + e + g ) == 15 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return false NEW_LINE DEDENT def CountMagicSquare ( Grid ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , R - 2 ) : NEW_LINE INDENT for j in range ( 0 , C - 2 ) : NEW_LINE INDENT if Grid [ i + 1 ] [ j + 1 ] != 5 : NEW_LINE INDENT continue NEW_LINE DEDENT if ( magic ( Grid [ i ] [ j ] , Grid [ i ] [ j + 1 ] , Grid [ i ] [ j + 2 ] , Grid [ i + 1 ] [ j ] , Grid [ i + 1 ] [ j + 1 ] , Grid [ i + 1 ] [ j + 2 ] , Grid [ i + 2 ] [ j ] , Grid [ i + 2 ] [ j + 1 ] , Grid [ i + 2 ] [ j + 2 ] ) == True ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT G = [ [ 4 , 3 , 8 , 4 ] , [ 9 , 5 , 1 , 9 ] , [ 2 , 7 , 6 , 2 ] ] NEW_LINE print ( CountMagicSquare ( G ) ) NEW_LINE DEDENT
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 greater or equal to A [ i ] found ; calculating required resultult ; Driver Code ; function call to get required resultult
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 s1 . append ( [ A [ i ] , cnt ] ) NEW_LINE left [ i ] = cnt NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT cnt = 1 NEW_LINE while len ( s2 ) > 0 and s2 [ - 1 ] [ 0 ] >= A [ i ] : NEW_LINE INDENT cnt += s2 [ - 1 ] [ 1 ] NEW_LINE s2 . pop ( ) NEW_LINE DEDENT s2 . append ( [ A [ i ] , cnt ] ) NEW_LINE right [ i ] = cnt NEW_LINE DEDENT result = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT result += A [ i ] * left [ i ] * right [ i ] NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 3 , 1 , 2 , 4 ] NEW_LINE n = len ( A ) NEW_LINE print ( sumSubarrayMins ( A , n ) ) 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 for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] % k == 0 ) : NEW_LINE INDENT res = max ( res , arr [ i ] ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 1230 , 45 , 67 , 1 ] NEW_LINE k = 10 NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum ▁ element ▁ of ▁ array ▁ which " , " is ▁ divisible ▁ by ▁ k : ▁ " , getMin ( arr , n , k ) ) NEW_LINE print ( " Maximum ▁ element ▁ of ▁ array ▁ which " , " is ▁ divisible ▁ by ▁ k : ▁ " , getMax ( arr , n , k ) ) NEW_LINE DEDENT
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__ == " _ _ main _ _ " : NEW_LINE INDENT k , d = 4 , 4 NEW_LINE printNumberWithDR ( k , d ) NEW_LINE DEDENT
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 form p * q ; p prime factor ; q prime factor ; if both prime factors are different if p * q <= n and q != ; Check if it can be expressed as p ^ 8 ; Driver Code
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 : NEW_LINE INDENT prime [ j ] = i NEW_LINE DEDENT DEDENT DEDENT i += 1 NEW_LINE DEDENT for i in range ( 2 , limit + 1 ) : NEW_LINE INDENT p = prime [ i ] NEW_LINE q = prime [ i // prime [ i ] ] NEW_LINE if p * q == i and q != 1 and p != q : NEW_LINE INDENT c += 1 NEW_LINE DEDENT elif prime [ i ] == i : NEW_LINE INDENT if i ** 8 <= n : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT DEDENT return c NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 1000 NEW_LINE print ( countNumbers ( n ) ) NEW_LINE DEDENT
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 number < n ; Calculate first prime number > n ; check if next_prime and prev_prime have the same average ; Driver Code
def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def isInterprime ( n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return False NEW_LINE DEDENT prev_prime = n NEW_LINE next_prime = n NEW_LINE while ( isPrime ( prev_prime ) == 0 ) : NEW_LINE INDENT prev_prime = prev_prime - 1 NEW_LINE DEDENT while ( isPrime ( next_prime ) == 0 ) : NEW_LINE INDENT next_prime = next_prime + 1 NEW_LINE DEDENT if ( ( prev_prime + next_prime ) == 2 * n ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = 9 NEW_LINE if ( isInterprime ( n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
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 ) : NEW_LINE INDENT print ( " For ▁ N ▁ = ▁ " , N , " : " , get_unit_digit ( N ) , sep = ' ▁ ' ) NEW_LINE DEDENT
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 ] . ; Function to calculate sum of squares of Fibonacci numbers ; Driver Code
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_LINE DEDENT else : NEW_LINE INDENT k = n // 2 NEW_LINE DEDENT if n & 1 : NEW_LINE INDENT f [ n ] = ( fib ( k ) * fib ( k ) + fib ( k - 1 ) * fib ( k - 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT f [ n ] = ( ( 2 * fib ( k - 1 ) + fib ( k ) ) * fib ( k ) ) NEW_LINE DEDENT return f [ n ] NEW_LINE DEDENT def calculateSumOfSquares ( n ) : NEW_LINE INDENT return fib ( n ) * fib ( n + 1 ) NEW_LINE DEDENT n = 6 NEW_LINE print ( " Sum ▁ of ▁ Squares ▁ of ▁ " " Fibonacci ▁ numbers ▁ is ▁ : " , calculateSumOfSquares ( n ) ) NEW_LINE
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 valid ; find minimum of temp and z ; return required answer ; Driver code
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 DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x , y , z , n = 1 , 2 , 3 , 4 NEW_LINE print ( NumberOfSolutions ( x , y , z , n ) ) NEW_LINE DEDENT
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 find numbers that are product of exactly two distinct prime numbers . ; Vector to store such numbers ; insert in the vector ; Print all numbers till n from the vector ; Driver function
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 num //= i NEW_LINE cnt += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( num > 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT return cnt == 2 NEW_LINE DEDENT def findNumbers ( N ) : NEW_LINE INDENT vec = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( isProduct ( i ) and not isPerfectSquare ( i ) ) : NEW_LINE INDENT vec . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( len ( vec ) ) : NEW_LINE INDENT print ( vec [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 30 NEW_LINE findNumbers ( N ) NEW_LINE DEDENT
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 numerator ; calculate denominator ; Driver code
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_LINE INDENT nCr [ i ] [ j ] = nCr [ i - 1 ] [ j ] + nCr [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def findTanNTheta ( tanTheta , n ) : NEW_LINE INDENT numerator = 0 NEW_LINE denominator = 1 NEW_LINE ans = 0 NEW_LINE toggle = 1 NEW_LINE for i in range ( 1 , n + 1 , 2 ) : NEW_LINE INDENT numerator = ( numerator + nCr [ n ] [ i ] * ( tanTheta ** ( i ) ) * toggle ) NEW_LINE toggle = toggle * - 1 NEW_LINE DEDENT toggle = - 1 NEW_LINE for i in range ( 2 , n + 1 , 2 ) : NEW_LINE INDENT numerator = ( numerator + nCr [ n ] [ i ] * ( tanTheta ** i ) * toggle ) NEW_LINE toggle = toggle * - 1 NEW_LINE DEDENT ans = numerator / denominator NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT binomial ( ) NEW_LINE tanTheta = 0.3 NEW_LINE n = 10 NEW_LINE print ( findTanNTheta ( tanTheta , n ) ) NEW_LINE DEDENT
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 given line has x - coordinate value as X ; Calculating Y of chosen point by line equation ; Utility method to find minimum total distance ; Loop until difference between low and high become less than EPS ; mid1 and mid2 are representative x co - ordiantes of search space ; If mid2 point gives more total distance , skip third part ; If mid1 point gives more total distance , skip first part ; Compute optimum distance cost by sending average of low and high as X ; Method to find optimum cost ; Converting 2D array input to point array ; Driver Code
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_LINE self . c = c NEW_LINE DEDENT DEDENT def dist ( self , x , y , p ) : NEW_LINE INDENT return math . sqrt ( ( x - p . x ) ** 2 + ( y - p . y ) ** 2 ) NEW_LINE DEDENT def compute ( self , p , n , l , x ) : NEW_LINE INDENT res = 0 NEW_LINE y = - 1 * ( l . a * x + l . c ) / l . b NEW_LINE for i in range ( n ) : NEW_LINE INDENT res += self . dist ( x , y , p [ i ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT def find_Optimum_cost_untill ( self , p , n , l ) : NEW_LINE INDENT low = - 1e6 NEW_LINE high = 1e6 NEW_LINE eps = 1e-6 + 1 NEW_LINE while ( ( high - low ) > eps ) : NEW_LINE INDENT mid1 = low + ( high - low ) / 3 NEW_LINE mid2 = high - ( high - low ) / 3 NEW_LINE dist1 = self . compute ( p , n , l , mid1 ) NEW_LINE dist2 = self . compute ( p , n , l , mid2 ) NEW_LINE if ( dist1 < dist2 ) : NEW_LINE INDENT high = mid2 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid1 NEW_LINE DEDENT DEDENT return self . compute ( p , n , l , ( low + high ) / 2 ) NEW_LINE DEDENT def find_Optimum_cost ( self , p , l ) : NEW_LINE INDENT n = len ( p ) NEW_LINE p_arr = [ None ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT p_obj = self . Point ( p [ i ] [ 0 ] , p [ i ] [ 1 ] ) NEW_LINE p_arr [ i ] = p_obj NEW_LINE DEDENT return self . find_Optimum_cost_untill ( p_arr , n , l ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT obj = Optimum_distance ( ) NEW_LINE l = obj . Line ( 1 , - 1 , - 3 ) NEW_LINE p = [ [ - 3 , - 2 ] , [ - 1 , 0 ] , [ - 1 , 2 ] , [ 1 , 2 ] , [ 3 , 4 ] ] NEW_LINE print ( obj . find_Optimum_cost ( p , l ) ) NEW_LINE DEDENT
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 index arr [ i ] - 1 , then swap ; Otherwise , increment the index ; Traverse the array again ; If the element is not at its correct position ; Stores the missing and the duplicate elements ; Print the Missing Number ; Print the Duplicate Number ; Driver code
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 : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] != i + 1 ) : NEW_LINE INDENT missing . append ( i + 1 ) ; NEW_LINE duplicate . add ( arr [ i ] ) ; NEW_LINE DEDENT DEDENT print ( " Missing ▁ Numbers : ▁ " , end = " " ) ; NEW_LINE for it in missing : NEW_LINE INDENT print ( it , end = " ▁ " ) ; NEW_LINE DEDENT print ( " Duplicate Numbers : " , end = " " ) ; NEW_LINE for it in list ( duplicate ) : NEW_LINE INDENT print ( it , end = ' ▁ ' ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 2 , 4 , 5 , 7 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE findElements ( arr , N ) ; NEW_LINE DEDENT
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 , k ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT n = 233 ; NEW_LINE printCombination ( n ) ; NEW_LINE
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 SPF ( Smallest Prime Factor ) for every number till MAXN . ; marking smallest prime factor for every number to be itself . ; separately marking spf for every even number as 2 ; checking if i is prime ; marking SPF for all numbers divisible by i ; marking spf [ j ] if it is not previously marked ; Function to find sum of digits in a number ; find sum of digits of all numbers up to MAXN ; add sum of digits of least prime factor and n / spf [ n ] ; if it is valid make isValid true ; prefix sum to compute answer ; Driver code ; print answer for required range ; print answer for required range
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 spf [ i ] = 2 NEW_LINE DEDENT i = 3 NEW_LINE while i * i <= MAXN : NEW_LINE INDENT if ( spf [ i ] == i ) : NEW_LINE INDENT for j in range ( i * i , MAXN , i ) : NEW_LINE INDENT if ( spf [ j ] == j ) : NEW_LINE INDENT spf [ j ] = i NEW_LINE DEDENT DEDENT DEDENT i += 2 NEW_LINE DEDENT DEDENT def Digit_Sum ( copy ) : NEW_LINE INDENT d = 0 NEW_LINE while ( copy ) : NEW_LINE INDENT d += copy % 10 NEW_LINE copy //= 10 NEW_LINE DEDENT return d NEW_LINE DEDENT def Sum_Of_All_Digits ( ) : NEW_LINE INDENT for n in range ( 2 , MAXN ) : NEW_LINE INDENT sum_digits [ n ] = ( sum_digits [ n // spf [ n ] ] + Digit_Sum ( spf [ n ] ) ) NEW_LINE if ( Digit_Sum ( n ) == sum_digits [ n ] ) : NEW_LINE INDENT isValid [ n ] = True NEW_LINE DEDENT DEDENT for n in range ( 2 , MAXN ) : NEW_LINE INDENT if ( isValid [ n ] ) : NEW_LINE INDENT ans [ n ] = 1 NEW_LINE DEDENT ans [ n ] += ans [ n - 1 ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT Smallest_prime_factor ( ) NEW_LINE Sum_Of_All_Digits ( ) NEW_LINE l = 2 NEW_LINE r = 3 NEW_LINE print ( " Valid ▁ numbers ▁ in ▁ the ▁ range " , l , r , " are " , ans [ r ] - ans [ l - 1 ] ) NEW_LINE l = 2 NEW_LINE r = 10 NEW_LINE print ( " Valid ▁ numbers ▁ in ▁ the ▁ range " , l , r , " are " , ans [ r ] - ans [ l - 1 ] ) NEW_LINE DEDENT
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 count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 3 , 4 , 6 ] NEW_LINE size = len ( a ) NEW_LINE print ( calculate ( a , size ) ) NEW_LINE DEDENT
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 for every query ; Function to pre - store unique prime factors ; 1 st query ; 2 nd query ; 3 rd query ; 4 th query
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 ( j ) NEW_LINE while ( num % j == 0 ) : NEW_LINE INDENT num = num // j NEW_LINE DEDENT DEDENT DEDENT if ( num > 2 ) : NEW_LINE INDENT v [ i ] . append ( num ) NEW_LINE DEDENT DEDENT DEDENT def query ( number , n ) : NEW_LINE INDENT return v [ number ] [ n - 1 ] NEW_LINE DEDENT preprocess ( ) NEW_LINE number = 6 NEW_LINE n = 1 NEW_LINE print ( query ( number , n ) ) NEW_LINE number = 210 NEW_LINE n = 3 NEW_LINE print ( query ( number , n ) ) NEW_LINE number = 210 NEW_LINE n = 2 NEW_LINE print ( query ( number , n ) ) NEW_LINE number = 60 NEW_LINE n = 2 NEW_LINE print ( query ( number , n ) ) NEW_LINE
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 ( ' not ▁ found ' ) NEW_LINE DEDENT
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 original number ( n ) ; observation ; Driver Code ; variable that stores no of digits in n
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 power = pow ( 10 , i ) NEW_LINE a = n % power NEW_LINE if ( d > a ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT t = 0 NEW_LINE for j in range ( 0 , i ) : NEW_LINE INDENT t += 9 * pow ( 10 , j ) NEW_LINE DEDENT if ( n % power == t ) : NEW_LINE INDENT print ( n , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ( n - ( n % power ) - 1 ) , end = " " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( n , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 1029 NEW_LINE d = 102 NEW_LINE num = dig ( n ) NEW_LINE required_number ( num , n , d ) NEW_LINE DEDENT
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 call to find volume of Icosahedron .
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 ) ) NEW_LINE print ( " Volume : ▁ " , findVolume ( a ) ) NEW_LINE
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 ( n ) ) ; NEW_LINE
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 ( countDigits ( n ) ) NEW_LINE DEDENT
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