text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
N | ; function to find Nth polite number ; Driver code
import math NEW_LINE def Polite ( n ) : NEW_LINE INDENT n = n + 1 NEW_LINE return ( int ) ( n + ( math . log ( ( n + math . log ( n , 2 ) ) , 2 ) ) ) NEW_LINE DEDENT n = 7 NEW_LINE print Polite ( n ) NEW_LINE
Find the number of stair steps | Modified Binary search function to solve the equation ; if mid is solution to equation ; if our solution to equation lies between mid and mid - 1 ; if solution to equation is greater than mid ; if solution to equation is less than mid ; driver code ; call binary search method to solve f...
def solve ( low , high , T ) : NEW_LINE INDENT while low <= high : NEW_LINE INDENT mid = int ( ( low + high ) / 2 ) NEW_LINE if ( mid * ( mid + 1 ) ) == T : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( mid > 0 and ( mid * ( mid + 1 ) ) > T and ( mid * ( mid - 1 ) ) <= T ) : NEW_LINE INDENT return mid - 1 NEW_LINE DE...
Check for integer overflow on multiplication | Function to check whether there is overflow in a * b or not . It returns true if there is overflow . ; Check if either of them is zero ; Driver code
def isOverflow ( a , b ) : NEW_LINE INDENT if ( a == 0 or b == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT result = a * b NEW_LINE if ( result >= 9223372036854775807 or result <= - 9223372036854775808 ) : NEW_LINE INDENT result = 0 NEW_LINE DEDENT if ( a == ( result // b ) ) : NEW_LINE INDENT print ( result // b...
Sum of first n odd numbers in O ( 1 ) Complexity | Python3 program to find sum of first n odd numbers ; Returns the sum of first n odd numbers ; Driver Code
def oddSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE curr = 1 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT sum = sum + curr NEW_LINE curr = curr + 2 NEW_LINE i = i + 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 20 NEW_LINE print ( " ▁ Sum ▁ of ▁ first " , n , " Odd ▁ Numbers ▁ is : ▁ " , oddSum ( n ) ) NEW_...
Sum of first n odd numbers in O ( 1 ) Complexity | Returns the sum of first n odd numbers ; Driver Code
def oddSum ( n ) : NEW_LINE INDENT return ( n * n ) ; NEW_LINE DEDENT n = 20 NEW_LINE print ( " ▁ Sum ▁ of ▁ first " , n , " Odd ▁ Numbers ▁ is : ▁ " , oddSum ( n ) ) NEW_LINE
K | Returns the sum of first n odd numbers ; Count prime factors of all numbers till B . ; Print all numbers with k prime factors ; Driver code
def printKPFNums ( A , B , K ) : NEW_LINE INDENT prime = [ True ] * ( B + 1 ) NEW_LINE p_factors = [ 0 ] * ( B + 1 ) NEW_LINE for p in range ( 2 , B + 1 ) : NEW_LINE INDENT if ( p_factors [ p ] == 0 ) : NEW_LINE INDENT for i in range ( p , B + 1 , p ) : NEW_LINE INDENT p_factors [ i ] = p_factors [ i ] + 1 NEW_LINE DED...
Queries for maximum difference between prime numbers in given ranges | Python 3 program to find maximum differences between two prime numbers in given ranges ; Precompute Sieve , Prefix array , Suffix array ; Sieve of Eratosthenes ; Precomputing Prefix array . ; Precompute Suffix array . ; Function to solve each query ...
from math import sqrt NEW_LINE MAX = 100005 NEW_LINE def precompute ( prefix , suffix ) : NEW_LINE INDENT prime = [ True for i in range ( MAX ) ] NEW_LINE k = int ( sqrt ( MAX ) ) NEW_LINE for i in range ( 2 , k , 1 ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , MAX , i ) : NEW_LINE I...
Sum of the Series 1 + x / 1 + x ^ 2 / 2 + x ^ 3 / 3 + . . + x ^ n / n | Function to print the sum of the series ; Driver Code
def SUM ( x , n ) : NEW_LINE INDENT total = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT total = total + ( ( x ** i ) / i ) NEW_LINE DEDENT return total NEW_LINE DEDENT x = 2 NEW_LINE n = 5 NEW_LINE s = SUM ( x , n ) NEW_LINE print ( round ( s , 2 ) ) NEW_LINE
Find if a number is part of AP whose first element and difference are given | '' returns yes if exist else no. ; If difference is 0 , then x must be same as a . ; Else difference between x and a must be divisible by d . ; Driver code
def isMember ( a , d , x ) : NEW_LINE INDENT if d == 0 : NEW_LINE INDENT return x == a NEW_LINE DEDENT return ( ( x - a ) % d == 0 and int ( ( x - a ) / d ) >= 0 ) NEW_LINE DEDENT a = 1 NEW_LINE x = 7 NEW_LINE d = 3 NEW_LINE if isMember ( a , d , x ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE I...
Number of GP ( Geometric Progression ) subsequences of size 3 | Python3 program to count GP subsequences of size 3. ; To calculate nCr DP approach ; nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Returns count of G . P . subsequences with length 3 and common ratio r ; hashing to maintain left a...
from collections import defaultdict NEW_LINE def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ 0 ] * ( k + 1 ) NEW_LINE C [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) , - 1 , - 1 ) : NEW_LINE C [ j ] = C [ j ] + C [ j - 1 ] NEW_LINE DEDENT return C [ k ] NEW_LINE DE...
Check whether a number can be represented by sum of two squares | function to check if there exist two numbers sum of whose squares is n . ; driver Program
def sumSquare ( n ) : NEW_LINE INDENT i = 1 NEW_LINE while i * i <= n : NEW_LINE INDENT j = 1 NEW_LINE while ( j * j <= n ) : NEW_LINE INDENT if ( i * i + j * j == n ) : NEW_LINE INDENT print ( i , " ^ 2 ▁ + ▁ " , j , " ^ 2" ) NEW_LINE return True NEW_LINE DEDENT j = j + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT retu...
Queries to count minimum flips required to fill a binary submatrix with 0 s only | Python3 program for the above approach ; Function to compute the matrix prefixCnt [ M ] [ N ] from mat [ M ] [ N ] such that prefixCnt [ i ] [ j ] stores the count of 0 's from (0, 0) to (i, j) ; Initialize prefixCnt [ i ] [ j ] with 1 i...
M = 6 NEW_LINE N = 7 NEW_LINE def preCompute ( mat , prefixCnt ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 0 ) : NEW_LINE INDENT prefixCnt [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT prefixCnt [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT...
Smallest root of the equation x ^ 2 + s ( x ) * x | Python3 program to find smallest value of root of an equation under given constraints . ; function to check if the sum of digits is equal to the summation assumed ; calculate the sum of digit ; function to find the largest root possible . ; iterate for all possible su...
import math NEW_LINE def check ( a , b ) : NEW_LINE INDENT c = 0 ; NEW_LINE while ( a != 0 ) : NEW_LINE INDENT c = c + a % 10 ; NEW_LINE a = int ( a / 10 ) ; NEW_LINE DEDENT return True if ( c == b ) else False ; NEW_LINE DEDENT def root ( n ) : NEW_LINE INDENT found = False ; NEW_LINE mx = 1000000000000000001 ; NEW_LI...
Sum of digits of a given number to a given power | Function to calculate sum ; Driver Code
def calculate ( n , power ) : NEW_LINE INDENT return sum ( [ int ( i ) for i in str ( pow ( n , power ) ) ] ) NEW_LINE DEDENT n = 5 NEW_LINE power = 4 NEW_LINE print ( calculate ( n , power ) ) NEW_LINE
Co | Python3 program to represent a number as sum of a co - prime pair such that difference between them is minimum ; function to check if pair is co - prime or not ; function to find and print co - prime pair ; Driver code
import math NEW_LINE def coprime ( a , b ) : NEW_LINE INDENT return 1 if ( math . gcd ( a , b ) == 1 ) else 0 ; NEW_LINE DEDENT def pairSum ( n ) : NEW_LINE INDENT mid = int ( n / 2 ) ; NEW_LINE i = mid ; NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT if ( coprime ( i , n - i ) == 1 ) : NEW_LINE INDENT print ( i , n - i )...
Program for quotient and remainder of big number | Function to calculate the modulus ; Store the modulus of big number ; Do step by step division ; Update modulo by concatenating current digit . ; Update quotient ; Update mod for next iteration . ; Flag used to remove starting zeros ; Driver Code
def modBigNumber ( num , m ) : NEW_LINE INDENT vec = [ ] NEW_LINE mod = 0 NEW_LINE for i in range ( 0 , len ( num ) , 1 ) : NEW_LINE INDENT digit = ord ( num [ i ] ) - ord ( '0' ) NEW_LINE mod = mod * 10 + digit NEW_LINE quo = int ( mod / m ) NEW_LINE vec . append ( quo ) NEW_LINE mod = mod % m NEW_LINE DEDENT print ( ...
Queries to find whether a number has exactly four distinct factors or not | Initialize global variable according to given condition so that it can be accessible to all function ; Function to calculate all number having four distinct factors ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as...
N = 1000001 ; NEW_LINE fourDiv = [ False ] * ( N + 1 ) ; NEW_LINE def fourDistinctFactors ( ) : NEW_LINE INDENT primeAll = [ True ] * ( N + 1 ) ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= N ) : NEW_LINE INDENT if ( primeAll [ p ] == True ) : NEW_LINE INDENT i = p * 2 ; NEW_LINE while ( i <= N ) : NEW_LINE INDENT prime...
Leonardo Number | A simple recursive program to find n - th leonardo number . ; Driver code
def leonardo ( n ) : NEW_LINE INDENT dp = [ ] ; NEW_LINE dp . append ( 1 ) ; NEW_LINE dp . append ( 1 ) ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp . append ( dp [ i - 1 ] + dp [ i - 2 ] + 1 ) ; NEW_LINE DEDENT return dp [ n ] ; NEW_LINE DEDENT print ( leonardo ( 3 ) ) ; NEW_LINE
Cholesky Decomposition : Matrix Decomposition | Python3 program to decompose a matrix using Cholesky Decomposition ; Decomposing a matrix into Lower Triangular ; summation for diagonals ; Evaluating L ( i , j ) using L ( j , j ) ; Displaying Lower Triangular and its Transpose ; Lower Triangular ; Transpose of Lower Tri...
import math NEW_LINE MAX = 100 ; NEW_LINE def Cholesky_Decomposition ( matrix , n ) : NEW_LINE INDENT lower = [ [ 0 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT sum1 = 0 ; NEW_LINE if ( j == i ) : NEW_LINE INDENT for k...
Program for sum of arithmetic series | Python3 Efficient solution to find sum of arithmetic series . ; Driver code
def sumOfAP ( a , d , n ) : NEW_LINE INDENT sum = ( n / 2 ) * ( 2 * a + ( n - 1 ) * d ) NEW_LINE return sum NEW_LINE DEDENT n = 20 NEW_LINE a = 2.5 NEW_LINE d = 1.5 NEW_LINE print ( sumOfAP ( a , d , n ) ) NEW_LINE
Program for cube sum of first n natural numbers | Returns the sum of series ; Driver Function
def sumOfSeries ( n ) : NEW_LINE INDENT x = 0 NEW_LINE if n % 2 == 0 : NEW_LINE INDENT x = ( n / 2 ) * ( n + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT x = ( ( n + 1 ) / 2 ) * n NEW_LINE DEDENT return ( int ) ( x * x ) NEW_LINE DEDENT n = 5 NEW_LINE print ( sumOfSeries ( n ) ) NEW_LINE
Maximum value of | arr [ i ] | Return maximum value of | arr [ i ] - arr [ j ] | + | i - j | ; Iterating two for loop , one for i and another for j . ; Evaluating | arr [ i ] - arr [ j ] | + | i - j | and compare with previous maximum . ; Driver Code
def findValue ( arr , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT ans = ans if ans > ( abs ( arr [ i ] - arr [ j ] ) + abs ( i - j ) ) else ( abs ( arr [ i ] - arr [ j ] ) + abs ( i - j ) ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT a...
Maximum value of | arr [ i ] | Return maximum | arr [ i ] - arr [ j ] | + | i - j | ; Calculating first_array and second_array ; Finding maximum and minimum value in first_array ; Storing the difference between maximum and minimum value in first_array ; Finding maximum and minimum value in second_array ; Storing the di...
def findValue ( arr , n ) : NEW_LINE INDENT a = [ ] NEW_LINE b = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT a . append ( arr [ i ] + i ) NEW_LINE b . append ( arr [ i ] - i ) NEW_LINE DEDENT x = a [ 0 ] NEW_LINE y = a [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > x ) : NEW_LINE INDENT x ...
Number of subarrays having product less than K | Python3 program to count subarrays having product less than k . ; Counter for single element ; Multiple subarray ; If this multiple is less than k , then increment ; Driver Code
def countsubarray ( array , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if array [ i ] < k : NEW_LINE INDENT count += 1 NEW_LINE DEDENT mul = array [ i ] NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT mul = mul * array [ j ] NEW_LINE if mul < k : NEW_LINE INDENT coun...
Perfect Cube factors of a Number | Function that returns the count of factors that are perfect cube ; To store the count of number of times a prime number divides N ; To store the count of factors that are perfect cube ; Count number of 2 's that divides N ; Calculate ans according to above formula ; Check for all poss...
def noofFactors ( N ) : NEW_LINE INDENT if N == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT count = 0 NEW_LINE ans = 1 NEW_LINE while ( N % 2 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE N //= 2 NEW_LINE DEDENT ans *= ( ( count // 3 ) + 1 ) NEW_LINE i = 3 NEW_LINE while ( ( i * i ) <= N ) : NEW_LINE INDENT count = 0 N...
Efficient program to print the number of factors of n numbers | Python3 program to count number of factors of an array of integers ; function to generate all prime factors of numbers from 1 to 10 ^ 6 ; Initializes all the positions with their value . ; Initializes all multiples of 2 with 2 ; A modified version of Sieve...
MAX = 1000001 ; NEW_LINE factor = [ 0 ] * ( MAX + 1 ) ; NEW_LINE def generatePrimeFactors ( ) : NEW_LINE INDENT factor [ 1 ] = 1 ; NEW_LINE for i in range ( 2 , MAX ) : NEW_LINE INDENT factor [ i ] = i ; NEW_LINE DEDENT for i in range ( 4 , MAX , 2 ) : NEW_LINE INDENT factor [ i ] = 2 ; NEW_LINE DEDENT i = 3 ; NEW_LINE...
Digit | function to produce and print Digit Product Sequence ; Array which store sequence ; Temporary variable to store product ; Initialize first element of the array with 1 ; Run a loop from 1 to N . Check if previous number is single digit or not . If yes then product = 1 else take modulus . Then again check if prev...
def digit_product_Sum ( N ) : NEW_LINE INDENT a = [ 0 ] * ( N + 1 ) ; NEW_LINE product = 1 ; NEW_LINE a [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT product = int ( a [ i - 1 ] / 10 ) ; NEW_LINE if ( product == 0 ) : NEW_LINE INDENT product = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT product = a...
Geometric mean ( Two Methods ) | Python Program to calculate the geometric mean of the given array elements . ; function to calculate geometric mean and return float value . ; declare product variable and initialize it to 1. ; Compute the product of all the elements in the array . ; compute geometric mean through formu...
import math NEW_LINE def geometricMean ( arr , n ) : NEW_LINE INDENT product = 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT product = product * arr [ i ] NEW_LINE DEDENT gm = ( float ) ( math . pow ( product , ( 1 / n ) ) ) NEW_LINE return ( float ) ( gm ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ...
Check whether a number can be expressed as a product of single digit numbers | Number of single digit prime numbers ; function to check whether a number can be expressed as a product of single digit numbers ; if ' n ' is a single digit number , then it can be expressed ; define single digit prime numbers array ; repeat...
SIZE = 4 NEW_LINE def productOfSingelDgt ( n ) : NEW_LINE INDENT if n >= 0 and n <= 9 : NEW_LINE INDENT return True NEW_LINE DEDENT prime = [ 2 , 3 , 5 , 7 ] NEW_LINE i = 0 NEW_LINE while i < SIZE and n > 1 : NEW_LINE INDENT while n % prime [ i ] == 0 : NEW_LINE INDENT n = n / prime [ i ] NEW_LINE DEDENT i += 1 NEW_LIN...
Program to find sum of first n natural numbers | Returns sum of first n natural numbers ; Driver code
def findSum ( n ) : NEW_LINE INDENT return n * ( n + 1 ) / 2 NEW_LINE DEDENT n = 5 NEW_LINE print findSum ( n ) NEW_LINE
Program to find sum of first n natural numbers | Returns sum of first n natural numbers ; If n is odd , ( n + 1 ) must be even ; Driver code
def findSum ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return ( n / 2 ) * ( n + 1 ) NEW_LINE DEDENT else : NEW_LINE return ( ( n + 1 ) / 2 ) * n NEW_LINE DEDENT n = 5 NEW_LINE print findSum ( n ) NEW_LINE
Maximum number of unique prime factors | Return maximum number of prime factors for any number in [ 1 , N ] ; Based on Sieve of Eratosthenes ; If p is prime ; We simply multiply first set of prime numbers while the product is smaller than N . ; Driver Code
def maxPrimefactorNum ( N ) : NEW_LINE INDENT if ( N < 2 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT arr = [ True ] * ( N + 1 ) ; NEW_LINE prod = 1 ; NEW_LINE res = 0 ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= N ) : NEW_LINE INDENT if ( arr [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , N + 1 , p ) : N...
To check a number is palindrome or not without using any extra space | Function to check if given number is palindrome or not without using the extra space ; Find the appropriate divisor to extract the leading digit ; If first and last digit not same return false ; Removing the leading and trailing digit from number ; ...
def isPalindrome ( n ) : NEW_LINE INDENT divisor = 1 NEW_LINE while ( n / divisor >= 10 ) : NEW_LINE INDENT divisor *= 10 NEW_LINE DEDENT while ( n != 0 ) : NEW_LINE INDENT leading = n // divisor NEW_LINE trailing = n % 10 NEW_LINE if ( leading != trailing ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = ( n % divi...
Find whether a given integer is a power of 3 or not | Returns true if n is power of 3 , else false ; The maximum power of 3 value that integer can hold is 1162261467 ( 3 ^ 19 ) . ; Driver code
def check ( n ) : NEW_LINE INDENT return 1162261467 % n == 0 NEW_LINE DEDENT n = 9 NEW_LINE if ( check ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Demlo number ( Square of 11. . .1 ) | To return demlo number Length of s is smaller than 10 ; Add numbers to res upto size of s then add in reverse ; Driver Code
def printDemlo ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE res = " " NEW_LINE for i in range ( 1 , l + 1 ) : NEW_LINE INDENT res = res + str ( i ) NEW_LINE DEDENT for i in range ( l - 1 , 0 , - 1 ) : NEW_LINE INDENT res = res + str ( i ) NEW_LINE DEDENT return res NEW_LINE DEDENT s = "111111" NEW_LINE print printDem...
Number of times a number can be replaced by the sum of its digits until it only contains one digit | Python 3 program to count number of times we need to add digits to get a single digit . ; Here the count variable store how many times we do sum of digits and temporary_sum always store the temporary sum we get at each ...
def NumberofTimes ( s ) : NEW_LINE INDENT temporary_sum = 0 NEW_LINE count = 0 NEW_LINE while ( len ( s ) > 1 ) : NEW_LINE INDENT temporary_sum = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT temporary_sum += ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT s = str ( temporary_sum ) NEW_LINE count += 1 NEW...
Climb n | Function to calculate leaps ; Driver code
def calculateLeaps ( n ) : NEW_LINE INDENT if n == 0 or n == 1 : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT leaps = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT leaps = leaps + calculateLeaps ( i ) ; NEW_LINE DEDENT return leaps ; NEW_LINE DEDENT DEDENT print ( calculateLeaps ( 4 ) ) ;...
Print last k digits of a ^ b ( a raised to power b ) | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; x = x % p Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; function to calculate number of digits in x ; f...
def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE 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 numberOfDigits ( x ) : NEW_LINE INDENT i = 0 NEW_LINE while ( x ) : NEW_LINE INDENT x //= 10 ...
Adam Number | To reverse Digits of numbers ; To square number ; To check Adam Number ; Square first number and square reverse digits of second number ; If reverse of b equals a then given number is Adam number ; Driver program to test above functions
def reverseDigits ( num ) : NEW_LINE INDENT rev = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT rev = rev * 10 + num % 10 NEW_LINE num /= 10 NEW_LINE DEDENT return rev NEW_LINE DEDENT def square ( num ) : NEW_LINE INDENT return ( num * num ) NEW_LINE DEDENT def checkAdamNumber ( num ) : NEW_LINE INDENT a = square ( nu...
Compute the parity of a number using XOR and table look | Generating the look - up table while pre - processing ; LOOK_UP is the macro expansion to generate the table ; Function to find the parity ; Number is considered to be of 32 bits ; Dividing the number o 8 - bit chunks while performing X - OR ; Masking the number...
def P2 ( n , table ) : NEW_LINE INDENT table . extend ( [ n , n ^ 1 , n ^ 1 , n ] ) NEW_LINE DEDENT def P4 ( n , table ) : NEW_LINE INDENT return ( P2 ( n , table ) , P2 ( n ^ 1 , table ) , P2 ( n ^ 1 , table ) , P2 ( n , table ) ) NEW_LINE DEDENT def P6 ( n , table ) : NEW_LINE INDENT return ( P4 ( n , table ) , P4 ( ...
Count total number of digits from 1 to n | Python3 program to count total number of digits we have to write from 1 to n ; number_of_digits store total digits we have to write ; In the loop we are decreasing 0 , 9 , 99 ... from n till ( n - i + 1 ) is greater than 0 and sum them to number_of_digits to get the required s...
def totalDigits ( n ) : NEW_LINE INDENT number_of_digits = 0 ; NEW_LINE for i in range ( 1 , n , 10 ) : NEW_LINE INDENT number_of_digits = ( number_of_digits + ( n - i + 1 ) ) ; NEW_LINE DEDENT return number_of_digits ; NEW_LINE DEDENT n = 13 ; NEW_LINE s = totalDigits ( n ) + 1 ; NEW_LINE print ( s ) ; NEW_LINE
Numbers with exactly 3 divisors | Generates all primes upto n and prints their squares ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; print squares of primes upto n . ; Driver program
def numbersWith3Divisors ( n ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) ; NEW_LINE prime [ 0 ] = prime [ 1 ] = False ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE...
Program for decimal to hexadecimal conversion | function to convert decimal to hexadecimal ; char array to store hexadecimal number ; counter for hexadecimal number array ; temporary variable to store remainder ; storing remainder in temp variable . ; check if temp < 10 ; printing hexadecimal number array in reverse or...
def decToHexa ( n ) : NEW_LINE INDENT hexaDeciNum = [ '0' ] * 100 NEW_LINE i = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT temp = 0 NEW_LINE temp = n % 16 NEW_LINE if ( temp < 10 ) : NEW_LINE INDENT hexaDeciNum [ i ] = chr ( temp + 48 ) NEW_LINE i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT hexaDeciNum [ i ] = chr...
Program for Decimal to Binary Conversion | function to convert decimal to binary ; array to store binary number ; counter for binary array ; storing remainder in binary array ; printing binary array in reverse order ; Driver Code
def decToBinary ( n ) : NEW_LINE INDENT binaryNum = [ 0 ] * n ; NEW_LINE i = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT binaryNum [ i ] = n % 2 ; NEW_LINE n = int ( n / 2 ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( binaryNum [ j ] , end = " " ) ; NEW_LINE DED...
Break the number into three parts | Function to count number of ways to make the given number n ; Driver code
def count_of_ways ( n ) : NEW_LINE INDENT count = 0 NEW_LINE count = ( n + 1 ) * ( n + 2 ) // 2 NEW_LINE return count NEW_LINE DEDENT n = 3 NEW_LINE print ( count_of_ways ( n ) ) NEW_LINE
Implement * , | Function to flip the sign using only " + " operator ( It is simple with ' * ' allowed . We need to do a = ( - 1 ) * a ; If sign is + ve turn it - ve and vice - versa ; Check if a and b are of different signs ; Function to subtract two numbers by negating b and adding them ; Negating b ; Function to mult...
def flipSign ( a ) : NEW_LINE INDENT neg = 0 ; NEW_LINE tmp = 1 if a < 0 else - 1 ; NEW_LINE while ( a != 0 ) : NEW_LINE INDENT neg += tmp ; NEW_LINE a += tmp ; NEW_LINE DEDENT return neg ; NEW_LINE DEDENT def areDifferentSign ( a , b ) : NEW_LINE INDENT return ( ( a < 0 and b > 0 ) or ( a > 0 and b < 0 ) ) ; NEW_LINE ...
Number of Groups of Sizes Two Or Three Divisible By 3 | Program to find groups of 2 or 3 whose sum is divisible by 3 ; Initialize groups to 0 ; Increment group with specified remainder ; Return groups using the formula ; Driver code
def numOfCombinations ( arr , N ) : NEW_LINE INDENT C = [ 0 , 0 , 0 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT C [ arr [ i ] % 3 ] = C [ arr [ i ] % 3 ] + 1 NEW_LINE DEDENT return ( C [ 1 ] * C [ 2 ] + C [ 0 ] * ( C [ 0 ] - 1 ) / 2 + C [ 0 ] * ( C [ 0 ] - 1 ) * ( C [ 0 ] - 2 ) / 6 + C [ 1 ] * ( C [ 1 ] - 1 ) * (...
Check if a number can be written as a sum of ' k ' prime numbers | Checking if a number is prime or not ; check for numbers from 2 to sqrt ( x ) if it is divisible return false ; Returns true if N can be written as sum of K primes ; N < 2 K directly return false ; If K = 1 return value depends on primality of N ; if N ...
def isprime ( x ) : NEW_LINE INDENT i = 2 NEW_LINE while ( i * i <= x ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def isSumOfKprimes ( N , K ) : NEW_LINE INDENT if ( N < 2 * K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( K == 1 ) ...
Count total divisors of A or B in a given range | Utility function to find GCD of two numbers ; Utility function to find LCM of two numbers ; Function to calculate all divisors in given range ; Find LCM of a and b ; Find common divisor by using LCM ; Driver code
def __gcd ( x , y ) : NEW_LINE INDENT if x > y : NEW_LINE INDENT small = y NEW_LINE DEDENT else : NEW_LINE INDENT small = x NEW_LINE DEDENT for i in range ( 1 , small + 1 ) : NEW_LINE INDENT if ( ( x % i == 0 ) and ( y % i == 0 ) ) : NEW_LINE INDENT gcd = i NEW_LINE DEDENT DEDENT return gcd NEW_LINE DEDENT def FindLCM ...
Numbers having Unique ( or Distinct ) digits | Function to print unique digit numbers in range from l to r . ; Start traversing the numbers ; Find digits and maintain its hash ; if a digit occurs more than 1 time then break ; num will be 0 only when above loop doesn 't get break that means the number is unique so pr...
def printUnique ( l , r ) : NEW_LINE INDENT for i in range ( l , r + 1 ) : NEW_LINE INDENT num = i ; NEW_LINE visited = [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] ; NEW_LINE while ( num ) : NEW_LINE INDENT if visited [ num % 10 ] == 1 : NEW_LINE INDENT break ; NEW_LINE DEDENT visited [ num % 10 ] = 1 ; NEW_LINE num = ( ...
Fibonacci modulo p | Returns position of first Fibonacci number whose modulo p is 0. ; add previous two remainders and then take its modulo p . ; Driver code
def findMinZero ( p ) : NEW_LINE INDENT first = 1 NEW_LINE second = 1 NEW_LINE number = 2 NEW_LINE next = 1 NEW_LINE while ( next ) : NEW_LINE INDENT next = ( first + second ) % p NEW_LINE first = second NEW_LINE second = next NEW_LINE number = number + 1 NEW_LINE DEDENT return number NEW_LINE DEDENT if __name__ == ' _...
Perfect cubes in a range | A Simple Method to count cubes between a and b ; Traverse through all numbers in given range and one by one check if number is prime ; Check if current number ' i ' is perfect cube ; Driver code
def printCubes ( a , b ) : NEW_LINE INDENT for i in range ( a , b + 1 ) : NEW_LINE INDENT j = 1 NEW_LINE for j in range ( j ** 3 , i + 1 ) : NEW_LINE INDENT if ( j ** 3 == i ) : NEW_LINE INDENT print ( j ** 3 , end = " ▁ " ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT a = 1 ; b = 100 NEW_LINE print ( " Perfect ...
Converting a Real Number ( between 0 and 1 ) to Binary String | Function to convert Binary real number to String ; Check if the number is Between 0 to 1 or Not ; Setting a limit on length : 32 characters . ; compare the number to .5 ; Now it become 0.25 ; Input value
def toBinary ( n ) : NEW_LINE INDENT if ( n >= 1 or n <= 0 ) : NEW_LINE INDENT return " ERROR " ; NEW_LINE DEDENT frac = 0.5 ; NEW_LINE answer = " . " ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( len ( answer ) >= 32 ) : NEW_LINE INDENT return " ERROR " ; NEW_LINE DEDENT if ( n >= frac ) : NEW_LINE INDENT answer +...
Given a number n , find the first k digits of n ^ n | function that manually calculates n ^ n and then removes digits until k digits remain ; loop will terminate when there are only k digits left ; Driver Code
def firstkdigits ( n , k ) : NEW_LINE INDENT product = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT product *= n NEW_LINE DEDENT while ( ( product // pow ( 10 , k ) ) != 0 ) : NEW_LINE INDENT product = product // 10 NEW_LINE DEDENT return product NEW_LINE DEDENT n = 15 NEW_LINE k = 4 NEW_LINE print ( firstkdigits ...
Check if a large number is divisible by 9 or not | Function to find that number divisible by 9 or not ; Compute sum of digits ; Check if sum of digits is divisible by 9. ; Driver code
def check ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE digitSum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT digitSum = digitSum + ( int ) ( st [ i ] ) NEW_LINE DEDENT return ( digitSum % 9 == 0 ) NEW_LINE DEDENT st = "99333" NEW_LINE if ( check ( st ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDEN...
XOR of all subarray XORs | Set 1 | Returns XOR of all subarray xors ; initialize result by 0 as ( a xor 0 = a ) ; select the starting element ; select the eNding element ; Do XOR of elements in current subarray ; Driver code to test above methods
def getTotalXorOfSubarrayXors ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i , N ) : NEW_LINE INDENT for k in range ( i , j + 1 ) : NEW_LINE INDENT res = res ^ arr [ k ] NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 3 , 5 , 2 , 4 , 6 ] NEW...
XOR of all subarray XORs | Set 1 | Returns XOR of all subarray xors ; initialize result by 0 as ( a XOR 0 = a ) ; loop over all elements once ; get the frequency of current element ; if frequency is odd , then include it in the result ; return the result ; Driver Code
def getTotalXorOfSubarrayXors ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT freq = ( i + 1 ) * ( N - i ) NEW_LINE if ( freq % 2 == 1 ) : NEW_LINE INDENT res = res ^ arr [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 3 , 5 , 2 , 4 , 6 ] NEW_LINE N = len ( arr ...
Refactorable number | Function to count all divisors ; Initialize result ; If divisors are equal , count only one ; else : Otherwise count both ; Driver Code
import math NEW_LINE def isRefactorableNumber ( n ) : NEW_LINE INDENT divCount = 0 NEW_LINE for i in range ( 1 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT if n / i == i : NEW_LINE INDENT divCount += 1 NEW_LINE divCount += 2 NEW_LINE DEDENT DEDENT DEDENT return n % divCount == 0 N...
Count all perfect divisors of a number | Python3 implementation of Naive method to count all perfect divisors ; Utility function to check perfect square number ; function to count all perfect divisors ; Initialize result ; Consider every number that can be a divisor of n ; If i is a divisor ; Driver program to test abo...
import math NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sq = ( int ) ( math . sqrt ( x ) ) NEW_LINE return ( x == sq * sq ) NEW_LINE DEDENT def countPerfectDivisors ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( 1 , ( int ) ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE I...
Nearest element with at | Python 3 program to print nearest element with at least one common prime factor . ; Loop covers the every element of arr [ ] ; Loop that covers from 0 to i - 1 and i + 1 to n - 1 indexes simultaneously ; print position of closest element ; Driver code
import math NEW_LINE def nearestGcd ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT closest = - 1 NEW_LINE j = i - 1 NEW_LINE k = i + 1 NEW_LINE while j > 0 or k <= n : NEW_LINE INDENT if ( j >= 0 and math . gcd ( arr [ i ] , arr [ j ] ) > 1 ) : NEW_LINE INDENT closest = j + 1 NEW_LINE break NEW_LI...
Largest subsequence having GCD greater than 1 | Efficient Python3 program to find length of the largest subsequence with GCD greater than 1. ; prime [ ] for storing smallest prime divisor of element count [ ] for storing the number of times a particular divisor occurs in a subsequence ; Simple sieve to find smallest pr...
import math as mt NEW_LINE MAX = 100001 NEW_LINE prime = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE countdiv = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT for i in range ( 2 , mt . ceil ( mt . sqrt ( MAX + 1 ) ) ) : NEW_LINE INDENT if ( prime [ i ] == 0 ) : NEW_LINE INDENT for...
Count of Binary Digit numbers smaller than N | Python3 program to count all binary digit numbers smaller than N ; method returns count of binary digit numbers smaller than N ; queue to store all intermediate binary digit numbers ; binary digits start with 1 ; loop until we have element in queue ; push next binary digit...
from collections import deque NEW_LINE def countOfBinaryNumberLessThanN ( N ) : NEW_LINE INDENT q = deque ( ) NEW_LINE q . append ( 1 ) NEW_LINE cnt = 0 NEW_LINE while ( q ) : NEW_LINE INDENT t = q . popleft ( ) NEW_LINE if ( t <= N ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE q . append ( t * 10 ) NEW_LINE q . append ( ...
Sum of product of x and y such that floor ( n / x ) = y | Return the sum of product x * y ; Iterating x from 1 to n ; Finding y = n / x . ; Adding product of x and y to answer . ; Driven Program
def sumofproduct ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for x in range ( 1 , n + 1 ) : NEW_LINE INDENT y = int ( n / x ) NEW_LINE ans += ( y * x ) NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 10 NEW_LINE print ( sumofproduct ( n ) ) NEW_LINE
Find the first natural number whose factorial is divisible by x | function for calculating factorial ; function for check Special_Factorial_Number ; call fact function and the Modulo with k and check if condition is TRUE then return i ; Driver Code ; taking input
def fact ( n ) : NEW_LINE INDENT num = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT num = num * i NEW_LINE DEDENT return num NEW_LINE DEDENT def Special_Factorial_Number ( k ) : NEW_LINE INDENT for i in range ( 1 , k + 1 ) : NEW_LINE INDENT if ( fact ( i ) % k == 0 ) : NEW_LINE INDENT return i NEW_LINE DED...
Program for Chocolate and Wrapper Puzzle | Returns maximum number of chocolates we can eat with given money , price of chocolate and number of wrapprices required to get a chocolate . ; Corner case ; First find number of chocolates that can be purchased with the given amount ; Now just add number of chocolates with the...
def countMaxChoco ( money , price , wrap ) : NEW_LINE INDENT if ( money < price ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT choc = int ( money / price ) NEW_LINE choc = choc + ( choc - 1 ) / ( wrap - 1 ) NEW_LINE return int ( choc ) NEW_LINE DEDENT money = 15 NEW_LINE price = 1 NEW_LINE wrap = 3 NEW_LINE print ( count...
Check if possible to move from given coordinate to desired coordinate | Python program to check if it is possible to reach ( a , b ) from ( x , y ) . Returns GCD of i and j ; Returns true if it is possible to go to ( a , b ) from ( x , y ) ; Find absolute values of all as sign doesn 't matter. ; If gcd is equal then i...
def gcd ( i , j ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return i NEW_LINE DEDENT if ( i > j ) : NEW_LINE INDENT return gcd ( i - j , j ) NEW_LINE DEDENT return gcd ( i , j - i ) NEW_LINE DEDENT def ispossible ( x , y , a , b ) : NEW_LINE INDENT x , y , a , b = abs ( x ) , abs ( y ) , abs ( a ) , abs ( b ) N...
Equidigital Numbers | Python3 Program to find Equidigital Numbers till n ; Array to store all prime less than and equal to MAX . ; Utility function for sieve of sundaram ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than MAX , we r...
import math NEW_LINE MAX = 10000 ; NEW_LINE primes = [ ] ; NEW_LINE def sieveSundaram ( ) : NEW_LINE INDENT marked = [ False ] * int ( MAX / 2 + 1 ) ; NEW_LINE for i in range ( 1 , int ( ( math . sqrt ( MAX ) - 1 ) / 2 ) + 1 ) : NEW_LINE INDENT for j in range ( ( i * ( i + 1 ) ) << 1 , int ( MAX / 2 ) + 1 , 2 * i + 1 )...
LCM of First n Natural Numbers | To calculate hcf ; to calculate lcm ; lcm ( a , b ) = ( a * b ) hcf ( a , b ) ; Assign a = lcm of n , n - 1 ; b = b - 1 ; Driver code ; ; Function call pass n , n - 1 in function to find LCM of first n natural number
def hcf ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return hcf ( b , a % b ) NEW_LINE DEDENT def findlcm ( a , b ) : NEW_LINE INDENT if ( b == 1 ) : NEW_LINE INDENT return a NEW_LINE DEDENT a = ( a * b ) // hcf ( a , b ) NEW_LINE b -= 1 NEW_LINE return findlcm ( a , b ) NEW_LINE...
Smallest number divisible by first n numbers | Python program to find the smallest number evenly divisible by all number 1 to n ; Returns the lcm of first n numbers ; Driver code
import math NEW_LINE def lcm ( n ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = int ( ( ans * i ) / math . gcd ( ans , i ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 20 NEW_LINE print ( lcm ( n ) ) NEW_LINE
Trapezoidal Rule for Approximate Value of Definite Integral | A sample function whose definite integral 's approximate value is computed using Trapezoidal rule ; Declaring the function f ( x ) = 1 / ( 1 + x * x ) ; Function to evaluate the value of integral ; Grid spacing ; Computing sum of first and last terms in abov...
def y ( x ) : NEW_LINE INDENT return ( 1 / ( 1 + x * x ) ) NEW_LINE DEDENT def trapezoidal ( a , b , n ) : NEW_LINE INDENT h = ( b - a ) / n NEW_LINE s = ( y ( a ) + y ( b ) ) NEW_LINE i = 1 NEW_LINE while i < n : NEW_LINE INDENT s += 2 * y ( a + i * h ) NEW_LINE i += 1 NEW_LINE DEDENT return ( ( h / 2 ) * s ) NEW_LINE...
Breaking an Integer to get Maximum Product | The main function that returns the max possible product ; n equals to 2 or 3 must be handled explicitly ; Keep removing parts of size 3 while n is greater than 4 ; Keep multiplying 3 to res ; The last part multiplied by previous parts ; Driver program to test above functions
def maxProd ( n ) : NEW_LINE INDENT if ( n == 2 or n == 3 ) : NEW_LINE INDENT return ( n - 1 ) ; NEW_LINE DEDENT res = 1 ; NEW_LINE while ( n > 4 ) : NEW_LINE INDENT n -= 3 ; NEW_LINE res *= 3 ; NEW_LINE DEDENT return ( n * res ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( " Maximum ▁ Pr...
Number of elements with odd factors in given range | Function to count odd squares ; Driver code
def countOddSquares ( n , m ) : NEW_LINE INDENT return int ( m ** 0.5 ) - int ( ( n - 1 ) ** 0.5 ) NEW_LINE DEDENT n = 5 NEW_LINE m = 100 NEW_LINE print ( " Count ▁ is " , countOddSquares ( n , m ) ) NEW_LINE
Check if a number exists having exactly N factors and K prime factors | Function to compute the number of factors of the given number ; Vector to store the prime factors ; While there are no two multiples in the number , divide it by 2 ; If the size is already greater than K , then return true ; Computing the remaining...
def factors ( n , k ) : NEW_LINE INDENT v = [ ] ; NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT v . append ( 2 ) ; NEW_LINE n //= 2 ; NEW_LINE DEDENT if ( len ( v ) >= k ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT for i in range ( 3 , int ( n ** ( 1 / 2 ) ) , 2 ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LIN...
To Generate a One Time Password or Unique Identification URL | A Python3 Program to generate OTP ( One Time Password ) ; A Function to generate a unique OTP everytime ; All possible characters of my OTP ; String to hold my OTP ; Driver code ; Declare the length of OTP
import random NEW_LINE def generateOTP ( length ) : NEW_LINE INDENT str = " abcdefghijklmnopqrstuvwxyzAB\ STRNEWLINE TABSYMBOL CDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ; NEW_LINE n = len ( str ) ; NEW_LINE OTP = " " ; NEW_LINE for i in range ( 1 , length + 1 ) : NEW_LINE INDENT OTP += str [ int ( random . random ( ) * 10 ) ...
LCM of given array elements | Recursive function to return gcd of a and b ; recursive implementation ; lcm ( a , b ) = ( a * b / gcd ( 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 LcmOfArray ( arr , idx ) : NEW_LINE INDENT if ( idx == len ( arr ) - 1 ) : NEW_LINE INDENT return arr [ idx ] NEW_LINE DEDENT a = arr [ idx ] NEW_LINE b = LcmOfArray ( arr , idx ...
Check if a number is a power of another number | Returns true if y is a power of x ; The only power of 1 is 1 itself ; Repeatedly compute power of x ; Check if power of x becomes y ; check the result for true / false and print
def isPower ( x , y ) : NEW_LINE INDENT if ( x == 1 ) : NEW_LINE INDENT return ( y == 1 ) NEW_LINE DEDENT pow = 1 NEW_LINE while ( pow < y ) : NEW_LINE INDENT pow = pow * x NEW_LINE DEDENT return ( pow == y ) NEW_LINE DEDENT if ( isPower ( 10 , 1 ) ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT ...
Number of perfect squares between two given numbers | An Efficient Method to count squares between a and b ; An efficient solution to count square between a and b ; Driver Code
import math NEW_LINE def CountSquares ( a , b ) : NEW_LINE INDENT return ( math . floor ( math . sqrt ( b ) ) - math . ceil ( math . sqrt ( a ) ) + 1 ) NEW_LINE DEDENT a = 9 NEW_LINE b = 25 NEW_LINE print " Count ▁ of ▁ squares ▁ is : " , int ( CountSquares ( a , b ) ) NEW_LINE
Check if count of divisors is even or odd | Naive Solution to find if count of divisors is even or odd ; Function to count the divisors ; Initialize count of divisors ; Note that this loop runs till square root ; If divisors are equal , increment count by one Otherwise increment count by 2 ; Driver Code
import math NEW_LINE def countDivisors ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , ( int ) ( math . sqrt ( n ) ) + 2 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n // i == i ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = count + 2 NEW_LINE DEDENT...
Gray to Binary and Binary to Gray conversion | Python3 code for above approach ; Driver code
def greyConverter ( n ) : NEW_LINE INDENT return n ^ ( n >> 1 ) NEW_LINE DEDENT n = 3 NEW_LINE print ( greyConverter ( n ) ) NEW_LINE n = 9 NEW_LINE print ( greyConverter ( n ) ) NEW_LINE
Compute n ! under modulo p | Returns largest power of p that divides n ! ; Initialize result ; Calculate x = n / p + n / ( p ^ 2 ) + n / ( p ^ 3 ) + ... . ; Utility function to do modular exponentiation . It returns ( x ^ y ) % p ; Initialize result Update x if it is more than or equal to p ; If y is odd , multiply x w...
def largestPower ( n , p ) : NEW_LINE INDENT x = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n //= p NEW_LINE x += n NEW_LINE DEDENT return x NEW_LINE DEDENT def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p ...
Count number of squares in a rectangle | Returns count of all squares in a rectangle of size m x n ; If n is smaller , swap m and n ; Now n is greater dimension , apply formula ; Driver Code
def countSquares ( m , n ) : NEW_LINE INDENT if ( n < m ) : NEW_LINE INDENT temp = m NEW_LINE m = n NEW_LINE n = temp NEW_LINE DEDENT return ( ( m * ( m + 1 ) * ( 2 * m + 1 ) / 6 + ( n - m ) * m * ( m + 1 ) / 2 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 4 NEW_LINE n = 3 NEW_LINE print ( "...
Count factorial numbers in a given range | Function to count factorial ; Find the first factorial number ' fact ' greater than or equal to 'low ; Count factorial numbers in range [ low , high ] ; Return the count ; Driver code
def countFact ( low , high ) : NEW_LINE ' NEW_LINE INDENT fact = 1 NEW_LINE x = 1 NEW_LINE while ( fact < low ) : NEW_LINE INDENT fact = fact * x NEW_LINE x += 1 NEW_LINE DEDENT res = 0 NEW_LINE while ( fact <= high ) : NEW_LINE INDENT res += 1 NEW_LINE fact = fact * x NEW_LINE x += 1 NEW_LINE DEDENT return res NEW_LIN...
Find number of days between two given dates | A date has day ' d ' , month ' m ' and year 'y ; To store number of days in all months from January to Dec . ; This function counts number of leap years before the given date ; Check if the current year needs to be considered for the count of leap years or not ; An year is ...
' NEW_LINE class Date : NEW_LINE INDENT def __init__ ( self , d , m , y ) : NEW_LINE INDENT self . d = d NEW_LINE self . m = m NEW_LINE self . y = y NEW_LINE DEDENT DEDENT monthDays = [ 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ] NEW_LINE def countLeapYears ( d ) : NEW_LINE INDENT years = d . y NEW_LINE...
Find length of period in decimal value of 1 / n | Function to find length of period in 1 / n ; Find the ( n + 1 ) th remainder after decimal point in value of 1 / n ; Store ( n + 1 ) th remainder ; Count the number of remainders before next occurrence of ( n + 1 ) ' th ▁ remainder ▁ ' d ; Driver Code
def getPeriod ( n ) : NEW_LINE INDENT rem = 1 NEW_LINE for i in range ( 1 , n + 2 ) : NEW_LINE INDENT rem = ( 10 * rem ) % n NEW_LINE DEDENT d = rem NEW_LINE DEDENT ' NEW_LINE INDENT count = 0 NEW_LINE rem = ( 10 * rem ) % n NEW_LINE count += 1 NEW_LINE while rem != d : NEW_LINE INDENT rem = ( 10 * rem ) % n NEW_LINE c...
Replace all Γ’ β‚¬Λœ 0 Γ’ €ℒ with Γ’ β‚¬Λœ 5 Γ’ €ℒ in an input Integer | ; returns the number to be added to the input to replace all zeroes with five ; amount to be added ; unit decimal place ; a number divisible by 10 , then this is a zero occurrence in the input ; move one decimal place ; Driver code
def replace0with5 ( number ) : NEW_LINE INDENT number += calculateAddedValue ( number ) NEW_LINE return number NEW_LINE DEDENT def calculateAddedValue ( number ) : NEW_LINE INDENT result = 0 NEW_LINE decimalPlace = 1 NEW_LINE if ( number == 0 ) : NEW_LINE INDENT result += ( 5 * decimalPlace ) NEW_LINE DEDENT while ( nu...
Program to find remainder without using modulo or % operator | This function returns remainder of num / divisor without using % ( modulo ) operator ; Driver program to test above functions
def getRemainder ( num , divisor ) : NEW_LINE INDENT return ( num - divisor * ( num // divisor ) ) NEW_LINE DEDENT num = 100 NEW_LINE divisor = 7 NEW_LINE print ( getRemainder ( num , divisor ) ) NEW_LINE
Efficient Program to Compute Sum of Series 1 / 1 ! + 1 / 2 ! + 1 / 3 ! + 1 / 4 ! + . . + 1 / n ! | Function to return value of 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; Update factorial ; Update series sum ; Driver program to test above functions
def sum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE fact = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fact *= i NEW_LINE sum += 1.0 / fact NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT n = 5 NEW_LINE sum ( n ) NEW_LINE
Print first k digits of 1 / n where n is a positive integer | Python code to Print first k digits of 1 / n where n is a positive integer ; Function to print first k digits after dot in value of 1 / n . n is assumed to be a positive integer . ; Initialize remainder ; Run a loop k times to print k digits ; The next digit...
import math NEW_LINE def Print ( n , k ) : NEW_LINE INDENT rem = 1 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT print ( math . floor ( ( ( 10 * rem ) / n ) ) , end = " " ) NEW_LINE rem = ( 10 * rem ) % n NEW_LINE DEDENT DEDENT n = 7 NEW_LINE k = 3 NEW_LINE Print ( n , k ) ; NEW_LINE print ( " ▁ " ) NEW_LINE n = ...
Program to find sum of series 1 + 1 / 2 + 1 / 3 + 1 / 4 + . . + 1 / n | Function to return sum of 1 / 1 + 1 / 2 + 1 / 3 + . . + 1 / n ; Driver Code
def sum ( n ) : NEW_LINE INDENT i = 1 NEW_LINE s = 0.0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT s = s + 1 / i ; NEW_LINE DEDENT return s ; NEW_LINE DEDENT n = 5 NEW_LINE print ( " Sum ▁ is " , round ( sum ( n ) , 6 ) ) NEW_LINE
Program to find GCD or HCF of two 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 ( ...
Rearrange an array so that arr [ i ] becomes arr [ arr [ i ] ] with O ( 1 ) extra space | The function to rearrange an array in - place so that arr [ i ] becomes arr [ arr [ i ] ] . ; First step : Increase all values by ( arr [ arr [ i ] ] % n ) * n ; Second Step : Divide all values by n ; A utility function to print a...
def rearrange ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT arr [ i ] += ( arr [ arr [ i ] ] % n ) * n NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT arr [ i ] = int ( arr [ i ] / n ) NEW_LINE DEDENT DEDENT def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_...
Print all sequences of given length | A utility function that prints a given arr [ ] of length size ; The core function that recursively generates and prints all sequences of length k ; A function that uses printSequencesRecur ( ) to prints all sequences from 1 , 1 , . .1 to n , n , . . n ; Driver Code
def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT print ( " " ) ; NEW_LINE return ; NEW_LINE DEDENT def printSequencesRecur ( arr , n , k , index ) : NEW_LINE INDENT if ( k == 0 ) : NEW_LINE INDENT printArray ( arr , index ) ; N...
Check if a number is multiple of 5 without using / and % operators | Assumes that n is a positive integer ; Driver Code
def isMultipleof5 ( n ) : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT n = n - 5 NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT i = 19 NEW_LINE if ( isMultipleof5 ( i ) == 1 ) : NEW_LINE INDENT print ( i , " is ▁ multiple ▁ of ▁ 5" ) NEW_LINE DEDENT else : NEW_LIN...
Count pairs from an array having sum of twice of their AND and XOR equal to K | Python3 program for the above approach ; Function to count number of pairs satisfying the given conditions ; Stores the frequency of array elements ; Stores the total number of pairs ; Traverse the array ; Add it to cnt ; Update frequency o...
from collections import defaultdict NEW_LINE def countPairs ( arr , N , K ) : NEW_LINE INDENT mp = defaultdict ( int ) NEW_LINE cnt = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cnt += mp [ K - arr [ i ] ] NEW_LINE mp [ arr [ i ] ] += 1 NEW_LINE DEDENT print ( cnt ) NEW_LINE DEDENT arr = [ 1 , 5 , 4 , 8 , 7 ] NEW...
Queries to count array elements from a given range having a single set bit | Function to check whether only one bit is set or not ; Function to perform Range - query ; Function to count array elements with a single set bit for each range in a query ; Initialize array for Prefix sum ; Driver Code ; Given array ; Size of...
def check ( x ) : NEW_LINE INDENT if ( ( ( x ) & ( x - 1 ) ) == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def query ( l , r , pre ) : NEW_LINE INDENT if ( l == 0 ) : NEW_LINE INDENT return pre [ r ] NEW_LINE DEDENT else : NEW_LINE INDENT return pre [ r ] - pre [ l - 1 ] NEW_LINE DEDENT DED...
Bitwise operations on Subarrays of size K | Function to convert bit array to decimal number ; Function to find minimum values of each bitwise AND operation on element of subarray of size K ; Maintain an integer array bit of size 32 all initialized to 0 ; Create a sliding window of size k ; Function call ; Perform opera...
def build_num ( bit , k ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT if ( bit [ i ] == k ) : NEW_LINE INDENT ans += ( 1 << i ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT def minimumAND ( arr , n , k ) : NEW_LINE INDENT bit = [ 0 ] * 32 ; NEW_LINE for i in range ( k ) : NEW_L...
Equal Sum and XOR of three Numbers | Function to calculate power of 3 ; Function to return the count of the unset bit ( zeros ) ; Check the bit is 0 or not ; Right shifting ( dividing by 2 ) ; Driver Code
def calculate ( bit_cnt ) : NEW_LINE INDENT res = 1 ; NEW_LINE while ( bit_cnt > 0 ) : NEW_LINE INDENT bit_cnt -= 1 ; NEW_LINE res = res * 3 ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def unset_bit_count ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( ( n & 1 ) == 0 ) : NEW_LINE ...
Count pairs of elements such that number of set bits in their AND is B [ i ] | Function to return the count of pairs which satisfy the given condition ; Check if the count of set bits in the AND value is B [ j ] ; Driver code
def solve ( A , B , n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT c = A [ i ] & A [ j ] NEW_LINE if ( bin ( c ) . count ( '1' ) == B [ j ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ ==...
Total pairs in an array such that the bitwise AND , bitwise OR and bitwise XOR of LSB is 1 | Function to find the count of required pairs ; To store the count of elements which give remainder 0 i . e . even values ; To store the count of elements which give remainder 1 i . e . odd values ; Driver code
def CalculatePairs ( a , n ) : NEW_LINE INDENT cnt_zero = 0 NEW_LINE cnt_one = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( a [ i ] % 2 == 0 ) : NEW_LINE INDENT cnt_zero += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt_one += 1 NEW_LINE DEDENT DEDENT total_XOR_pairs = cnt_zero * cnt_one NEW_LINE total_AND_...
Assign other value to a variable from two possible values | Function to alternate the values ; Driver code
def alternate ( a , b , x ) : NEW_LINE INDENT x = a + b - x NEW_LINE print ( " After ▁ change ▁ x ▁ is : " , x ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = - 10 NEW_LINE b = 15 NEW_LINE x = a NEW_LINE print ( " x ▁ is : " , x ) NEW_LINE alternate ( a , b , x ) NEW_LINE DEDENT