text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Count of a , b & c after n seconds for given reproduction rate | Function to print the count of a , b and c after n seconds ; Number of multiples of 60 below n ; Multiple of 60 nearest to n ; Change all a to b ; Change all b to c ; Change each c to two a ; Print the updated values of a , b and c ; Driver code
import math NEW_LINE def findCount ( n ) : NEW_LINE INDENT a , b , c = 1 , 0 , 0 ; NEW_LINE x = ( int ) ( n / 60 ) ; NEW_LINE a = int ( math . pow ( 32 , x ) ) ; NEW_LINE x = 60 * x ; NEW_LINE for i in range ( x + 1 , n + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT b += a ; NEW_LINE a = 0 ; NEW_LINE DEDENT if ( i % 5 == 0 ) : NEW_LINE INDENT c += b ; NEW_LINE b = 0 ; NEW_LINE DEDENT if ( i % 12 == 0 ) : NEW_LINE INDENT a += ( 2 * c ) ; NEW_LINE c = 0 ; NEW_LINE DEDENT DEDENT print ( " a ▁ = " , a , end = " , ▁ " ) ; NEW_LINE print ( " b ▁ = " , b , end = " , ▁ " ) ; NEW_LINE print ( " c ▁ = " , c ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 72 ; NEW_LINE findCount ( n ) ; NEW_LINE DEDENT
Find GCD of factorial of elements of given array | Implementation of factorial function ; Function to find GCD of factorial of elements from array ; find the minimum element of array ; return the factorial of minimum element ; Driver Code
def factorial ( n ) : NEW_LINE INDENT if n == 1 or n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return factorial ( n - 1 ) * n NEW_LINE DEDENT DEDENT def gcdOfFactorial ( arr , n ) : NEW_LINE INDENT minm = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if minm > arr [ i ] : NEW_LINE INDENT minm = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = minm NEW_LINE DEDENT DEDENT return factorial ( minm ) NEW_LINE DEDENT arr = [ 9 , 12 , 122 , 34 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE print ( gcdOfFactorial ( arr , n ) ) NEW_LINE
Sum of the series 1 ^ 1 + 2 ^ 2 + 3 ^ 3 + ... . . + n ^ n using recursion | Recursive function to return the sum of the given series ; 1 ^ 1 = 1 ; Recursive call ; Driver code
def sum ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return pow ( n , n ) + sum ( n - 1 ) NEW_LINE DEDENT DEDENT n = 2 NEW_LINE print ( sum ( n ) ) NEW_LINE
Count permutations that are first decreasing then increasing . | Python3 implementation of the above approach ; Function to compute a ^ n % mod ; Function to count permutations that are first decreasing and then increasing ; For n = 1 return 0 ; Calculate and return result ; Driver code
mod = 1000000007 NEW_LINE def power ( a , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT p = power ( a , int ( n / 2 ) ) % mod ; NEW_LINE p = ( p * p ) % mod NEW_LINE if ( n & 1 ) : NEW_LINE INDENT p = ( p * a ) % mod NEW_LINE DEDENT return p NEW_LINE DEDENT def countPermutations ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( power ( 2 , n - 1 ) - 2 ) % mod NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( countPermutations ( n ) ) NEW_LINE DEDENT
Find the count of numbers that can be formed using digits 3 , 4 only and having length at max N . | Function to find the count of numbers that can be formed using digits 3 , 4 only and having length at max N . ; Driver code
def numbers ( n ) : NEW_LINE INDENT return pow ( 2 , n + 1 ) - 2 NEW_LINE DEDENT n = 2 NEW_LINE print ( numbers ( n ) ) NEW_LINE
Ways to place 4 items in n ^ 2 positions such that no row / column contains more than one | Function to return the number of ways to place 4 items in n ^ 2 positions ; Driver code
def NumbersofWays ( n ) : NEW_LINE INDENT x = ( n * ( n - 1 ) * ( n - 2 ) * ( n - 3 ) ) // ( 4 * 3 * 2 * 1 ) NEW_LINE y = n * ( n - 1 ) * ( n - 2 ) * ( n - 3 ) NEW_LINE return x * y NEW_LINE DEDENT n = 4 NEW_LINE print ( NumbersofWays ( n ) ) NEW_LINE
Find Nth term of the series 1 , 6 , 18 , 40 , 75 , ... . | Function to generate a fixed number ; ( N ^ 2 * ( N + 1 ) ) / 2 ; Driver code
def nthTerm ( N ) : NEW_LINE INDENT nth = 0 NEW_LINE nth = ( N * N * ( N + 1 ) ) // 2 NEW_LINE return nth NEW_LINE DEDENT N = 5 NEW_LINE print ( nthTerm ( N ) ) NEW_LINE
Print n numbers such that their sum is a perfect square | Function to print n numbers such that their sum is a perfect square ; Print ith odd number ; Driver code
def findNumber ( n ) : NEW_LINE INDENT i = 1 NEW_LINE while i <= n : NEW_LINE INDENT print ( ( 2 * i ) - 1 , end = " ▁ " ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT n = 3 NEW_LINE findNumber ( n ) NEW_LINE
Missing even and odd elements from the given arrays | Python3 implementation of the approach ; Function to find the missing numbers ; To store the minimum and the maximum odd and even elements from the arrays ; To store the sum of the array elements ; Get the minimum and the maximum even elements from the array ; Get the minimum and the maximum odd elements from the array ; To store the total terms in the series and the required sum of the array ; Total terms from 2 to minEven ; Sum of all even numbers from 2 to minEven ; Total terms from 2 to maxEven ; Sum of all even numbers from 2 to maxEven ; Required sum for the even array ; Missing even number ; Total terms from 1 to minOdd ; Sum of all odd numbers from 1 to minOdd ; Total terms from 1 to maxOdd ; Sum of all odd numbers from 1 to maxOdd ; Required sum for the odd array ; Missing odd number ; Driver code
import sys NEW_LINE def findMissingNums ( even , sizeEven , odd , sizeOdd ) : NEW_LINE INDENT minEven = sys . maxsize ; NEW_LINE maxEven = - ( sys . maxsize - 1 ) ; NEW_LINE minOdd = sys . maxsize ; NEW_LINE maxOdd = - ( sys . maxsize - 1 ) ; NEW_LINE sumEvenArr = 0 ; NEW_LINE sumOddArr = 0 ; NEW_LINE for i in range ( sizeEven ) : NEW_LINE INDENT minEven = min ( minEven , even [ i ] ) ; NEW_LINE maxEven = max ( maxEven , even [ i ] ) ; NEW_LINE sumEvenArr += even [ i ] ; NEW_LINE DEDENT for i in range ( sizeOdd ) : NEW_LINE INDENT minOdd = min ( minOdd , odd [ i ] ) ; NEW_LINE maxOdd = max ( maxOdd , odd [ i ] ) ; NEW_LINE sumOddArr += odd [ i ] ; NEW_LINE DEDENT totalTerms = 0 ; NEW_LINE reqSum = 0 ; NEW_LINE totalTerms = minEven // 2 ; NEW_LINE evenSumMin = ( totalTerms * ( totalTerms + 1 ) ) ; NEW_LINE totalTerms = maxEven // 2 ; NEW_LINE evenSumMax = ( totalTerms * ( totalTerms + 1 ) ) ; NEW_LINE reqSum = ( evenSumMax - evenSumMin + minEven ) ; NEW_LINE print ( " Even ▁ = " , reqSum - sumEvenArr ) ; NEW_LINE totalTerms = ( minOdd // 2 ) + 1 ; NEW_LINE oddSumMin = totalTerms * totalTerms ; NEW_LINE totalTerms = ( maxOdd // 2 ) + 1 ; NEW_LINE oddSumMax = totalTerms * totalTerms ; NEW_LINE reqSum = ( oddSumMax - oddSumMin + minOdd ) ; NEW_LINE print ( " Odd ▁ = " , reqSum - sumOddArr ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT even = [ 6 , 4 , 8 , 14 , 10 ] ; NEW_LINE sizeEven = len ( even ) NEW_LINE odd = [ 7 , 5 , 3 , 11 , 13 ] ; NEW_LINE sizeOdd = len ( odd ) ; NEW_LINE findMissingNums ( even , sizeEven , odd , sizeOdd ) ; NEW_LINE DEDENT
Minimum matches the team needs to win to qualify | Function to return the minimum number of matches to win to qualify for next round ; Do a binary search to find ; Find mid element ; Check for condition to qualify for next round ; Driver Code
def findMinimum ( x , y ) : NEW_LINE INDENT low = 0 NEW_LINE high = y NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) >> 1 NEW_LINE if ( ( mid * 2 + ( y - mid ) ) >= x ) : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 6 NEW_LINE y = 5 NEW_LINE print ( findMinimum ( x , y ) ) NEW_LINE DEDENT
Check if product of digits of a number at even and odd places is equal | Python3 implementation of the approach ; To store the respective product ; Converting integer to string ; Traversing the string ; Driver code
def getResult ( n ) : NEW_LINE INDENT proOdd = 1 NEW_LINE proEven = 1 NEW_LINE num = str ( n ) NEW_LINE for i in range ( len ( num ) ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT proOdd = proOdd * int ( num [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT proEven = proEven * int ( num [ i ] ) NEW_LINE DEDENT DEDENT if ( proOdd == proEven ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4324 NEW_LINE getResult ( n ) NEW_LINE DEDENT
Count of all even numbers in the range [ L , R ] whose sum of digits is divisible by 3 | Function to return the sum of digits of x ; Function to return the count of required numbers ; If i is divisible by 2 and sum of digits of i is divisible by 3 ; Return the required count ; Driver code
def sumOfDigits ( x ) : NEW_LINE INDENT sum = 0 NEW_LINE while x != 0 : NEW_LINE INDENT sum += x % 10 NEW_LINE x = x // 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def countNumbers ( l , r ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT if i % 2 == 0 and sumOfDigits ( i ) % 3 == 0 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT l = 1000 ; r = 6000 NEW_LINE print ( countNumbers ( l , r ) ) NEW_LINE
Sum of minimum element of all subarrays of a sorted array | Function to find the sum of minimum of all subarrays ; Driver code
def findMinSum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum += arr [ i ] * ( n - i ) NEW_LINE DEDENT return sum NEW_LINE DEDENT arr = [ 3 , 5 , 7 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMinSum ( arr , n ) ) NEW_LINE
Longest Sub | Function to return the max length of the sub - array that have the maximum average ( average value of the elements ) ; Finding the maximum value ; If consecutive maximum found ; Find the max length of consecutive max ; Driver code
def maxLenSubArr ( a , n ) : NEW_LINE INDENT cm , Max = 1 , 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if a [ i ] > Max : NEW_LINE INDENT Max = a [ i ] NEW_LINE DEDENT DEDENT i = 0 NEW_LINE while i < n - 1 : NEW_LINE INDENT count = 1 NEW_LINE if a [ i ] == a [ i + 1 ] and a [ i ] == Max : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if a [ j ] == Max : NEW_LINE INDENT count += 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if count > cm : NEW_LINE INDENT cm = count NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return cm NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 1 , 6 , 6 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxLenSubArr ( arr , n ) ) NEW_LINE DEDENT
Minimum possible sum of array elements after performing the given operation | Function to return the minimized sum ; To store the largest element from the array which is divisible by x ; Sum of array elements before performing any operation ; If current element is divisible by x and it is maximum so far ; Update the minimum element ; If no element can be reduced then there 's no point in performing the operation as we will end up increasing the sum when an element is multiplied by x ; Subtract the chosen elements from the sum and then add their updated values ; Return the minimized sum ; Driver code
def minSum ( arr , n , x ) : NEW_LINE INDENT Sum = 0 NEW_LINE largestDivisible , minimum = - 1 , arr [ 0 ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE if ( arr [ i ] % x == 0 and largestDivisible < arr [ i ] ) : NEW_LINE INDENT largestDivisible = arr [ i ] NEW_LINE DEDENT if arr [ i ] < minimum : NEW_LINE INDENT minimum = arr [ i ] NEW_LINE DEDENT DEDENT if largestDivisible == - 1 : NEW_LINE INDENT return Sum NEW_LINE DEDENT sumAfterOperation = ( Sum - minimum - largestDivisible + ( x * minimum ) + ( largestDivisible // x ) ) NEW_LINE return min ( Sum , sumAfterOperation ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 5 , 5 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE x = 3 NEW_LINE print ( minSum ( arr , n , x ) ) NEW_LINE DEDENT
Maximum Bitwise AND pair from given range | Function to return the maximum bitwise AND possible among all the possible pairs ; If there is only a single value in the range [ L , R ] ; If there are only two values in the range [ L , R ] ; Driver code
def maxAND ( L , R ) : NEW_LINE INDENT if ( L == R ) : NEW_LINE INDENT return L ; NEW_LINE DEDENT elif ( ( R - L ) == 1 ) : NEW_LINE INDENT return ( R & L ) ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( ( ( R - 1 ) & R ) > ( ( R - 2 ) & ( R - 1 ) ) ) : NEW_LINE INDENT return ( ( R - 1 ) & R ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( R - 2 ) & ( R - 1 ) ) ; NEW_LINE DEDENT DEDENT DEDENT L = 1 ; NEW_LINE R = 632 ; NEW_LINE print ( maxAND ( L , R ) ) ; NEW_LINE
Smallest Special Prime which is greater than or equal to a given number | Function to check whether the number is a special prime or not ; While number is not equal to zero ; If the number is not prime return false . ; Else remove the last digit by dividing the number by 10. ; If the number has become zero then the number is special prime , hence return true ; Function to find the Smallest Special Prime which is greater than or equal to a given number ; sieve for finding the Primes ; There is always an answer possible ; Checking if the number is a special prime or not ; If yes print the number and break the loop . ; Else increment the number . ; Driver code
def checkSpecialPrime ( sieve , num ) : NEW_LINE INDENT while ( num ) : NEW_LINE INDENT if ( sieve [ num ] == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT num = int ( num / 10 ) NEW_LINE DEDENT return True NEW_LINE DEDENT def findSpecialPrime ( N ) : NEW_LINE INDENT sieve = [ True for i in range ( N * 10 + 1 ) ] NEW_LINE sieve [ 0 ] = False NEW_LINE sieve [ 1 ] = False NEW_LINE for i in range ( 2 , N * 10 + 1 ) : NEW_LINE INDENT if ( sieve [ i ] ) : NEW_LINE INDENT for j in range ( i * i , N * 10 + 1 , i ) : NEW_LINE INDENT sieve [ j ] = False NEW_LINE DEDENT DEDENT DEDENT while ( True ) : NEW_LINE INDENT if ( checkSpecialPrime ( sieve , N ) ) : NEW_LINE INDENT print ( N ) NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT N += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 379 NEW_LINE findSpecialPrime ( N ) NEW_LINE N = 100 NEW_LINE findSpecialPrime ( N ) NEW_LINE DEDENT
Minimum number of given moves required to make N divisible by 25 | Python3 implementation of the approach ; Function to return the minimum number of moves required to make n divisible by 25 ; Convert number into string ; To store required answer ; Length of the string ; To check all possible pairs ; Make a duplicate string ; Number of swaps required to place ith digit in last position ; Number of swaps required to place jth digit in 2 nd last position ; Find first non zero digit ; Place first non zero digit in the first position ; Convert string to number ; If this number is divisible by 25 then cur is one of the possible answer ; If not possible ; Driver code
import sys NEW_LINE def minMoves ( n ) : NEW_LINE INDENT s = str ( n ) ; NEW_LINE ans = sys . maxsize ; NEW_LINE len1 = len ( s ) ; NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT for j in range ( len1 ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT t = s ; NEW_LINE cur = 0 ; NEW_LINE list1 = list ( t ) ; NEW_LINE for k in range ( i , len1 - 1 ) : NEW_LINE INDENT e = list1 [ k ] ; NEW_LINE list1 [ k ] = list1 [ k + 1 ] ; NEW_LINE list1 [ k + 1 ] = e ; NEW_LINE cur += 1 ; NEW_LINE DEDENT t = ' ' . join ( list1 ) ; NEW_LINE list1 = list ( t ) ; NEW_LINE for k in range ( j - ( j > i ) , len1 - 2 ) : NEW_LINE INDENT e = list1 [ k ] ; NEW_LINE list1 [ k ] = list1 [ k + 1 ] ; NEW_LINE list1 [ k + 1 ] = e ; NEW_LINE cur += 1 ; NEW_LINE DEDENT t = ' ' . join ( list1 ) ; NEW_LINE pos = - 1 ; NEW_LINE for k in range ( len1 ) : NEW_LINE INDENT if ( t [ k ] != '0' ) : NEW_LINE INDENT pos = k ; NEW_LINE break ; NEW_LINE DEDENT DEDENT for k in range ( pos , 0 , - 1 ) : NEW_LINE INDENT e = list1 [ k ] ; NEW_LINE list1 [ k ] = list1 [ k + 1 ] ; NEW_LINE list1 [ k + 1 ] = e ; NEW_LINE cur += 1 ; NEW_LINE DEDENT t = ' ' . join ( list1 ) ; NEW_LINE nn = int ( t ) ; NEW_LINE if ( nn % 25 == 0 ) : NEW_LINE INDENT ans = min ( ans , cur ) ; NEW_LINE DEDENT DEDENT DEDENT if ( ans == sys . maxsize ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT n = 509201 ; NEW_LINE print ( minMoves ( n ) ) ; NEW_LINE
Maximum positive integer divisible by C and is in the range [ A , B ] | Function to return the required number ; If b % c = 0 then b is the required number ; Else get the maximum multiple of c smaller than b ; Driver code
def getMaxNum ( a , b , c ) : NEW_LINE INDENT if ( b % c == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT x = ( ( b // c ) * c ) NEW_LINE if ( x >= a and x <= b ) : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT a , b , c = 2 , 10 , 3 NEW_LINE print ( getMaxNum ( a , b , c ) ) NEW_LINE
Count of pairs ( x , y ) in an array such that x < y | Function to return the number of pairs ( x , y ) such that x < y ; Length of the array ; Calculate the number of valid pairs ; Return the count of valid pairs ; Driver code
def getPairs ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE count = ( n * ( n - 1 ) ) // 2 NEW_LINE return count NEW_LINE DEDENT a = [ 2 , 4 , 3 , 1 ] NEW_LINE print ( getPairs ( a ) ) NEW_LINE
Count the total number of squares that can be visited by Bishop in one move | Function to return the count of total positions the Bishop can visit in a single move ; Count top left squares ; Count bottom right squares ; Count top right squares ; Count bottom left squares ; Return total count ; Bishop 's Position
def countSquares ( row , column ) : NEW_LINE INDENT topLeft = min ( row , column ) - 1 NEW_LINE bottomRight = 8 - max ( row , column ) NEW_LINE topRight = min ( row , 9 - column ) - 1 NEW_LINE bottomLeft = 8 - max ( row , 9 - column ) NEW_LINE return ( topLeft + topRight + bottomRight + bottomLeft ) NEW_LINE DEDENT row = 4 NEW_LINE column = 4 NEW_LINE print ( countSquares ( row , column ) ) NEW_LINE
Check whether Bishop can take down Pawn or not | Function that return true if the Bishop can take down the pawn ; If pawn is at angle 45 or 225 degree from bishop 's Position ; If pawn is at angle 135 or 315 degree from bishop 's Position ; Bishop 's Position ; Pawn 's Position
def canTakeDown ( bishopX , bishopY , pawnX , pawnY ) : NEW_LINE INDENT if ( pawnX - bishopX == pawnY - bishopY ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( - pawnX + bishopX == pawnY - bishopY ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT bishopX = 5 NEW_LINE bishopY = 5 NEW_LINE pawnX = 1 NEW_LINE pawnY = 1 NEW_LINE if ( canTakeDown ( bishopX , bishopY , pawnX , pawnY ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Find maximum operations to reduce N to 1 | Python3 program to find maximum number moves possible ; To store number of prime factors of each number ; Function to find number of prime factors of each number ; if i is a prime number ; increase value by one from it 's preveious multiple ; make prefix sum this will be helpful for multiple test cases ; Driver Code ; Generate primeFactors array ; required answer
N = 1000005 NEW_LINE primeFactors = [ 0 ] * N ; NEW_LINE def findPrimeFactors ( ) : NEW_LINE INDENT for i in range ( 2 , N ) : NEW_LINE INDENT if ( primeFactors [ i ] == 0 ) : NEW_LINE INDENT for j in range ( i , N , i ) : NEW_LINE INDENT primeFactors [ j ] = primeFactors [ j // i ] + 1 ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT primeFactors [ i ] += primeFactors [ i - 1 ] ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT findPrimeFactors ( ) ; NEW_LINE a = 6 ; b = 3 ; NEW_LINE print ( primeFactors [ a ] - primeFactors [ b ] ) ; NEW_LINE DEDENT
Smallest integer with digit sum M and multiple of N | Python 3 implementation of the above approach ; Function to return digit sum ; Function to find out the smallest integer ; Start of the iterator ( Smallest multiple of n ) ; Driver code
from math import floor , pow NEW_LINE import sys NEW_LINE def digitSum ( n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT ans += n % 10 ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE DEDENT return ans NEW_LINE DEDENT def findInt ( n , m ) : NEW_LINE INDENT minDigit = floor ( m / 9 ) NEW_LINE start = ( int ( pow ( 10 , minDigit ) ) - int ( pow ( 10 , minDigit ) ) % n ) NEW_LINE while ( start < sys . maxsize ) : NEW_LINE INDENT if ( digitSum ( start ) == m ) : NEW_LINE INDENT return start NEW_LINE DEDENT else : NEW_LINE INDENT start += n NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 13 NEW_LINE m = 32 NEW_LINE print ( findInt ( n , m ) ) NEW_LINE DEDENT
Maximum sum after repeatedly dividing N by a divisor | Python 3 implementation of the above approach ; Function to find the smallest divisor ; Function to find the maximum sum ; Driver Code
from math import sqrt NEW_LINE def smallestDivisor ( n ) : NEW_LINE INDENT mx = int ( sqrt ( n ) ) NEW_LINE for i in range ( 2 , mx + 1 , 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return n NEW_LINE DEDENT def maxSum ( n ) : NEW_LINE INDENT res = n NEW_LINE while ( n > 1 ) : NEW_LINE INDENT divi = smallestDivisor ( n ) NEW_LINE n = int ( n / divi ) NEW_LINE res += n NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 34 NEW_LINE print ( maxSum ( n ) ) NEW_LINE DEDENT
Make all elements of an array equal with the given operation | Function that returns true if all the elements of the array can be made equal with the given operation ; To store the sum of the array elements and the maximum element from the array ; Driver code
def isPossible ( n , k , arr ) : NEW_LINE INDENT sum = arr [ 0 ] NEW_LINE maxVal = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE maxVal = max ( maxVal , arr [ i ] ) NEW_LINE DEDENT if ( int ( maxVal ) > int ( ( sum + k ) / n ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 8 NEW_LINE arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE if ( isPossible ( n , k , arr ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Maximize the value of x + y + z such that ax + by + cz = n | Python3 implementation of the approach ; Function to return the maximum value of ( x + y + z ) such that ( ax + by + cz = n ) ; i represents possible values of a * x ; j represents possible values of b * y ; If z is an integer ; Driver code ; Function Call
from math import * NEW_LINE def maxResult ( n , a , b , c ) : NEW_LINE INDENT maxVal = 0 NEW_LINE for i in range ( 0 , n + 1 , a ) : NEW_LINE INDENT for j in range ( 0 , n - i + 1 , b ) : NEW_LINE INDENT z = ( n - ( i + j ) ) / c NEW_LINE if ( floor ( z ) == ceil ( z ) ) : NEW_LINE INDENT x = i // a NEW_LINE y = j // b NEW_LINE maxVal = max ( maxVal , x + y + int ( z ) ) NEW_LINE DEDENT DEDENT DEDENT return maxVal NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 NEW_LINE a = 5 NEW_LINE b = 3 NEW_LINE c = 4 NEW_LINE print ( maxResult ( n , a , b , c ) ) NEW_LINE DEDENT
Make all numbers of an array equal | Function that returns true if all the array elements can be made equal with the given operation ; Divide number by 2 ; Divide number by 3 ; Driver code
def EqualNumbers ( a , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT while a [ i ] % 2 == 0 : NEW_LINE INDENT a [ i ] //= 2 NEW_LINE DEDENT while a [ i ] % 3 == 0 : NEW_LINE INDENT a [ i ] //= 3 NEW_LINE DEDENT if a [ i ] != a [ 0 ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 50 , 75 , 150 ] NEW_LINE n = len ( a ) NEW_LINE if EqualNumbers ( a , n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Maximum GCD from Given Product of Unknowns | Python3 implementation of the approach ; Function to return the required gcd ; Count the number of times 2 divides p ; Equivalent to p = p / 2 ; ; If 2 divides p ; Check all the possible numbers that can divide p ; If n in the end is a prime number ; Return the required gcd ; Driver code
import math NEW_LINE def max_gcd ( n , p ) : NEW_LINE INDENT count = 0 ; NEW_LINE gcd = 1 ; NEW_LINE while ( p % 2 == 0 ) : NEW_LINE INDENT p >>= 1 ; NEW_LINE count = count + 1 ; NEW_LINE DEDENT if ( count > 0 ) : NEW_LINE INDENT gcd = gcd * pow ( 2 , count // n ) ; NEW_LINE DEDENT for i in range ( 3 , ( int ) ( math . sqrt ( p ) ) , 2 ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( p % i == 0 ) : NEW_LINE INDENT count = count + 1 ; NEW_LINE p = p // i ; NEW_LINE DEDENT if ( count > 0 ) : NEW_LINE INDENT gcd = gcd * pow ( i , count // n ) ; NEW_LINE DEDENT DEDENT if ( p > 2 ) : NEW_LINE INDENT gcd = gcd * pow ( p , 1 // n ) ; NEW_LINE DEDENT return gcd ; NEW_LINE DEDENT n = 3 ; NEW_LINE p = 80 ; NEW_LINE print ( max_gcd ( n , p ) ) ; NEW_LINE
Minimum positive integer divisible by C and is not in range [ A , B ] | Function to return the required number ; If doesn 't belong to the range then c is the required number ; Else get the next multiple of c starting from b + 1 ; Driver code
def getMinNum ( a , b , c ) : NEW_LINE INDENT if ( c < a or c > b ) : NEW_LINE INDENT return c NEW_LINE DEDENT x = ( ( b // c ) * c ) + c NEW_LINE return x NEW_LINE DEDENT a , b , c = 2 , 4 , 4 NEW_LINE print ( getMinNum ( a , b , c ) ) NEW_LINE
Count of pairs of ( i , j ) such that ( ( n % i ) % j ) % n is maximized | Function to return the count of required pairs ; Special case ; Number which will give the max value for ( ( n % i ) % j ) % n ; To store the maximum possible value of ( ( n % i ) % j ) % n ; Count of possible pairs ; Driver code
def countPairs ( n ) : NEW_LINE INDENT if ( n == 2 ) : NEW_LINE INDENT return 4 NEW_LINE DEDENT num = ( ( n // 2 ) + 1 ) ; NEW_LINE max = n % num ; NEW_LINE count = n - max ; NEW_LINE return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; NEW_LINE DEDENT print ( countPairs ( n ) ) ; NEW_LINE
Remove characters from a numeric string such that string becomes divisible by 8 | Python3 program to remove digits from a numeric string such that the number becomes divisible by 8 ; Function that return true if sub is a sub - sequence in s ; Function to return a multiple of 8 formed after removing 0 or more characters from the given string ; Iterate over all multiples of 8 ; If current multiple exists as a subsequence in the given string ; Driver Code
import math as mt NEW_LINE def checkSub ( sub , s ) : NEW_LINE INDENT j = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( sub [ j ] == s [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT if j == int ( len ( sub ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def getMultiple ( s ) : NEW_LINE INDENT for i in range ( 0 , 10 ** 3 , 8 ) : NEW_LINE INDENT if ( checkSub ( str ( i ) , s ) ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT s = "3454" NEW_LINE print ( getMultiple ( s ) ) NEW_LINE
Program to check if a number is divisible by any of its digits | Python implementation of above approach ; Converting integer to string ; Traversing the string ; If the number is divisible by digits then return yes ; If no digits are dividing the number then return no ; Driver Code ; passing this number to get result function
def getResult ( n ) : NEW_LINE INDENT st = str ( n ) NEW_LINE for i in st : NEW_LINE INDENT if ( n % int ( i ) == 0 ) : NEW_LINE INDENT return ' Yes ' NEW_LINE DEDENT DEDENT return ' No ' NEW_LINE DEDENT n = 9876543 NEW_LINE print ( getResult ( n ) ) NEW_LINE
Program to find sum of harmonic series | Python program to find sum of harmonic series using recursion ; Base condition ; Driven Code
def sum ( n ) : NEW_LINE INDENT if n < 2 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 / n + ( sum ( n - 1 ) ) NEW_LINE DEDENT DEDENT print ( sum ( 8 ) ) NEW_LINE print ( sum ( 10 ) ) NEW_LINE
Sum of P terms of an AP if Mth and Nth terms are given | Python3 implementation of the above approach ; Function to calculate the value of the ; Calculate value of d using formula ; Calculate value of a using formula ; Return pair ; Function to calculate value sum of first p numbers of the series ; First calculate value of a and d ; Calculate the sum by using formula ; Return the Sum ; Driver Code
import math as mt NEW_LINE def findingValues ( m , n , mth , nth ) : NEW_LINE INDENT d = ( ( abs ( mth - nth ) ) / abs ( ( m - 1 ) - ( n - 1 ) ) ) NEW_LINE a = mth - ( ( m - 1 ) * d ) NEW_LINE return a , d NEW_LINE DEDENT def findSum ( m , n , mth , nth , p ) : NEW_LINE INDENT a , d = findingValues ( m , n , mth , nth ) NEW_LINE Sum = ( p * ( 2 * a + ( p - 1 ) * d ) ) / 2 NEW_LINE return Sum NEW_LINE DEDENT m = 6 NEW_LINE n = 10 NEW_LINE mTerm = 12 NEW_LINE nTerm = 20 NEW_LINE p = 5 NEW_LINE print ( findSum ( m , n , mTerm , nTerm , p ) ) NEW_LINE
Print all integers that are sum of powers of two given numbers | Function to print powerful integers ; Set is used to store distinct numbers in sorted order ; Store all the powers of y < bound in a vector to avoid calculating them again and again ; x ^ i ; If num is within limits insert it into the set ; Break out of the inner loop ; Adding any number to it will be out of bounds ; Increment i ; Print the contents of the set ; Driver code ; Print powerful integers
def powerfulIntegers ( x , y , bound ) : NEW_LINE INDENT s = set ( ) NEW_LINE powersOfY = [ ] NEW_LINE powersOfY . append ( 1 ) NEW_LINE i = y NEW_LINE while i < bound and y != 1 : NEW_LINE INDENT powersOfY . append ( i ) NEW_LINE i *= y NEW_LINE DEDENT i = 0 NEW_LINE while ( True ) : NEW_LINE INDENT xPowI = pow ( x , i ) NEW_LINE for j in powersOfY : NEW_LINE INDENT num = xPowI + j NEW_LINE if ( num <= bound ) : NEW_LINE INDENT s . add ( num ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( xPowI >= bound or x == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT for itr in s : NEW_LINE INDENT print ( itr , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 2 NEW_LINE y = 3 NEW_LINE bound = 10 NEW_LINE powerfulIntegers ( x , y , bound ) NEW_LINE DEDENT
Distribute N candies among K people | Python3 code for better approach to distribute candies ; Function to find out the number of candies every person received ; Count number of complete turns ; Get the last term ; Stores the number of candies ; Last term of last and current series ; Sum of current and last series ; Sum of current series only ; If sum of current is less than N ; else : Individually distribute ; First term ; Distribute candies till there ; Candies available ; Not available ; Count the total candies ; Print the total candies ; Driver Code
import math as mt NEW_LINE def candies ( n , k ) : NEW_LINE INDENT count = 0 NEW_LINE ind = 1 NEW_LINE arr = [ 0 for i in range ( k ) ] NEW_LINE while n > 0 : NEW_LINE INDENT f1 = ( ind - 1 ) * k NEW_LINE f2 = ind * k NEW_LINE sum1 = ( f1 * ( f1 + 1 ) ) // 2 NEW_LINE sum2 = ( f2 * ( f2 + 1 ) ) // 2 NEW_LINE res = sum2 - sum1 NEW_LINE if ( res <= n ) : NEW_LINE INDENT count += 1 NEW_LINE n -= res NEW_LINE ind += 1 NEW_LINE i = 0 NEW_LINE term = ( ( ind - 1 ) * k ) + 1 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( term <= n ) : NEW_LINE INDENT arr [ i ] = term NEW_LINE i += 1 NEW_LINE n -= term NEW_LINE term += 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = n NEW_LINE i += 1 NEW_LINE n = 0 NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( k ) : NEW_LINE INDENT arr [ i ] += ( ( count * ( i + 1 ) ) + ( k * ( count * ( count - 1 ) ) // 2 ) ) NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT n , k = 10 , 3 NEW_LINE candies ( n , k ) NEW_LINE
Distribute N candies among K people | Function to find out the number of candies every person received ; Count number of complete turns ; Get the last term ; Stores the number of candies ; Do a binary search to find the number whose sum is less than N . ; Get mide ; If sum is below N ; Find number of complete turns ; Right halve ; Left halve ; Last term of last complete series ; Subtract the sum till ; First term of incomplete series ; Count the total candies ; Print the total candies ; Driver Code
def candies ( n , k ) : NEW_LINE INDENT count = 0 ; NEW_LINE ind = 1 ; NEW_LINE arr = [ 0 ] * k ; NEW_LINE low = 0 ; NEW_LINE high = n ; NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) >> 1 ; NEW_LINE sum = ( mid * ( mid + 1 ) ) >> 1 ; NEW_LINE if ( sum <= n ) : NEW_LINE INDENT count = int ( mid / k ) ; NEW_LINE low = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 ; NEW_LINE DEDENT DEDENT last = ( count * k ) ; NEW_LINE n -= int ( ( last * ( last + 1 ) ) / 2 ) ; NEW_LINE i = 0 ; NEW_LINE term = ( count * k ) + 1 ; NEW_LINE while ( n ) : NEW_LINE INDENT if ( term <= n ) : NEW_LINE INDENT arr [ i ] = term ; NEW_LINE i += 1 ; NEW_LINE n -= term ; NEW_LINE term += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] += n ; NEW_LINE n = 0 ; NEW_LINE DEDENT DEDENT for i in range ( k ) : NEW_LINE INDENT arr [ i ] += ( ( count * ( i + 1 ) ) + int ( k * ( count * ( count - 1 ) ) / 2 ) ) ; NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT n = 7 ; NEW_LINE k = 4 ; NEW_LINE candies ( n , k ) ; NEW_LINE
Smallest multiple of 3 which consists of three given non | Function to return the minimum number divisible by 3 formed by the given digits ; Sort the given array in ascending ; Check if any single digit is divisible by 3 ; Check if any two digit number formed by the given digits is divisible by 3 starting from the minimum ; Generate the two digit number ; If none of the above is true , we can form three digit number by taking a [ 0 ] three times . ; Driver code
def printSmallest ( a , n ) : NEW_LINE INDENT sum0 , sum1 = 0 , 0 NEW_LINE a = sorted ( a ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 3 == 0 ) : NEW_LINE INDENT return a [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT num = ( a [ i ] * 10 ) + a [ j ] NEW_LINE if ( num % 3 == 0 ) : NEW_LINE INDENT return num NEW_LINE DEDENT DEDENT DEDENT return a [ 0 ] * 100 + a [ 0 ] * 10 + a [ 0 ] NEW_LINE DEDENT arr = [ 7 , 7 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( printSmallest ( arr , n ) ) NEW_LINE
Print matrix after applying increment operations in M ranges | Function to update and print the matrix after performing queries ; Add 1 to the first element of the sub - matrix ; If there is an element after the last element of the sub - matrix then decrement it by 1 ; Calculate the running sum ; Print the updated element ; Next line ; Size of the matrix ; Queries
def updateMatrix ( n , q , mat ) : NEW_LINE INDENT for i in range ( 0 , len ( q ) ) : NEW_LINE INDENT X1 = q [ i ] [ 0 ] ; NEW_LINE Y1 = q [ i ] [ 1 ] ; NEW_LINE X2 = q [ i ] [ 2 ] ; NEW_LINE Y2 = q [ i ] [ 3 ] ; NEW_LINE mat [ X1 ] [ Y1 ] = mat [ X1 ] [ Y1 ] + 1 ; NEW_LINE if ( Y2 + 1 < n ) : NEW_LINE INDENT mat [ X2 ] [ Y2 + 1 ] = mat [ X2 ] [ Y2 + 1 ] - 1 ; NEW_LINE DEDENT elif ( X2 + 1 < n ) : NEW_LINE INDENT mat [ X2 + 1 ] [ 0 ] = mat [ X2 + 1 ] [ 0 ] - 1 ; NEW_LINE DEDENT DEDENT sum = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT sum = sum + mat [ i ] [ j ] ; NEW_LINE print ( sum , end = ' ▁ ' ) ; NEW_LINE DEDENT print ( " ▁ " ) ; NEW_LINE DEDENT DEDENT n = 5 ; NEW_LINE mat = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] ; NEW_LINE q = [ [ 0 , 0 , 1 , 2 ] , [ 1 , 2 , 3 , 4 ] , [ 1 , 4 , 3 , 4 ] ] ; NEW_LINE updateMatrix ( n , q , mat ) ; NEW_LINE
Replace the maximum element in the array by coefficient of range | Utility function to print the contents of the array ; Function to replace the maximum element from the array with the coefficient of range of the array ; Maximum element from the array ; Minimum element from the array ; Calculate the coefficient of range for the array ; Assuming all the array elements are distinct . Replace the maximum element with the coefficient of range of the array ; Print the updated array ; Driver code
def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def replaceMax ( arr , n ) : NEW_LINE INDENT max_element = max ( arr ) NEW_LINE min_element = min ( arr ) NEW_LINE ranges = max_element - min_element NEW_LINE coeffOfRange = ranges / ( max_element + min_element ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == max_element ) : NEW_LINE INDENT arr [ i ] = coeffOfRange NEW_LINE break NEW_LINE DEDENT DEDENT printArr ( arr , n ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 15 , 16 , 10 , 9 , 6 , 7 , 17 ] NEW_LINE n = len ( arr ) NEW_LINE replaceMax ( arr , n ) NEW_LINE DEDENT
Divide the two given numbers by their common divisors | print the numbers after dividing them by their common factors ; iterate from 1 to minimum of a and b ; if i is the common factor of both the numbers ; Driver code ; divide A and B by their common factors
def divide ( a , b ) : NEW_LINE INDENT for i in range ( 2 , min ( a , b ) + 1 ) : NEW_LINE INDENT while ( a % i == 0 and b % i == 0 ) : NEW_LINE INDENT a = a // i NEW_LINE b = b // i NEW_LINE DEDENT DEDENT print ( " A ▁ = " , a , " , ▁ B ▁ = " , b ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A , B = 10 , 15 NEW_LINE divide ( A , B ) NEW_LINE DEDENT
Divide the two given numbers by their common divisors | Function to calculate gcd of two numbers ; Function to calculate all common divisors of two given numbers a , b -- > input eger numbers ; find gcd of a , b ; Driver code
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def commDiv ( a , b ) : NEW_LINE INDENT n = gcd ( a , b ) NEW_LINE a = a // n NEW_LINE b = b // n NEW_LINE print ( " A ▁ = " , a , " , ▁ B ▁ = " , b ) NEW_LINE DEDENT a , b = 10 , 15 NEW_LINE commDiv ( a , b ) NEW_LINE
Minimum absolute difference between N and a power of 2 | Python3 implementation of the above approach ; Function to return the minimum difference between N and a power of 2 ; Power of 2 closest to n on its left ; Power of 2 closest to n on its right ; Return the minimum abs difference ; Driver code
import math NEW_LINE def minAbsDiff ( n ) : NEW_LINE INDENT left = 1 << ( int ) ( math . floor ( math . log2 ( n ) ) ) NEW_LINE right = left * 2 NEW_LINE return min ( ( n - left ) , ( right - n ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 15 NEW_LINE print ( minAbsDiff ( n ) ) NEW_LINE DEDENT
Find probability that a player wins when probabilities of hitting the target are given | Function to return the probability of the winner ; Driver Code ; Will print 9 digits after the decimal point
def find_probability ( p , q , r , s ) : NEW_LINE INDENT t = ( 1 - p / q ) * ( 1 - r / s ) NEW_LINE ans = ( p / q ) / ( 1 - t ) ; NEW_LINE return round ( ans , 9 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p , q , r , s = 1 , 2 , 1 , 2 NEW_LINE print ( find_probability ( p , q , r , s ) ) NEW_LINE DEDENT
Represent n as the sum of exactly k powers of two | Set 2 | Function to print k numbers which are powers of two and whose sum is equal to n ; Initialising the sum with k ; Initialising an array A with k elements and filling all elements with 1 ; Iterating A [ ] from k - 1 to 0 ; Update sum and A [ i ] till sum + A [ i ] is less than equal to n ; Impossible to find the combination ; Possible solution is stored in A [ ] ; Driver code
def FindAllElements ( n , k ) : NEW_LINE INDENT sum = k NEW_LINE A = [ 1 for i in range ( k ) ] NEW_LINE i = k - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT while ( sum + A [ i ] <= n ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE A [ i ] *= 2 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT if ( sum != n ) : NEW_LINE INDENT print ( " Impossible " ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 0 , k , 1 ) : NEW_LINE INDENT print ( A [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 NEW_LINE k = 6 NEW_LINE FindAllElements ( n , k ) NEW_LINE DEDENT
Check whether a + b = c or not after removing all zeroes from a , b and c | Function to remove zeroes ; Initialize result to zero holds the Result after removing zeroes from no ; Initialize variable d to 1 that holds digits of no ; Loop while n is greater then zero ; Check if n mod 10 is not equal to zero ; store the result by removing zeroes And increment d by 10 ; Go to the next digit ; Return the result ; Function to check if sum is true after Removing all zeroes . ; Call removeZero ( ) for both sides and check whether they are equal After removing zeroes . ; Driver code
def removeZero ( n ) : NEW_LINE INDENT res = 0 NEW_LINE d = 1 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( n % 10 != 0 ) : NEW_LINE INDENT res += ( n % 10 ) * d NEW_LINE d *= 10 NEW_LINE DEDENT n //= 10 NEW_LINE DEDENT return res NEW_LINE DEDENT def isEqual ( a , b ) : NEW_LINE INDENT if ( removeZero ( a ) + removeZero ( b ) == removeZero ( a + b ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT a = 105 NEW_LINE b = 106 NEW_LINE if ( isEqual ( a , b ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
A Sum Array Puzzle | Python3 implementation of above approach ; Allocate memory for temporary arrays leftSum [ ] , rightSum [ ] and Sum [ ] ; Left most element of left array is always 0 ; Rightmost most element of right array is always 0 ; Construct the left array ; Construct the right array ; Construct the sum array using left [ ] and right [ ] ; print the constructed prod array ; Driver Code
def sumArray ( arr , n ) : NEW_LINE INDENT leftSum = [ 0 for i in range ( n ) ] NEW_LINE rightSum = [ 0 for i in range ( n ) ] NEW_LINE Sum = [ 0 for i in range ( n ) ] NEW_LINE i , j = 0 , 0 NEW_LINE leftSum [ 0 ] = 0 NEW_LINE rightSum [ n - 1 ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT leftSum [ i ] = arr [ i - 1 ] + leftSum [ i - 1 ] NEW_LINE DEDENT for j in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT rightSum [ j ] = arr [ j + 1 ] + rightSum [ j + 1 ] NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT Sum [ i ] = leftSum [ i ] + rightSum [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( Sum [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 3 , 6 , 4 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE sumArray ( arr , n ) NEW_LINE
Find minimum x such that ( x % k ) * ( x / k ) == n | Set | Python3 program to find the minimum positive X such that the given equation holds true ; This function gives the required answer ; Iterate for all the factors ; Check if i is a factor ; Consider i to be A and n / i to be B ; Consider i to be B and n / i to be A ; Driver Code
import sys NEW_LINE def minimumX ( n , k ) : NEW_LINE INDENT mini = sys . maxsize NEW_LINE i = 1 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT fir = i NEW_LINE sec = n // i NEW_LINE num1 = fir * k + sec NEW_LINE res = ( num1 // k ) * ( num1 % k ) NEW_LINE if ( res == n ) : NEW_LINE INDENT mini = min ( num1 , mini ) NEW_LINE DEDENT num2 = sec * k + fir NEW_LINE res = ( num2 // k ) * ( num2 % k ) NEW_LINE if ( res == n ) : NEW_LINE INDENT mini = min ( num2 , mini ) NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return mini NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE k = 6 NEW_LINE print ( minimumX ( n , k ) ) NEW_LINE n = 5 NEW_LINE k = 5 NEW_LINE print ( minimumX ( n , k ) ) NEW_LINE DEDENT
Find minimum x such that ( x % k ) * ( x / k ) == n | This function gives the required answer ; Iterate over all possible remainders ; it must divide n ; Driver Code
def minimumX ( n , k ) : NEW_LINE INDENT ans = 10 ** 18 NEW_LINE for i in range ( k - 1 , 0 , - 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT ans = min ( ans , i + ( n / i ) * k ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n , k = 4 , 6 NEW_LINE print ( minimumX ( n , k ) ) NEW_LINE n , k = 5 , 5 NEW_LINE print ( minimumX ( n , k ) ) NEW_LINE
Find nth Hermite number | Function to return nth Hermite number ; Base conditions ; Driver Code ; Print nth Hermite number
def getHermiteNumber ( n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return ( - 2 * ( n - 1 ) * getHermiteNumber ( n - 2 ) ) NEW_LINE DEDENT DEDENT n = 6 NEW_LINE print ( getHermiteNumber ( n ) ) ; NEW_LINE
Find numbers a and b that satisfy the given conditions | Function to print the required numbers ; Suppose b = n and we want a % b = 0 and also ( a / b ) < n so a = b * ( n - 1 ) ; Special case if n = 1 we get a = 0 so ( a * b ) < n ; If no pair satisfies the conditions ; Driver Code
def find ( n ) : NEW_LINE INDENT b = n NEW_LINE a = b * ( n - 1 ) NEW_LINE if a * b > n and a // b < n : NEW_LINE INDENT print ( " a ▁ = ▁ { } , ▁ b ▁ = ▁ { } " . format ( a , b ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 NEW_LINE find ( n ) NEW_LINE DEDENT
Closest perfect square and its distance | Function to check if a number is perfect square or not ; Function to find the closest perfect square taking minimum steps to reach from a number ; Variables to store first perfect square number above and below N ; Finding first perfect square number greater than N ; Finding first perfect square number less than N ; Variables to store the differences ; Driver code
from math import sqrt , floor NEW_LINE def isPerfect ( N ) : NEW_LINE INDENT if ( sqrt ( N ) - floor ( sqrt ( N ) ) != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def getClosestPerfectSquare ( N ) : NEW_LINE INDENT if ( isPerfect ( N ) ) : NEW_LINE INDENT print ( N , "0" ) NEW_LINE return NEW_LINE DEDENT aboveN = - 1 NEW_LINE belowN = - 1 NEW_LINE n1 = 0 NEW_LINE n1 = N + 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( isPerfect ( n1 ) ) : NEW_LINE INDENT aboveN = n1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT n1 += 1 NEW_LINE DEDENT DEDENT n1 = N - 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( isPerfect ( n1 ) ) : NEW_LINE INDENT belowN = n1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT n1 -= 1 NEW_LINE DEDENT DEDENT diff1 = aboveN - N NEW_LINE diff2 = N - belowN NEW_LINE if ( diff1 > diff2 ) : NEW_LINE INDENT print ( belowN , diff2 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( aboveN , diff1 ) NEW_LINE DEDENT DEDENT N = 1500 NEW_LINE getClosestPerfectSquare ( N ) NEW_LINE
Fraction | Function to return gcd of a and b ; Function to convert the obtained fraction into it 's simplest form ; Finding gcd of both terms ; Converting both terms into simpler terms by dividing them by common factor ; Function to add two fractions ; Finding gcd of den1 and den2 ; Denominator of final fraction obtained finding LCM of den1 and den2 LCM * GCD = a * b ; Changing the fractions to have same denominator Numerator of the final fraction obtained ; Calling function to convert final fraction into it 's simplest form ; Driver Code
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def lowest ( den3 , num3 ) : NEW_LINE INDENT common_factor = gcd ( num3 , den3 ) NEW_LINE den3 = int ( den3 / common_factor ) NEW_LINE num3 = int ( num3 / common_factor ) NEW_LINE print ( num3 , " / " , den3 ) NEW_LINE DEDENT def addFraction ( num1 , den1 , num2 , den2 ) : NEW_LINE INDENT den3 = gcd ( den1 , den2 ) NEW_LINE den3 = ( den1 * den2 ) / den3 NEW_LINE num3 = ( ( num1 ) * ( den3 / den1 ) + ( num2 ) * ( den3 / den2 ) ) NEW_LINE lowest ( den3 , num3 ) NEW_LINE DEDENT num1 = 1 ; den1 = 500 NEW_LINE num2 = 2 ; den2 = 1500 NEW_LINE print ( num1 , " / " , den1 , " ▁ + ▁ " , num2 , " / " , den2 , " ▁ is ▁ equal ▁ to ▁ " , end = " " ) NEW_LINE addFraction ( num1 , den1 , num2 , den2 ) NEW_LINE
Largest Divisor of a Number not divisible by a perfect square | Efficient Python3 Program to find the largest divisor not divisible by any perfect square greater than 1 ; Function to find the largest divisor not divisible by any perfect square greater than 1 ; If the number is divisible by i * i , then remove one i ; Now all squares are removed from n ; Driver Code
import math NEW_LINE def findLargestDivisor ( n ) : NEW_LINE INDENT for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT while ( n % ( i * i ) == 0 ) : NEW_LINE INDENT n = n // i NEW_LINE DEDENT DEDENT return n NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 12 NEW_LINE print ( findLargestDivisor ( n ) ) NEW_LINE n = 97 NEW_LINE print ( findLargestDivisor ( n ) ) NEW_LINE DEDENT
Arithmetic Progression | Returns true if a permutation of arr [ 0. . n - 1 ] can form arithmetic progression ; Sort array ; After sorting , difference between consecutive elements must be same . ; Driver code
def checkIsAP ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : return True NEW_LINE arr . sort ( ) NEW_LINE d = arr [ 1 ] - arr [ 0 ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] != d ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 20 , 15 , 5 , 0 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Yes " ) if ( checkIsAP ( arr , n ) ) else print ( " No " ) NEW_LINE
Check if a number is Triperfect Number | Returns true if n is Triperfect ; To store sum of divisors . Adding 1 and n since they are divisors of n . ; Find all divisors and add them ; If sum of divisors is equal to 3 * n , then n is a Triperfect number ; Driver program
def isTriPerfect ( n ) : NEW_LINE INDENT sum = 1 + n NEW_LINE i = 2 NEW_LINE while i * i <= n : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT if n / i == i : NEW_LINE INDENT sum = sum + i NEW_LINE DEDENT else : NEW_LINE INDENT sum = sum + i + n / i NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return ( True if sum == 3 * n and n != 1 else False ) NEW_LINE DEDENT n = 120 NEW_LINE if isTriPerfect ( n ) : NEW_LINE INDENT print ( n , " is ▁ a ▁ Triperfect ▁ number " ) NEW_LINE DEDENT
Sum of first N natural numbers which are divisible by X or Y | Python 3 program to find sum of numbers from 1 to N which are divisible by X or Y ; Function to calculate the sum of numbers divisible by X or Y ; Driver code
from math import ceil , floor NEW_LINE def sum ( N , X , Y ) : NEW_LINE INDENT S1 = floor ( floor ( N / X ) * floor ( 2 * X + floor ( N / X - 1 ) * X ) / 2 ) NEW_LINE S2 = floor ( floor ( N / Y ) ) * floor ( 2 * Y + floor ( N / Y - 1 ) * Y ) / 2 NEW_LINE S3 = floor ( floor ( N / ( X * Y ) ) ) * floor ( 2 * ( X * Y ) + floor ( N / ( X * Y ) - 1 ) * ( X * Y ) ) / 2 NEW_LINE return S1 + S2 - S3 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 14 NEW_LINE X = 3 NEW_LINE Y = 5 NEW_LINE print ( int ( sum ( N , X , Y ) ) ) NEW_LINE DEDENT
Count numbers from range whose prime factors are only 2 and 3 | Function to count the number within a range whose prime factors are only 2 and 3 ; Start with 2 so that 1 doesn 't get counted ; While num is divisible by 2 , divide it by 2 ; While num is divisible by 3 , divide it by 3 ; If num got reduced to 1 then it has only 2 and 3 as prime factors ; Driver code
def findTwoThreePrime ( l , r ) : NEW_LINE INDENT if ( l == 1 ) : NEW_LINE INDENT l += 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT num = i NEW_LINE while ( num % 2 == 0 ) : NEW_LINE INDENT num //= 2 ; NEW_LINE DEDENT while ( num % 3 == 0 ) : NEW_LINE INDENT num //= 3 NEW_LINE DEDENT if ( num == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 1 NEW_LINE r = 10 NEW_LINE print ( findTwoThreePrime ( l , r ) ) NEW_LINE DEDENT
Maximum number with same digit factorial product | Function to return the required number ; Count the frequency of each digit ; 4 ! can be expressed as 2 ! * 2 ! * 3 ! ; 6 ! can be expressed as 5 ! * 3 ! ; 8 ! can be expressed as 7 ! * 2 ! * 2 ! * 2 ! ; 9 ! can be expressed as 7 ! * 3 ! * 3 ! * 2 ! ; To store the required number ; If number has only either 1 and 0 as its digits ; Generate the greatest number possible ; Driver code
def getNumber ( s ) : NEW_LINE INDENT number_of_digits = len ( s ) ; NEW_LINE freq = [ 0 ] * 10 ; NEW_LINE for i in range ( number_of_digits ) : NEW_LINE INDENT if ( s [ i ] == '1' or s [ i ] == '2' or s [ i ] == '3' or s [ i ] == '5' or s [ i ] == '7' ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - 48 ] += 1 ; NEW_LINE DEDENT if ( s [ i ] == '4' ) : NEW_LINE INDENT freq [ 2 ] += 2 ; NEW_LINE freq [ 3 ] += 1 ; NEW_LINE DEDENT if ( s [ i ] == '6' ) : NEW_LINE INDENT freq [ 5 ] += 1 ; NEW_LINE freq [ 3 ] += 1 ; NEW_LINE DEDENT if ( s [ i ] == '8' ) : NEW_LINE INDENT freq [ 7 ] += 1 ; NEW_LINE freq [ 2 ] += 3 ; NEW_LINE DEDENT if ( s [ i ] == '9' ) : NEW_LINE INDENT freq [ 7 ] += 1 ; NEW_LINE freq [ 3 ] += 2 ; NEW_LINE freq [ 2 ] += 1 ; NEW_LINE DEDENT DEDENT t = " " ; NEW_LINE if ( freq [ 1 ] == number_of_digits or freq [ 0 ] == number_of_digits or ( freq [ 0 ] + freq [ 1 ] ) == number_of_digits ) : NEW_LINE INDENT return s ; NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 9 , 1 , - 1 ) : NEW_LINE INDENT ctr = freq [ i ] ; NEW_LINE while ( ctr > 0 ) : NEW_LINE INDENT t += chr ( i + 48 ) ; NEW_LINE ctr -= 1 ; NEW_LINE DEDENT DEDENT return t ; NEW_LINE DEDENT DEDENT s = "1280" ; NEW_LINE print ( getNumber ( s ) ) ; NEW_LINE
Program to find first N Iccanobif Numbers | Iterative function to reverse digits of num ; Function to print first N Icanobif Numbers ; Initialize first , second numbers ; Print first two numbers ; Reversing digit of previous two terms and adding them ; Driver code
def reversedigit ( num ) : NEW_LINE INDENT rev_num = 0 NEW_LINE while num > 0 : NEW_LINE INDENT rev_num = rev_num * 10 + num % 10 NEW_LINE num = num // 10 NEW_LINE DEDENT return rev_num NEW_LINE DEDENT def icanobifNumbers ( N ) : NEW_LINE INDENT first = 0 NEW_LINE second = 1 NEW_LINE if N == 1 : NEW_LINE INDENT print ( first ) NEW_LINE DEDENT elif N == 2 : NEW_LINE INDENT print ( first , second ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( first , second , end = " ▁ " ) NEW_LINE for i in range ( 3 , N + 1 ) : NEW_LINE INDENT x = reversedigit ( first ) NEW_LINE y = reversedigit ( second ) NEW_LINE print ( x + y , end = " ▁ " ) NEW_LINE temp = second NEW_LINE second = x + y NEW_LINE first = temp NEW_LINE DEDENT DEDENT DEDENT N = 12 NEW_LINE icanobifNumbers ( N ) NEW_LINE
Add N digits to A such that it is divisible by B after each addition | Python3 implementation of the approach ; Try all digits from ( 0 to 9 ) ; Fails in the first move itself ; Add ( n - 1 ) 0 's ; Driver Code
def addNDigits ( a , b , n ) : NEW_LINE INDENT num = a NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT tmp = a * 10 + i NEW_LINE if ( tmp % b == 0 ) : NEW_LINE INDENT a = tmp NEW_LINE break NEW_LINE DEDENT DEDENT if ( num == a ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for j in range ( n - 1 ) : NEW_LINE INDENT a *= 10 NEW_LINE DEDENT return a NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 5 NEW_LINE b = 3 NEW_LINE n = 3 NEW_LINE print ( addNDigits ( a , b , n ) ) NEW_LINE DEDENT
Count number of triplets ( a , b , c ) such that a ^ 2 + b ^ 2 = c ^ 2 and 1 <= a <= b <= c <= n | Python3 program to Find number of Triplets 1 <= a <= b <= c <= n , Such that a ^ 2 + b ^ 2 = c ^ 2 ; function to ind number of Triplets 1 <= a <= b <= c <= n , Such that a ^ 2 + b ^ 2 = c ^ 2 ; to store required answer ; run nested loops for first two numbers . ; third number ; check if third number is perfect square and less than n ; Driver code ; function call
import math NEW_LINE def Triplets ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( i , n + 1 ) : NEW_LINE INDENT x = i * i + j * j NEW_LINE y = int ( math . sqrt ( x ) ) NEW_LINE if ( y * y == x and y <= n ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 NEW_LINE print ( Triplets ( n ) ) NEW_LINE DEDENT
Sum of the digits of a number N written in all bases from 2 to N / 2 | Python 3 implementation of the approach ; Function to calculate the sum of the digits of n in the given base ; Sum of digits ; Digit of n in the given base ; Add the digit ; Function to calculate the sum of digits of n in bases from 2 to n / 2 ; to store digit sum in all base ; function call for multiple bases ; Driver program
from math import floor NEW_LINE def solve ( n , base ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT remainder = n % base NEW_LINE sum = sum + remainder NEW_LINE n = int ( n / base ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def SumsOfDigits ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE N = floor ( n / 2 ) NEW_LINE for base in range ( 2 , N + 1 , 1 ) : NEW_LINE INDENT sum = sum + solve ( n , base ) NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 8 NEW_LINE SumsOfDigits ( n ) NEW_LINE DEDENT
Largest number in an array that is not a perfect cube | Python 3 program to find the largest non - perfect cube number among n numbers ; Function to check if a number is perfect cube number or not ; takes the sqrt of the number ; checks if it is a perfect cube number ; Function to find the largest non perfect cube number in the array ; stores the maximum of all perfect cube numbers ; Traverse all elements in the array ; store the maximum if current element is a non perfect cube ; Driver Code
import math NEW_LINE def checkPerfectcube ( n ) : NEW_LINE INDENT cube_root = n ** ( 1. / 3. ) NEW_LINE if round ( cube_root ) ** 3 == n : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def largestNonPerfectcubeNumber ( a , n ) : NEW_LINE INDENT maxi = - 1 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( checkPerfectcube ( a [ i ] ) == False ) : NEW_LINE INDENT maxi = max ( a [ i ] , maxi ) NEW_LINE DEDENT DEDENT return maxi NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 16 , 64 , 25 , 2 , 3 , 10 ] NEW_LINE n = len ( a ) NEW_LINE print ( largestNonPerfectcubeNumber ( a , n ) ) NEW_LINE DEDENT
Check if N can be represented as sum of integers chosen from set { A , B } | Function to find if number N can be represented as sum of a ' s ▁ and ▁ b ' s ; base condition ; If x is already visited ; Set x as possible ; Recursive call ; Driver Code
def checkIfPossibleRec ( x , a , b , isPossible , n ) : NEW_LINE INDENT if x > n : NEW_LINE INDENT return NEW_LINE DEDENT if isPossible [ x ] : NEW_LINE INDENT return NEW_LINE DEDENT isPossible [ x ] = True NEW_LINE checkIfPossibleRec ( x + a , a , b , isPossible , n ) NEW_LINE checkIfPossibleRec ( x + b , a , b , isPossible , n ) NEW_LINE DEDENT def checkPossible ( n , a , b ) : NEW_LINE INDENT isPossible = [ False ] * ( n + 1 ) NEW_LINE checkIfPossibleRec ( 0 , a , b , isPossible , n ) NEW_LINE return isPossible [ n ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a , b , n = 3 , 7 , 8 NEW_LINE if checkPossible ( a , b , n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Sum of all odd natural numbers in range L and R | Function to return the sum of all odd natural numbers ; Function to return the sum of all odd numbers in range L and R ; Driver code
def sumOdd ( n ) : NEW_LINE INDENT terms = ( n + 1 ) // 2 NEW_LINE sum1 = terms * terms NEW_LINE return sum1 NEW_LINE DEDENT def suminRange ( l , r ) : NEW_LINE INDENT return sumOdd ( r ) - sumOdd ( l - 1 ) NEW_LINE DEDENT l = 2 ; r = 5 NEW_LINE print ( " Sum ▁ of ▁ odd ▁ natural ▁ number " , " from ▁ L ▁ to ▁ R ▁ is " , suminRange ( l , r ) ) NEW_LINE
Sum of common divisors of two numbers A and B | Python 3 implementation of above approach ; Function to calculate all common divisors of two given numbers a , b -- > input integer numbers ; find gcd of a , b ; Find the sum of divisors of n . ; if ' i ' is factor of n ; check if divisors are equal ; Driver program to run the case
from math import gcd , sqrt NEW_LINE def sumcommDiv ( a , b ) : NEW_LINE INDENT n = gcd ( a , b ) NEW_LINE sum = 0 NEW_LINE N = int ( sqrt ( n ) ) + 1 NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n / i == i ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT else : NEW_LINE INDENT sum += ( n / i ) + i NEW_LINE DEDENT DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 10 NEW_LINE b = 15 NEW_LINE print ( " Sum ▁ = " , int ( sumcommDiv ( a , b ) ) ) NEW_LINE DEDENT
Check if a number is formed by Concatenation of 1 , 14 or 144 only | Function to check if a number is formed by Concatenation of 1 , 14 or 144 only ; check for each possible digit if given number consist other then 1 , 14 , 144 print NO else print YES ; Driver Code
def checkNumber ( N ) : NEW_LINE INDENT temp = N NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT if ( temp % 1000 == 144 ) : NEW_LINE INDENT temp /= 1000 NEW_LINE DEDENT elif ( temp % 100 == 14 ) : NEW_LINE INDENT temp /= 100 NEW_LINE DEDENT elif ( temp % 10 == 1 ) : NEW_LINE INDENT temp /= 10 NEW_LINE DEDENT else : NEW_LINE INDENT return " YES " NEW_LINE DEDENT DEDENT return " NO " NEW_LINE DEDENT N = 1414 ; NEW_LINE print ( checkNumber ( N ) ) ; NEW_LINE
Fibonacci problem ( Value of Fib ( N ) * Fib ( N ) | Python 3 implementation of the approach ; Driver code
def getResult ( n ) : NEW_LINE INDENT if n & 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT n = 3 NEW_LINE print ( getResult ( n ) ) NEW_LINE
Find two numbers with sum and product both same as N | Python 3 program to find a and b such that a * b = N and a + b = N ; Function to return the smallest string ; Not possible ; find a and b ; Driver Code
from math import sqrt NEW_LINE def findAandB ( N ) : NEW_LINE INDENT val = N * N - 4.0 * N NEW_LINE if ( val < 0 ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE return NEW_LINE DEDENT a = ( N + sqrt ( val ) ) / 2.0 NEW_LINE b = ( N - sqrt ( val ) ) / 2.0 NEW_LINE print ( " a ▁ = " , ' { 0 : . 6 } ' . format ( a ) ) NEW_LINE print ( " b ▁ = " , ' { 0 : . 6 } ' . format ( b ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 69.0 NEW_LINE findAandB ( N ) NEW_LINE DEDENT
Find minimum operations needed to make an Array beautiful | Function to find minimum operations required to make array beautiful ; counting consecutive zeros . ; check that start and end are same ; check is zero and one are equal ; Driver code
def minOperations ( A , n ) : NEW_LINE INDENT if n & 1 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT zeros , consZeros , ones = 0 , 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if A [ i ] : NEW_LINE INDENT zeros += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT if ( i + 1 < n ) : NEW_LINE INDENT if A [ i ] == 0 and A [ i + 1 ] == 0 : NEW_LINE INDENT consZeros += 1 NEW_LINE DEDENT DEDENT DEDENT if A [ 0 ] == A [ n - 1 ] and A [ 0 ] == 0 : NEW_LINE INDENT consZeros += 1 NEW_LINE DEDENT if zeros == ones : NEW_LINE INDENT return consZeros NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 1 , 0 , 0 ] NEW_LINE n = len ( A ) NEW_LINE print ( minOperations ( A , n ) ) NEW_LINE DEDENT
Steps to reduce N to zero by subtracting its most significant digit at every step | Function to count the number of digits in a number m ; Function to count the number of steps to reach 0 ; count the total number of stesp ; iterate till we reach 0 ; count the digits in last ; decrease it by 1 ; find the number on whose division , we get the first digit ; first digit in last ; find the first number less than last where the first digit changes ; find the number of numbers with same first digit that are jumped ; count the steps ; the next number with a different first digit ; Driver code
def countdig ( m ) : NEW_LINE INDENT if ( m == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 + countdig ( m // 10 ) NEW_LINE DEDENT DEDENT def countSteps ( x ) : NEW_LINE INDENT c = 0 NEW_LINE last = x NEW_LINE while ( last ) : NEW_LINE INDENT digits = countdig ( last ) NEW_LINE digits -= 1 NEW_LINE divisor = pow ( 10 , digits ) NEW_LINE first = last // divisor NEW_LINE lastnumber = first * divisor NEW_LINE skipped = ( last - lastnumber ) // first NEW_LINE skipped += 1 NEW_LINE c += skipped NEW_LINE last = last - ( first * skipped ) NEW_LINE DEDENT return c NEW_LINE DEDENT n = 14 NEW_LINE print ( countSteps ( n ) ) NEW_LINE
GCD of a number raised to some power and another number | Calculates modular exponentiation , i . e . , ( x ^ y ) % p in O ( log y ) ; x = x % p Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; Returns GCD of a ^ n and b ; Driver code
def power ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def powerGCD ( a , b , n ) : NEW_LINE INDENT e = power ( a , n , b ) NEW_LINE return gcd ( e , b ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 5 NEW_LINE b = 4 NEW_LINE n = 2 NEW_LINE print ( powerGCD ( a , b , n ) ) NEW_LINE DEDENT
Largest number not greater than N all the digits of which are odd | Function to check if all digits of a number are odd ; iterate for all digits ; if digit is even ; all digits are odd ; function to return the largest number with all digits odd ; iterate till we find a number with all digits odd ; Driver Code
def allOddDigits ( n ) : NEW_LINE INDENT while ( n ) : NEW_LINE INDENT if ( ( n % 10 ) % 2 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = int ( n / 10 ) NEW_LINE DEDENT return True NEW_LINE DEDENT def largestNumber ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT n -= 1 NEW_LINE DEDENT i = n NEW_LINE while ( 1 ) : NEW_LINE INDENT if ( allOddDigits ( i ) ) : NEW_LINE INDENT return i NEW_LINE DEDENT i -= 2 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 23 NEW_LINE print ( largestNumber ( N ) ) NEW_LINE DEDENT
Largest number not greater than N all the digits of which are odd | function to return the largest number with all digits odd ; convert the number to a string for easy operations ; find first even digit ; if no even digit , then N is the answer ; till first even digit , add all odd numbers ; decrease 1 from the even digit ; add 9 in the rest of the digits ; Driver Code
def largestNumber ( n ) : NEW_LINE INDENT s = " " NEW_LINE duplicate = n NEW_LINE while ( n ) : NEW_LINE INDENT s = chr ( n % 10 + 48 ) + s NEW_LINE n //= 10 NEW_LINE DEDENT index = - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( ( ( ord ( s [ i ] ) - ord ( '0' ) ) % 2 & 1 ) == 0 ) : NEW_LINE INDENT index = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( index == - 1 ) : NEW_LINE INDENT return duplicate NEW_LINE DEDENT num = 0 NEW_LINE for i in range ( index ) : NEW_LINE INDENT num = num * 10 + ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT num = num * 10 + ( ord ( s [ index ] ) - ord ( '0' ) - 1 ) NEW_LINE for i in range ( index + 1 , len ( s ) ) : NEW_LINE INDENT num = num * 10 + 9 NEW_LINE DEDENT return num NEW_LINE DEDENT N = 24578 NEW_LINE print ( largestNumber ( N ) ) NEW_LINE
Count number less than N which are product of perfect squares | Python 3 program to count number less than N which are product of any two perfect squares ; Function to count number less than N which are product of any two perfect squares ; Driver Code
import math NEW_LINE def countNumbers ( N ) : NEW_LINE INDENT return int ( math . sqrt ( N ) ) - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 36 NEW_LINE print ( countNumbers ( N ) ) NEW_LINE DEDENT
Count ordered pairs with product less than N | Python3 implementation of above approach ; Function to return count of Ordered pairs whose product are less than N ; Initialize count to 0 ; count total pairs ; multiply by 2 to get ordered_pairs ; subtract redundant pairs ( a , b ) where a == b . ; return answer ; Driver code ; function call to print required answer
from math import sqrt NEW_LINE def countOrderedPairs ( N ) : NEW_LINE INDENT count_pairs = 0 NEW_LINE p = int ( sqrt ( N - 1 ) ) + 1 NEW_LINE q = int ( sqrt ( N ) ) + 2 NEW_LINE for i in range ( 1 , p , 1 ) : NEW_LINE INDENT for j in range ( i , q , 1 ) : NEW_LINE INDENT count_pairs += 1 NEW_LINE DEDENT DEDENT count_pairs *= 2 NEW_LINE count_pairs -= int ( sqrt ( N - 1 ) ) NEW_LINE return count_pairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE print ( countOrderedPairs ( N ) ) NEW_LINE DEDENT
Absolute Difference of all pairwise consecutive elements in an array | Function to print pairwise absolute difference of consecutive elements ; absolute difference between consecutive numbers ; Driver Code
def pairwiseDifference ( arr , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT diff = abs ( arr [ i ] - arr [ i + 1 ] ) NEW_LINE print ( diff , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 10 , 15 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE pairwiseDifference ( arr , n ) NEW_LINE DEDENT
Find the sum of all multiples of 2 and 5 below N | Function to find sum of AP series ; Number of terms ; Function to find the sum of all multiples of 2 and 5 below N ; Since , we need the sum of multiples less than N ; Driver code
def sumAP ( n , d ) : NEW_LINE INDENT n = int ( n / d ) ; NEW_LINE return ( n ) * ( 1 + n ) * ( d / 2 ) ; NEW_LINE DEDENT def sumMultiples ( n ) : NEW_LINE INDENT n -= 1 ; NEW_LINE return ( int ( sumAP ( n , 2 ) + sumAP ( n , 5 ) - sumAP ( n , 10 ) ) ) ; NEW_LINE DEDENT n = 20 ; NEW_LINE print ( sumMultiples ( n ) ) ; NEW_LINE
Find the total marks obtained according to given marking scheme | Function that calculates marks . ; for not attempt score + 0 ; for each correct answer score + 3 ; for each wrong answer score - 1 ; calculate total marks ; Driver code
def markingScheme ( N , answerKey , studentAnswer ) : NEW_LINE INDENT positive = 0 NEW_LINE negative = 0 NEW_LINE notattempt = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( studentAnswer [ i ] == 0 ) : NEW_LINE INDENT notattempt += 1 NEW_LINE DEDENT elif ( answerKey [ i ] == studentAnswer [ i ] ) : NEW_LINE INDENT positive += 1 NEW_LINE DEDENT elif ( answerKey [ i ] != studentAnswer [ i ] ) : NEW_LINE INDENT negative += 1 NEW_LINE DEDENT DEDENT return ( positive * 3 ) + ( negative * - 1 ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT answerKey = [ 1 , 2 , 3 , 4 , 1 ] NEW_LINE studentAnswer = [ 1 , 2 , 3 , 4 , 0 ] NEW_LINE N = 5 NEW_LINE print ( markingScheme ( N , answerKey , studentAnswer ) ) NEW_LINE DEDENT
Find the Product of first N Prime Numbers | python3 implementation of above solution ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; if prime [ p ] is not changes , then it is a prime ; set all multiples of p to non - prime ; find the product of 1 st N prime numbers ; count of prime numbers ; product of prime numbers ; if the number is prime add it ; increase the count ; get to next number ; create the sieve ; find the value of 1 st n prime numbers
import math as mt NEW_LINE MAX = 10000 NEW_LINE prime = [ True for i in range ( MAX + 1 ) ] NEW_LINE def SieveOfErastosthenes ( ) : NEW_LINE INDENT prime [ 1 ] = False NEW_LINE for p in range ( 2 , mt . ceil ( mt . sqrt ( MAX ) ) ) : NEW_LINE INDENT if prime [ p ] : NEW_LINE INDENT for i in range ( 2 * p , MAX + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def solve ( n ) : NEW_LINE INDENT count , num = 0 , 1 NEW_LINE prod = 1 NEW_LINE while count < n : NEW_LINE INDENT if prime [ num ] : NEW_LINE INDENT prod *= num NEW_LINE count += 1 NEW_LINE DEDENT num += 1 NEW_LINE DEDENT return prod NEW_LINE DEDENT SieveOfErastosthenes ( ) NEW_LINE n = 5 NEW_LINE print ( solve ( n ) ) NEW_LINE
Program to find count of numbers having odd number of divisors in given range | Function to return the count of divisors of a number ; Count the powers of the current prime i which divides a ; Update the count of divisors ; Reset the count ; If the remaining a is prime then a ^ 1 will be one of its prime factors ; Function to count numbers having odd number of divisors in range [ A , B ] ; To store the count of elements having odd number of divisors ; Iterate from a to b and find the count of their divisors ; To store the count of divisors of i ; If the divisor count of i is odd ; Driver code
def divisor ( a ) : NEW_LINE INDENT div = 1 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( 2 , int ( pow ( a , 1 / 2 ) ) + 1 ) : NEW_LINE INDENT while ( a % i == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE a = a / i ; NEW_LINE DEDENT div = div * ( count + 1 ) ; NEW_LINE count = 0 ; NEW_LINE DEDENT if ( a > 1 ) : NEW_LINE INDENT div = div * ( 2 ) ; NEW_LINE DEDENT return div ; NEW_LINE DEDENT def OddDivCount ( a , b ) : NEW_LINE INDENT res = 0 ; NEW_LINE for i in range ( a , b + 1 ) : NEW_LINE INDENT divCount = divisor ( i ) ; NEW_LINE if ( divCount % 2 ) : NEW_LINE INDENT res += 1 ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a , b = 1 , 10 ; NEW_LINE print ( OddDivCount ( a , b ) ) ; NEW_LINE DEDENT
Check if there is any pair in a given range with GCD is divisible by k | Returns count of numbers in [ l r ] that are divisible by k . ; Add 1 explicitly as l is divisible by k ; l is not divisible by k ; Driver Code
def Check_is_possible ( l , r , k ) : NEW_LINE INDENT div_count = ( r // k ) - ( l // k ) NEW_LINE if l % k == 0 : NEW_LINE INDENT div_count += 1 NEW_LINE DEDENT return div_count > 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l , r , k = 30 , 70 , 10 NEW_LINE if Check_is_possible ( l , r , k ) == True : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Find sum of N | calculate sum of Nth group ; Driver code
def nth_group ( n ) : NEW_LINE INDENT return n * ( 2 * pow ( n , 2 ) + 1 ) NEW_LINE DEDENT N = 5 NEW_LINE print ( nth_group ( N ) ) NEW_LINE
Find if a molecule can be formed from 3 atoms using their valence numbers | Function to check if it is possible ; Driver code
def printPossible ( a , b , c ) : NEW_LINE INDENT if ( ( a + b + c ) % 2 != 0 or a + b < c ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 2 NEW_LINE b = 4 NEW_LINE c = 2 NEW_LINE printPossible ( a , b , c ) NEW_LINE DEDENT
Check if a number is a Trojan Number | Python 3 program to check if a number is Trojan Number or not ; Function to check if a number can be expressed as x ^ y ; Try all numbers from 2 to sqrt ( n ) as base ; Keep increasing y while power ' p ' is smaller than n . ; Function to check if a number is Strong ; count the number for each prime factor ; minimum number of prime divisors should be 2 ; Function to check if a number is Trojan Number ; Driver Code
from math import sqrt , pow NEW_LINE def isPerfectPower ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return True NEW_LINE DEDENT for x in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT y = 2 NEW_LINE p = pow ( x , y ) NEW_LINE while p <= n and p > 0 : NEW_LINE INDENT if p == n : NEW_LINE INDENT return True NEW_LINE DEDENT y += 1 NEW_LINE p = pow ( x , y ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def isStrongNumber ( n ) : NEW_LINE INDENT count = { i : 0 for i in range ( n ) } NEW_LINE while n % 2 == 0 : NEW_LINE INDENT n = n // 2 NEW_LINE count [ 2 ] += 1 NEW_LINE DEDENT for i in range ( 3 , int ( sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT while n % i == 0 : NEW_LINE INDENT n = n // i NEW_LINE count [ i ] += 1 NEW_LINE DEDENT DEDENT if n > 2 : NEW_LINE INDENT count [ n ] += 1 NEW_LINE DEDENT flag = 0 NEW_LINE for key , value in count . items ( ) : NEW_LINE INDENT if value == 1 : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if flag == 1 : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def isTrojan ( n ) : NEW_LINE INDENT return isPerfectPower ( n ) == False and isStrongNumber ( n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 108 NEW_LINE if ( isTrojan ( n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Find the sum of first N terms of the series 2 Γƒ β€” 3 + 4 Γƒ β€” 4 + 6 Γƒ β€” 5 + 8 Γƒ β€” 6 + ... | calculate sum upto N term of series ; Driver code
def Sum_upto_nth_Term ( n ) : NEW_LINE INDENT return n * ( n + 1 ) * ( 2 * n + 7 ) // 3 NEW_LINE DEDENT N = 5 NEW_LINE print ( Sum_upto_nth_Term ( N ) ) NEW_LINE
Absolute Difference between the Sum of Non | Python3 program to find the Absolute Difference between the Sum of Non - Prime numbers and Prime numbers of an Array ; Function to find the difference between the sum of non - primes and the sum of primes of an array . ; Find maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store the sum of primes in S1 and the sum of non primes in S2 ; the number is prime ; the number is non - prime ; Return the absolute difference ; Get the array ; Find the absolute difference
import sys NEW_LINE def CalculateDifference ( arr , n ) : NEW_LINE INDENT max_val = - 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] > max_val ) : NEW_LINE INDENT max_val = arr [ i ] NEW_LINE DEDENT DEDENT prime = [ True for i in range ( max_val + 1 ) ] NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while ( p * p <= max_val ) : NEW_LINE INDENT if prime [ p ] == True : NEW_LINE INDENT for i in range ( p * 2 , max_val + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT S1 = 0 NEW_LINE S2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if prime [ arr [ i ] ] : NEW_LINE INDENT S1 += arr [ i ] NEW_LINE DEDENT elif arr [ i ] != 1 : NEW_LINE INDENT S2 += arr [ i ] NEW_LINE DEDENT DEDENT return abs ( S2 - S1 ) NEW_LINE DEDENT arr = [ 1 , 3 , 5 , 10 , 15 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( CalculateDifference ( arr , n ) ) NEW_LINE
Program to find sum of 1 + x / 2 ! + x ^ 2 / 3 ! + ... + x ^ n / ( n + 1 ) ! | Function to compute the series sum ; To store the value of S [ i - 1 ] ; Iterate over n to store sum in total ; Update previous with S [ i ] ; Driver code ; Get x and n ; Find and prthe sum
def sum ( x , n ) : NEW_LINE INDENT total = 1.0 ; NEW_LINE previous = 1.0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT previous = ( previous * x ) / ( i + 1 ) ; NEW_LINE total = total + previous ; NEW_LINE DEDENT return total ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 5 ; NEW_LINE n = 4 ; NEW_LINE print ( " Sum ▁ is : ▁ " , sum ( x , n ) ) ; NEW_LINE DEDENT
Count number of integers less than or equal to N which has exactly 9 divisors | Function to count factors in O ( N ) ; iterate and check if factor or not ; Function to count numbers having exactly 9 divisors ; check for all numbers <= N ; check if exactly 9 factors or not ; Driver Code
def numberOfDivisors ( num ) : NEW_LINE INDENT c = 0 NEW_LINE for i in range ( 1 , num + 1 ) : NEW_LINE INDENT if ( num % i == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT return c NEW_LINE DEDENT def countNumbers ( n ) : NEW_LINE INDENT c = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( numberOfDivisors ( i ) == 9 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT return c NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 1000 NEW_LINE print ( countNumbers ( n ) ) NEW_LINE DEDENT
Number of distinct integers obtained by lcm ( X , N ) / X | Python 3 program to find distinct integers ontained by lcm ( x , num ) / x ; Function to count the number of distinct integers ontained by lcm ( x , num ) / x ; iterate to count the number of factors ; Driver Code
import math NEW_LINE def numberOfDistinct ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE if ( ( n // i ) != i ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE print ( numberOfDistinct ( n ) ) NEW_LINE DEDENT
Ulam Number Sequence | Python3 code to print nth Ulam number ; Array to store Ulam Number ; function to compute ulam Number ; push First 2 two term of the sequence in the array for further calculation ; loop to generate Ulam number ; traverse the array and check if i can be represented as sum of two distinct element of the array ; If count is 1 that means i can be represented as sum of two distinct terms of the sequence ; i is ulam number ; Driver code ; Pre compute Ulam Number sequence ; Print nth Ulam number
MAX = 1000 NEW_LINE arr = [ ] NEW_LINE def ulam ( ) : NEW_LINE INDENT arr . append ( 1 ) ; NEW_LINE arr . append ( 2 ) ; NEW_LINE for i in range ( 3 , MAX ) : NEW_LINE INDENT count = 0 ; NEW_LINE for j in range ( len ( arr ) - 1 ) : NEW_LINE INDENT for k in range ( j + 1 , len ( arr ) ) : NEW_LINE INDENT if ( arr [ j ] + arr [ k ] == i ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( count > 1 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT if ( count > 1 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT if ( count == 1 ) : NEW_LINE INDENT arr . append ( i ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ulam ( ) ; NEW_LINE n = 9 ; NEW_LINE print ( arr [ n - 1 ] ) NEW_LINE DEDENT
Find the number of rectangles of size 2 * 1 which can be placed inside a rectangle of size n * m | function to Find the number of rectangles of size 2 * 1 can be placed inside a rectangle of size n * m ; if n is even ; if m is even ; if both are odd ; Driver code ; function call
def NumberOfRectangles ( n , m ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return ( n / 2 ) * m NEW_LINE DEDENT elif ( m % 2 == 0 ) : NEW_LINE INDENT return ( m // 2 ) * n NEW_LINE DEDENT return ( n * m - 1 ) // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE m = 3 NEW_LINE print ( NumberOfRectangles ( n , m ) ) NEW_LINE DEDENT
Next greater Number than N with the same quantity of digits A and B | Recursive function to find the required number ; If the resulting number is >= n and count of a = count of b , return the number ; select minimum of two and call the function again ; Function to find the number next greater Number than N with the same quantity of digits A and B ; Driver code
def findNumUtil ( res , a , aCount , b , bCount , n ) : NEW_LINE INDENT if ( res > 1e11 ) : NEW_LINE INDENT return 1e11 NEW_LINE DEDENT if ( aCount == bCount and res >= n ) : NEW_LINE INDENT return res NEW_LINE DEDENT return min ( findNumUtil ( res * 10 + a , a , aCount + 1 , b , bCount , n ) , findNumUtil ( res * 10 + b , a , aCount , b , bCount + 1 , n ) ) NEW_LINE DEDENT def findNum ( n , a , b ) : NEW_LINE INDENT result = 0 NEW_LINE aCount = 0 NEW_LINE bCount = 0 NEW_LINE return findNumUtil ( result , a , aCount , b , bCount , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4500 NEW_LINE A = 4 NEW_LINE B = 7 NEW_LINE print ( findNum ( N , A , B ) ) NEW_LINE DEDENT
Minimum and maximum number of N chocolates after distribution among K students | Driver code
n , k = 7 , 3 NEW_LINE if ( n % k == 0 ) : NEW_LINE INDENT print ( n // k , n // k ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ( n - n % k ) // k , ( n - n % k ) // k + 1 ) NEW_LINE DEDENT
Total money to be paid after traveling the given number of hours | Python3 implementation of the above approach ; calculating hours travelled
import math as ma NEW_LINE m , n , x , h = 50 , 5 , 67 , 2927 NEW_LINE z = int ( ma . ceil ( h / 60 ) ) NEW_LINE if ( z <= n ) : NEW_LINE INDENT print ( z * m ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( n * m + ( z - n ) * x ) NEW_LINE DEDENT
Absolute difference between sum and product of roots of a quartic equation | Function taking coefficient of each term of equation as input ; Finding sum of roots ; Finding product of roots ; Absolute difference ; Driver Code
def sumProductDifference ( a , b , c , d , e ) : NEW_LINE INDENT rootSum = ( - 1 * b ) / a NEW_LINE rootProduct = e / a NEW_LINE return abs ( rootSum - rootProduct ) NEW_LINE DEDENT print ( sumProductDifference ( 8 , 4 , 6 , 4 , 1 ) ) NEW_LINE
Number of solutions of n = x + n Γ’Ε  β€’ x | Function to find the number of solutions of n = n xor x ; Counter to store the number of solutions found ; Driver code
def numberOfSolutions ( n ) : NEW_LINE INDENT c = 0 NEW_LINE for x in range ( n + 1 ) : NEW_LINE INDENT if ( n == ( x + ( n ^ x ) ) ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT return c NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE print ( numberOfSolutions ( n ) ) NEW_LINE DEDENT
Program to find minimum number of lectures to attend to maintain 75 % | Python Program to find minimum number of lectures to attend to maintain 75 % attendance ; Function to compute minimum lecture ; Formula to compute ; Driver Code
import math NEW_LINE def minimumLecture ( m , n ) : NEW_LINE INDENT ans = 0 NEW_LINE if ( n < math . ceil ( 0.75 * m ) ) : NEW_LINE INDENT ans = math . ceil ( ( ( 0.75 * m ) - n ) / 0.25 ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = 0 NEW_LINE DEDENT return ans NEW_LINE DEDENT M = 9 NEW_LINE N = 1 NEW_LINE print ( minimumLecture ( M , N ) ) NEW_LINE