text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Chen Prime Number | Python3 program to check Chen Prime number ; Utility function to Check Semi - prime number ; Increment count of prime number ; If count is greater than 2 , break loop ; If number is greater than 1 , add it to the count variable as it indicates the number remain is prime number ; Return '1' if count ...
import math NEW_LINE def isSemiPrime ( num ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( 2 , int ( math . sqrt ( num ) ) + 1 ) : NEW_LINE INDENT while num % i == 0 : NEW_LINE INDENT num /= i NEW_LINE DEDENT cnt += 1 NEW_LINE if cnt >= 2 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( num > 1 ) : NEW_LINE IN...
Thabit number | Utility function to Check power of two ; function to check if the given number is Thabit Number ; Add 1 to the number ; Divide the number by 3 ; Check if the given number is power of 2 ; Driver Program ; Check if number is thabit number
def isPowerOfTwo ( n ) : NEW_LINE INDENT return ( n and ( not ( n & ( n - 1 ) ) ) ) NEW_LINE DEDENT def isThabitNumber ( n ) : NEW_LINE INDENT n = n + 1 ; NEW_LINE if ( n % 3 == 0 ) : NEW_LINE INDENT n = n // 3 ; NEW_LINE DEDENT else : NEW_LINE return False NEW_LINE if ( isPowerOfTwo ( n ) ) : NEW_LINE INDENT return Tr...
Sum of all the prime numbers in a given range | Suppose the constraint is N <= 1000 ; Declare an array for dynamic approach ; Method to compute the array ; Declare an extra array as array ; Iterate the loop till sqrt ( N ) Time Complexity is O ( log ( n ) X sqrt ( N ) ) ; if ith element of arr is 0 i . e . marked as pr...
N = 1000 NEW_LINE dp = [ 0 ] * ( N + 1 ) NEW_LINE def sieve ( ) : NEW_LINE INDENT array = [ 0 ] * ( N + 1 ) NEW_LINE array [ 0 ] = 1 NEW_LINE array [ 1 ] = 1 NEW_LINE for i in range ( 2 , math . ceil ( math . sqrt ( N ) + 1 ) ) : NEW_LINE INDENT if array [ i ] == 0 : NEW_LINE INDENT for j in range ( i * i , N + 1 , i )...
Smallest Integer to be inserted to have equal sums | Python3 program to find the smallest number to be added to make the sum of left and right subarrays equal ; Function to find the minimum value to be added ; Variable to store entire array sum ; Variables to store sum of subarray1 and subarray 2 ; minimum value to be ...
import sys NEW_LINE def findMinEqualSums ( a , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum = sum + a [ i ] NEW_LINE DEDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE min = sys . maxsize NEW_LINE for i in range ( 0 , N - 1 ) : NEW_LINE INDENT sum1 += a [ i ] NEW_LINE sum2 = sum - sum1 ...
Sum of the 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 changed , then it is a prime ; Set all multiples of p ...
MAX = 10000 NEW_LINE prime = [ True for i in range ( MAX + 1 ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime [ 1 ] = False NEW_LINE for p in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT i = p * 2 NEW_LINE while ( i <= MAX ) : NEW_LINE INDENT prime [ i ] = False N...
Implementation of Wilson Primality test | Function to calculate the factorial ; Function to check if the number is prime or not ; Driver code
def fact ( p ) : NEW_LINE INDENT if ( p <= 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return p * fact ( p - 1 ) NEW_LINE DEDENT def isPrime ( p ) : NEW_LINE INDENT if ( p == 4 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( fact ( p >> 1 ) % p ) NEW_LINE DEDENT if ( isPrime ( 127 ) == 0 ) : NEW_LINE INDENT pr...
Find the total Number of Digits in ( N ! ) N | Python program to find the total Number of Digits in ( N ! ) ^ N ; Function to find the total Number of Digits in ( N ! ) ^ N ; Finding X ; Calculating N * X ; Floor ( N * X ) + 1 equivalent to floor ( sum ) + 1 ; Driver code
import math as ma NEW_LINE def CountDigits ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT sum += ma . log ( i , 10 ) NEW_LINE DEDENT sum *= n NEW_LINE return ma . ceil ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ...
Find the value of max ( f ( x ) ) | Python 3 implementation of above approach ; Function to calculate the value ; forming the prefix sum arrays ; Taking the query ; finding the sum in the range l to r in array a ; finding the sum in the range l to r in array b ; Finding the max value of the function ; Finding the min v...
MAX = 200006 NEW_LINE CONS = 32766 NEW_LINE def calc ( a , b , lr , q , n ) : NEW_LINE INDENT cc = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT a [ i + 1 ] += a [ i ] NEW_LINE b [ i + 1 ] += b [ i ] NEW_LINE DEDENT while ( q > 0 ) : NEW_LINE INDENT l = lr [ cc ] NEW_LINE cc += 1 NEW_LINE r = lr [ cc ] NEW_LINE...
Program to find the Nth number of the series 2 , 10 , 24 , 44 , 70. ... . | Function for calculating Nth term of series ; return nth term ; Driver code ; Function Calling
def NthTerm ( N ) : NEW_LINE INDENT x = ( 3 * N * N ) % 1000000009 NEW_LINE return ( ( x - N + 1000000009 ) % 1000000009 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE print ( NthTerm ( N ) ) NEW_LINE DEDENT
Sum of first N natural numbers by taking powers of 2 as negative number | to store power of 2 ; to store presum of the power of 2 's ; function to find power of 2 ; to store power of 2 ; to store pre sum ; Function to find the sum ; first store sum of first n natural numbers . ; find the first greater number than given...
power = [ 0 ] * 31 NEW_LINE pre = [ 0 ] * 31 NEW_LINE def PowerOfTwo ( ) : NEW_LINE INDENT x = 1 NEW_LINE for i in range ( 31 ) : NEW_LINE INDENT power [ i ] = x NEW_LINE x *= 2 NEW_LINE DEDENT pre [ 0 ] = 1 NEW_LINE for i in range ( 1 , 31 ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + power [ i ] NEW_LINE DEDENT DED...
Check if a number is Quartan Prime or not | Utility function to check if a number is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Driver Code ; Check if number is prime and of the form 16 * n + 1
def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2...
Print a number strictly less than a given number such that all its digits are distinct . | Function to find a number less than n such that all its digits are distinct ; looping through numbers less than n ; initializing a hash array ; creating a copy of i ; initializing variables to compare lengths of digits ; counting...
def findNumber ( n ) : NEW_LINE INDENT i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT count = [ 0 for i in range ( 10 ) ] NEW_LINE x = i NEW_LINE count1 = 0 NEW_LINE count2 = 0 NEW_LINE while ( x ) : NEW_LINE INDENT count [ x % 10 ] += 1 NEW_LINE x = int ( x / 10 ) NEW_LINE count1 += 1 NEW_LINE DEDENT for j in r...
Check if two Linked Lists are permutations of each other | A linked list node ; Function to check if two linked lists are permutations of each other first : reference to head of first linked list second : reference to head of second linked list ; Variables to keep track of sum and multiplication ; Traversing through li...
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def isPermutation ( first , second ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE mul1 = 1 NEW_LINE mul2 = 1 NEW_LINE temp1 = first NEW_LINE while ( temp1 != None ) : NEW_LINE...
Find two distinct prime numbers with given product | from math lib . import everything ; Function to generate all prime numbers less than n ; Initialize all entries of boolean array as true . A value in isPrime [ i ] will finally be false if i is Not a prime , else true bool isPrime [ n + 1 ] ; ; If isPrime [ p ] is no...
from math import * NEW_LINE def SieveOfEratosthenes ( n , isPrime ) : NEW_LINE INDENT isPrime [ 0 ] , isPrime [ 1 ] = False , False NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT isPrime [ i ] = True NEW_LINE DEDENT for p in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if isPrime [ p ] == True : NEW_...
Program to find the common ratio of three numbers | Python 3 implementation of above approach ; Function to print a : b : c ; To print the given proportion in simplest form . ; Driver code ; Get ratio a : b1 ; Get ratio b2 : c ; Find the ratio a : b : c
import math NEW_LINE def solveProportion ( a , b1 , b2 , c ) : NEW_LINE INDENT A = a * b2 NEW_LINE B = b1 * b2 NEW_LINE C = b1 * c NEW_LINE gcd1 = math . gcd ( math . gcd ( A , B ) , C ) NEW_LINE print ( str ( A // gcd1 ) + " : " + str ( B // gcd1 ) + " : " + str ( C // gcd1 ) ) NEW_LINE DEDENT if __name__ == " _ _ mai...
Number of divisors of a given number N which are divisible by K | Function to count number of divisors of N which are divisible by K ; Variable to store count of divisors ; Traverse from 1 to n ; increase the count if both the conditions are satisfied ; Driver code
def countDivisors ( n , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( n % i == 0 and i % k == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 12 , 3 NEW_LINE print ( countDivisor...
Calculate volume and surface area of a cone | Python3 program to calculate Volume and Surface area of Cone ; Function to calculate Volume of Cone ; Function To Calculate Surface Area of Cone ; Driver Code ; Printing value of volume and surface area
import math NEW_LINE pi = math . pi NEW_LINE def volume ( r , h ) : NEW_LINE INDENT return ( 1 / 3 ) * pi * r * r * h NEW_LINE DEDENT def surfacearea ( r , s ) : NEW_LINE INDENT return pi * r * s + pi * r * r NEW_LINE DEDENT radius = float ( 5 ) NEW_LINE height = float ( 12 ) NEW_LINE slat_height = float ( 13 ) NEW_LIN...
Program to find the Nth term of the series 0 , 14 , 40 , 78 , 124 , ... | calculate sum upto Nth term of series ; return the final sum ; Driver code
def nthTerm ( n ) : NEW_LINE INDENT return int ( 6 * pow ( n , 2 ) - 4 * n - 2 ) NEW_LINE DEDENT N = 4 NEW_LINE print ( nthTerm ( N ) ) NEW_LINE
Program to find the Nth term of series 5 , 10 , 17 , 26 , 37 , 50 , 65 , 82 , ... | Python3 program to find the N - th term of the series : 5 , 10 , 17 , 26 , 37 , 50 , 65 , 82 , ... ; calculate Nth term of series ; return the final sum ; Driver code
from math import * NEW_LINE def nthTerm ( n ) : NEW_LINE INDENT return pow ( n , 2 ) + 2 * n + 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE print ( nthTerm ( N ) ) NEW_LINE DEDENT
Find nth term of a given recurrence relation | function to return required value ; Get the answer ; Return the answer ; Get the value of n ; function call to prresult
def sum ( n ) : NEW_LINE INDENT ans = ( n * ( n - 1 ) ) / 2 ; NEW_LINE return ans NEW_LINE DEDENT n = 5 NEW_LINE print ( int ( sum ( n ) ) ) NEW_LINE
Program to find Nth term of the series 3 , 12 , 29 , 54 , 87 , ... | calculate Nth term of series ; Return Nth term ; driver code ; declaration of number of terms ; Get the Nth term
def getNthTerm ( N ) : NEW_LINE INDENT return 4 * pow ( N , 2 ) - 3 * N + 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE print ( getNthTerm ( N ) ) NEW_LINE DEDENT
Find sum of product of number in given series | Python 3 program to find sum of product of number in given series ; function to calculate ( a ^ b ) % p ; Initialize result ; 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 return re...
MOD = 1000000007 NEW_LINE 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 NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def sumProd ( n , t ) : NEW_LINE INDENT dino = power ( t + 1...
Find the sum of series 3 , 7 , 13 , 21 , 31. ... | Function to calculate sum ; Return sum ; driver code
def findSum ( n ) : NEW_LINE INDENT return ( n * ( pow ( n , 2 ) + 3 * n + 5 ) ) / 3 NEW_LINE DEDENT n = 25 NEW_LINE print ( int ( findSum ( n ) ) ) NEW_LINE
Minimum Players required to win the game | Python 3 Program to find minimum players required to win the game anyhow ; function to calculate ( a ^ b ) % ( 10 ^ 9 + 7 ) . ; function to find the minimum required player ; computing the nenomenator ; computing modulo inverse of denominator ; final result ; Driver Code
mod = 1000000007 NEW_LINE def power ( a , b ) : NEW_LINE INDENT res = 1 NEW_LINE while ( b ) : NEW_LINE INDENT if ( b & 1 ) : NEW_LINE INDENT res *= a NEW_LINE res %= mod NEW_LINE DEDENT b //= 2 NEW_LINE a *= a NEW_LINE a %= mod NEW_LINE DEDENT return res NEW_LINE DEDENT def minPlayer ( n , k ) : NEW_LINE INDENT num = ...
Sum of Factors of a Number using Prime Factorization | Using SieveOfEratosthenes to find smallest prime factor of all the numbers . For example , if N is 10 , s [ 2 ] = s [ 4 ] = s [ 6 ] = s [ 10 ] = 2 s [ 3 ] = s [ 9 ] = 3 s [ 5 ] = 5 s [ 7 ] = 7 ; Create a boolean list " prime [ 0 . . n ] " and initialize all entries...
def sieveOfEratosthenes ( N , s ) : NEW_LINE INDENT prime = [ False ] * ( N + 1 ) NEW_LINE for i in range ( 2 , N + 1 , 2 ) : NEW_LINE INDENT s [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , N + 1 , 2 ) : NEW_LINE INDENT if prime [ i ] == False : NEW_LINE INDENT s [ i ] = i NEW_LINE for j in range ( i , ( N + 1 ) // i ...
Find Multiples of 2 or 3 or 5 less than or equal to N | Function to count number of multiples of 2 or 3 or 5 less than or equal to N ; As we have to check divisibility by three numbers , So we can implement bit masking ; we check whether jth bit is set or not , if jth bit is set , simply multiply to prod ; check for se...
def countMultiples ( n ) : NEW_LINE INDENT multiple = [ 2 , 3 , 5 ] NEW_LINE count = 0 NEW_LINE mask = int ( pow ( 2 , 3 ) ) NEW_LINE for i in range ( 1 , mask ) : NEW_LINE INDENT prod = 1 NEW_LINE for j in range ( 3 ) : NEW_LINE INDENT if ( i & ( 1 << j ) ) : NEW_LINE INDENT prod = prod * multiple [ j ] NEW_LINE DEDEN...
Minimum value of N such that xor from 1 to N is equal to K | Function to find the value of N ; handling case for '0 ; handling case for '1 ; when number is completely divided by 4 then minimum ' x ' will be 'k ; when number divided by 4 gives 3 as remainder then minimum ' x ' will be 'k-1 ; else it is not possible to g...
def findN ( k ) : NEW_LINE ' NEW_LINE INDENT if ( k == 0 ) : NEW_LINE INDENT ans = 3 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( k == 1 ) : NEW_LINE INDENT ans = 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT elif ( k % 4 == 0 ) : NEW_LINE INDENT ans = k NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT elif ( k % 4 == 3 ) : NEW_...
Permutations to arrange N persons around a circular table | Function to find no . of permutations ; Driver Code
def Circular ( n ) : NEW_LINE INDENT Result = 1 NEW_LINE while n > 0 : NEW_LINE INDENT Result = Result * n NEW_LINE n -= 1 NEW_LINE DEDENT return Result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE print ( Circular ( n - 1 ) ) NEW_LINE DEDENT
Minimum time required to complete a work by N persons together | Function to calculate the time ; Driver Code
def calTime ( arr , n ) : NEW_LINE INDENT work = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT work += 1 / arr [ i ] NEW_LINE DEDENT return 1 / work NEW_LINE DEDENT arr = [ 6.0 , 3.0 , 4.0 ] NEW_LINE n = len ( arr ) NEW_LINE print ( calTime ( arr , n ) , " Hours " ) NEW_LINE
Find the largest twins in given range | Function to find twins ; Create a boolean array " prime [ 0 . . high ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Look for the smallest twin ; If p is not marked , then it is a prime ; Update all mult...
from math import sqrt , floor NEW_LINE def printTwins ( low , high ) : NEW_LINE INDENT prime = [ True for i in range ( high + 1 ) ] NEW_LINE twin = False NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE k = floor ( sqrt ( high ) ) + 2 NEW_LINE for p in range ( 2 , k , 1 ) : NEW_LINE INDENT if ( prime ...
Complement of a number with any base b | Function to find ( b - 1 ) 's complement ; Calculate number of digits in the given number ; Largest digit in the number system with base b ; Largest number in the number system with base b ; return Complement ; Function to find b 's complement ; b ' s ▁ complement ▁ = ▁ ( b - 1 ...
def prevComplement ( n , b ) : NEW_LINE INDENT maxNum , digits , num = 0 , 0 , n NEW_LINE while n > 1 : NEW_LINE INDENT digits += 1 NEW_LINE n = n // 10 NEW_LINE DEDENT maxDigit = b - 1 NEW_LINE while digits : NEW_LINE INDENT maxNum = maxNum * 10 + maxDigit NEW_LINE digits -= 1 NEW_LINE DEDENT return maxNum - num NEW_L...
Minimum positive integer value possible of X for given A and B in X = P * A + Q * B | Function to return gcd of a and b ;
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 / * Driver code * / NEW_LINE a = 2 NEW_LINE b = 4 NEW_LINE print ( gcd ( a , b ) ) NEW_LINE
Count elements in the given range which have maximum number of divisors | Function to count the elements with maximum number of divisors ; to store number of divisors initialise with zero ; to store the maximum number of divisors ; to store required answer ; Find the first divisible number ; Count number of divisors ; ...
def MaximumDivisors ( X , Y ) : NEW_LINE INDENT arr = [ 0 ] * ( Y - X + 1 ) NEW_LINE mx = 0 NEW_LINE cnt = 0 NEW_LINE i = 1 NEW_LINE while i * i <= Y : NEW_LINE INDENT sq = i * i NEW_LINE if ( ( X // i ) * i >= X ) : NEW_LINE INDENT first_divisible = ( X // i ) * i NEW_LINE DEDENT else : NEW_LINE INDENT first_divisible...
Find First element in AP which is multiple of given prime | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; 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 / 2 ; function to find nearest element in common ; base conditions ; ...
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 NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def NearestElement ( A , D , P ) : NEW_LINE INDENT if A == 0 : NEW...
Cunningham chain | Function to print Cunningham chain of the first kind ; Iterate till all elements are printed ; check prime or not ; Driver Code
def print_C ( p0 ) : NEW_LINE INDENT i = 0 ; NEW_LINE while ( True ) : NEW_LINE INDENT flag = 1 ; NEW_LINE x = pow ( 2 , i ) ; NEW_LINE p1 = x * p0 + ( x - 1 ) ; NEW_LINE for k in range ( 2 , p1 ) : NEW_LINE INDENT if ( p1 % k == 0 ) : NEW_LINE INDENT flag = 0 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag == 0 ) ...
Count pairs with Bitwise AND as ODD number | Function to count number of odd pairs ; variable for counting odd pairs ; find all pairs ; find AND operation check odd or even ; return number of odd pair ; Driver Code ; calling function findOddPair and print number of odd pair
def findOddPair ( A , N ) : NEW_LINE INDENT oddPair = 0 NEW_LINE for i in range ( 0 , N - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , N - 1 ) : NEW_LINE INDENT if ( ( A [ i ] & A [ j ] ) % 2 != 0 ) : NEW_LINE INDENT oddPair = oddPair + 1 NEW_LINE DEDENT DEDENT DEDENT return oddPair NEW_LINE DEDENT a = [ 5 , 1 , 3 , ...
Sudo Placement [ 1.7 ] | Greatest Digital Root | Function to return dig - sum ; Function to print the Digital Roots ; store the largest digital roots ; Iterate till sqrt ( n ) ; if i is a factor ; get the digit sum of both factors i and n / i ; if digit sum is greater then previous maximum ; if digit sum is greater the...
def summ ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n % 9 == 0 ) : NEW_LINE INDENT return 9 ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( n % 9 ) ; NEW_LINE DEDENT DEDENT def printDigitalRoot ( n ) : NEW_LINE INDENT maxi = 1 ; NEW_LINE dig = 1 ; NEW_LINE for i in range (...
Sum of all elements up to Nth row in a Pascal triangle | Function to find sum of all elements upto nth row . ; Initialize sum with 0 ; Calculate 2 ^ n ; Driver unicode
def calculateSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE sum = 1 << n ; NEW_LINE return ( sum - 1 ) NEW_LINE DEDENT n = 10 NEW_LINE print ( " Sum ▁ of ▁ all ▁ elements : " , calculateSum ( n ) ) NEW_LINE
Divide two integers without using multiplication , division and mod operator | Set2 | Python3 program for above approach ; Returns the quotient of dividend / divisor . ; Calculate sign of divisor i . e . , sign will be negative only if either one of them is negative otherwise it will be positive ; Remove signs of divid...
import math NEW_LINE def Divide ( a , b ) : NEW_LINE INDENT dividend = a ; NEW_LINE divisor = b ; NEW_LINE sign = - 1 if ( ( dividend < 0 ) ^ ( divisor < 0 ) ) else 1 ; NEW_LINE dividend = abs ( dividend ) ; NEW_LINE divisor = abs ( divisor ) ; NEW_LINE if ( divisor == 0 ) : NEW_LINE INDENT print ( " Cannot ▁ Divide ▁ ...
Represent the fraction of two numbers in the string format | Function to return the required fraction in string format ; If the numerator is zero , answer is 0 ; If any one ( out of numerator and denominator ) is - ve , sign of resultant answer - ve . ; Calculate the absolute part ( before decimal point ) . ; Output st...
def calculateFraction ( num , den ) : NEW_LINE INDENT if ( num == 0 ) : NEW_LINE INDENT return "0" NEW_LINE DEDENT sign = - 1 if ( num < 0 ) ^ ( den < 0 ) else 1 NEW_LINE num = abs ( num ) NEW_LINE den = abs ( den ) NEW_LINE initial = num // den NEW_LINE res = " " NEW_LINE if ( sign == - 1 ) : NEW_LINE INDENT res += " ...
Check if the n | Return if the nth term is even or odd . ; If a is even ; If b is even ; If b is odd ; If a is odd ; If b is odd ; If b is eve ; Driver Code
def findNature ( a , b , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return ( a & 1 ) ; NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return ( b & 1 ) ; NEW_LINE DEDENT if ( ( a & 1 ) == 0 ) : NEW_LINE INDENT if ( ( b & 1 ) == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT else : NEW_LINE INDENT retur...
Check if mirror image of a number is same if displayed in seven segment display | Return " Yes " , if the mirror image of number is same as the given number Else return " No " ; Checking if the number contain only 0 , 1 , 8. ; Checking if the number is palindrome or not . ; If corresponding index is not equal . ; Drive...
def checkEqual ( S ) : NEW_LINE INDENT for i in range ( len ( S ) ) : NEW_LINE INDENT if ( S [ i ] != '1' and S [ i ] != '0' and S [ i ] != '8' ) : NEW_LINE INDENT return " No " ; NEW_LINE DEDENT DEDENT start = 0 ; NEW_LINE end = len ( S ) - 1 ; NEW_LINE while ( start < end ) : NEW_LINE INDENT if ( S [ start ] != S [ e...
Check whether a given number is Polydivisible or Not | function to check polydivisible number ; digit extraction of input number ; store the digits in an array ; n contains first i digits ; n should be divisible by i ; Driver Code
def check_polydivisible ( n ) : NEW_LINE INDENT N = n NEW_LINE digit = [ ] NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit . append ( n % 10 ) NEW_LINE n /= 10 NEW_LINE DEDENT digit . reverse ( ) NEW_LINE flag = True NEW_LINE n = digit [ 0 ] NEW_LINE for i in range ( 1 , len ( digit ) , 1 ) : NEW_LINE INDENT n = n * 1...
Check if given number is a power of d where d is a power of 2 | Python3 program to find if a number is power of d where d is power of 2. ; Function to count the number of ways to paint N * 3 grid based on given conditions ; Check if there is only one bit set in n ; count 0 bits before set bit ; If count is a multiple o...
def Log2n ( n ) : NEW_LINE INDENT return ( 1 + Log2n ( n / 2 ) ) if ( n > 1 ) else 0 ; NEW_LINE DEDENT def isPowerOfd ( n , d ) : NEW_LINE INDENT count = 0 ; NEW_LINE if ( n and ( n & ( n - 1 ) ) == 0 ) : NEW_LINE INDENT while ( n > 1 ) : NEW_LINE INDENT n >>= 1 ; NEW_LINE count += 1 ; NEW_LINE DEDENT return ( count % ...
Octahedral Number | Function to find octahedral number ; Formula to calculate nth octahedral number ; Driver Code ; print result
def octahedral_num ( n ) : NEW_LINE INDENT return n * ( 2 * n * n + 1 ) // 3 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( n , " th ▁ Octahedral ▁ number : ▁ " , octahedral_num ( n ) ) NEW_LINE DEDENT
Centered tetrahedral number | Function to calculate Centered tetrahedral number ; Formula to calculate nth Centered tetrahedral number and return it into main function ; Driver Code
def centeredTetrahedralNumber ( n ) : NEW_LINE INDENT return ( 2 * n + 1 ) * ( n * n + n + 3 ) // 3 NEW_LINE DEDENT n = 6 NEW_LINE print ( centeredTetrahedralNumber ( n ) ) NEW_LINE
Swapping four variables without temporary variable | Python 3 program to swap 4 variables without using temporary variable . ; swapping a and b variables ; swapping b and c variables ; swapping c and d variables ; initialising variables ; Function call
def swap ( a , b , c , d ) : NEW_LINE INDENT a = a + b NEW_LINE b = a - b NEW_LINE a = a - b NEW_LINE b = b + c NEW_LINE c = b - c NEW_LINE b = b - c NEW_LINE c = c + d NEW_LINE d = c - d NEW_LINE c = c - d NEW_LINE print ( " values ▁ after ▁ swapping ▁ are ▁ : ▁ " ) NEW_LINE print ( " a ▁ = ▁ " , a ) NEW_LINE print ( ...
Sum of first n natural numbers | Function to find the sum of series ; Driver code
def seriessum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum += i * ( i + 1 ) / 2 NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 4 NEW_LINE print ( seriessum ( n ) ) NEW_LINE
Centrosymmetric Matrix | Python3 Program to check whether given matrix is centrosymmetric or not . ; Finding the middle row of the matrix ; for each row upto middle row . ; If each element and its corresponding element is not equal then return false . ; Driver Code
def checkCentrosymmetricted ( n , m ) : NEW_LINE INDENT mid_row = 0 ; NEW_LINE if ( ( n & 1 ) > 0 ) : NEW_LINE INDENT mid_row = n / 2 + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT mid_row = n / 2 ; NEW_LINE DEDENT for i in range ( int ( mid_row ) ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( m [ i ] [ ...
Centered triangular number | function for Centered Triangular number ; Formula to calculate nth Centered Triangular number ; Driver Code ; For 3 rd Centered Triangular number ; For 12 th Centered Triangular number
def Centered_Triangular_num ( n ) : NEW_LINE INDENT return ( 3 * n * n + 3 * n + 2 ) // 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE print ( Centered_Triangular_num ( n ) ) NEW_LINE n = 12 NEW_LINE print ( Centered_Triangular_num ( n ) ) NEW_LINE DEDENT
Array with GCD of any of its subset belongs to the given array | Python 3 implementation to generate the required array ; Function to find gcd of array of numbers ; Function to generate the array with required constraints . ; computing GCD of the given set ; Solution exists if GCD of array is equal to the minimum eleme...
from math import gcd NEW_LINE def findGCD ( arr , n ) : NEW_LINE INDENT result = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT result = gcd ( arr [ i ] , result ) NEW_LINE DEDENT return result NEW_LINE DEDENT def compute ( arr , n ) : NEW_LINE INDENT answer = [ ] NEW_LINE GCD_of_array = findGCD ( arr , ...
Combinatorics on ordered trees | Function returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to calculate the number of trees with exactly k leaves . ; Function to calculate total number...
def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ [ 0 for i in range ( k + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT C [ ...
Repeated Unit Divisibility | To find least value of k ; To check n is coprime or not ; to store R ( k ) mod n and 10 ^ k mod n value ; Driver code
def repUnitValue ( n ) : NEW_LINE INDENT if ( n % 2 == 0 or n % 5 == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT rem = 1 NEW_LINE power = 1 NEW_LINE k = 1 NEW_LINE while ( rem % n != 0 ) : NEW_LINE INDENT k += 1 NEW_LINE power = power * 10 % n NEW_LINE rem = ( rem + power ) % n NEW_LINE DEDENT return k NEW_LINE DEDE...
First N natural can be divided into two sets with given difference and co | Python3 code to determine whether numbers 1 to N can be divided into two sets such that absolute difference between sum of these two sets is M and these two sum are co - prime ; function that returns boolean value on the basis of whether it is ...
def __gcd ( a , b ) : NEW_LINE INDENT return a if ( b == 0 ) else __gcd ( b , a % b ) ; NEW_LINE DEDENT def isSplittable ( n , m ) : NEW_LINE INDENT total_sum = ( int ) ( ( n * ( n + 1 ) ) / 2 ) ; NEW_LINE sum_s1 = int ( ( total_sum + m ) / 2 ) ; NEW_LINE sum_s2 = total_sum - sum_s1 ; NEW_LINE if ( total_sum < m ) : NE...
Making zero array by decrementing pairs of adjacent | Python3 implementation of the above approach ; converting array element into number ; Check if divisible by 11 ; Driver Code
def isPossibleToZero ( a , n ) : NEW_LINE INDENT num = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT num = num * 10 + a [ i ] ; NEW_LINE DEDENT return ( num % 11 == 0 ) ; NEW_LINE DEDENT arr = [ 0 , 1 , 1 , 0 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE if ( isPossibleToZero ( arr , n ) ) : NEW_LINE INDENT print ( " Y...
Blum Integer | Function to cheek if number is Blum Integer ; to store prime numbers from 2 to n ; If prime [ i ] is not changed , then it is a prime ; Update all multiples of p ; to check if the given odd integer is Blum Integer or not ; checking the factors are of 4 t + 3 form or not ; give odd integer greater than 20
def isBlumInteger ( n ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) NEW_LINE i = 2 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( prime [ i ] == True ) : NEW_LINE INDENT for j in range ( i * 2 , n + 1 , i ) : NEW_LINE INDENT prime [ j ] = False NEW_LINE DEDENT DEDENT i = i + 1 NEW_LINE DEDENT for i in range ( ...
Program to calculate value of nCr | Python 3 program To calculate The Value Of nCr ; Returns factorial of n ; Driver code
def nCr ( n , r ) : NEW_LINE INDENT return ( fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ) NEW_LINE DEDENT def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT n = 5 NEW_LINE r = 3 NEW_LINE print ( int ( nCr ( n , r ) ...
Program to print the sum of the given nth term | Python3 program to illustrate ... Summation of series ; function to calculate sum of series ; Sum of n terms is n ^ 2 ; Driver Code
import math NEW_LINE def summingSeries ( n ) : NEW_LINE INDENT return math . pow ( n , 2 ) NEW_LINE DEDENT n = 100 NEW_LINE print ( " The ▁ sum ▁ of ▁ n ▁ term ▁ is : ▁ " , summingSeries ( n ) ) NEW_LINE
Brahmagupta Fibonacci Identity | Python 3 code to verify Brahmagupta Fibonacci identity ; represent the product as sum of 2 squares ; check identity criteria ; 1 ^ 2 + 2 ^ 2 ; 3 ^ 2 + 4 ^ 2 ; express product of sum of 2 squares as sum of ( sum of 2 squares )
def find_sum_of_two_squares ( a , b ) : NEW_LINE INDENT ab = a * b NEW_LINE i = 0 ; NEW_LINE while ( i * i <= ab ) : NEW_LINE INDENT j = i NEW_LINE while ( i * i + j * j <= ab ) : NEW_LINE INDENT if ( i * i + j * j == ab ) : NEW_LINE INDENT print ( i , " ^ 2 ▁ + ▁ " , j , " ^ 2 ▁ = ▁ " , ab ) NEW_LINE DEDENT j += 1 NEW...
Tetrahedral Numbers | Python3 Program to find the nth tetrahedral number ; Function to find Tetrahedral Number ; Driver Code
def tetrahedralNumber ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) * ( n + 2 ) ) / 6 NEW_LINE DEDENT def tetrahedralNumber ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) * ( n + 2 ) ) / 6 NEW_LINE DEDENT n = 5 NEW_LINE print ( tetrahedralNumber ( n ) ) NEW_LINE
Euler 's Four Square Identity | function to check euler four square identity ; loops checking the sum of squares ; sum of 2 squares ; sum of 3 squares ; sum of 4 squares ; product of 2 numbers represented as sum of four squares i , j , k , l ; product of 2 numbers a and b represented as sum of four squares i , j , k , ...
def check_euler_four_square_identity ( a , b , ab ) : NEW_LINE INDENT s = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i * i <= ab ) : NEW_LINE INDENT s = i * i ; NEW_LINE j = i ; NEW_LINE while ( j * j <= ab ) : NEW_LINE INDENT s = j * j + i * i ; NEW_LINE k = j ; NEW_LINE while ( k * k <= ab ) : NEW_LINE INDENT s = k * k + ...
Number of solutions to Modular Equations | Python Program to find number of possible values of X to satisfy A mod X = B ; Returns the number of divisors of ( A - B ) greater than B ; if N is divisible by i ; count only the divisors greater than B ; checking if a divisor isnt counted twice ; Utility function to calculat...
import math NEW_LINE def calculateDivisors ( A , B ) : NEW_LINE INDENT N = A - B NEW_LINE noOfDivisors = 0 NEW_LINE a = math . sqrt ( N ) NEW_LINE for i in range ( 1 , int ( a + 1 ) ) : NEW_LINE INDENT if ( ( N % i == 0 ) ) : NEW_LINE INDENT if ( i > B ) : NEW_LINE INDENT noOfDivisors += 1 NEW_LINE DEDENT if ( ( N / i ...
Perfect power ( 1 , 4 , 8 , 9 , 16 , 25 , 27 , ... ) | Python3 program to count number of numbers from 1 to n are of type x ^ y where x > 0 and y > 1 ; Function that keeps all the odd power numbers upto n ; We need exclude perfect squares . ; sort the vector ; Return sum of odd and even powers . ; Driver Code
import math NEW_LINE def powerNumbers ( n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 2 , int ( math . pow ( n , 1.0 / 3.0 ) ) + 1 ) : NEW_LINE INDENT j = i * i NEW_LINE while ( j * i <= n ) : NEW_LINE INDENT j = j * i NEW_LINE s = int ( math . sqrt ( j ) ) NEW_LINE if ( s * s != j ) : NEW_LINE INDENT v . app...
Variance and standard | Python3 program to find mean and variance of a matrix . ; variance function declaration Function for calculating mean ; Calculating sum ; Returning mean ; Function for calculating variance ; subtracting mean from elements ; a [ i ] [ j ] = fabs ( a [ i ] [ j ] ) ; squaring each terms ; taking su...
import math ; NEW_LINE def mean ( a , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT sum += a [ i ] [ j ] ; NEW_LINE DEDENT DEDENT return math . floor ( int ( sum / ( n * n ) ) ) ; NEW_LINE DEDENT def variance ( a , n , m ) : NEW_LINE INDENT sum = ...
Find N Arithmetic Means between A and B | Prints N arithmetic means between A and B . ; Calculate common difference ( d ) ; For finding N the arithmetic mean between A and B ; Driver code
def printAMeans ( A , B , N ) : NEW_LINE INDENT d = ( B - A ) / ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( int ( A + i * d ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT A = 20 ; B = 32 ; N = 5 NEW_LINE printAMeans ( A , B , N ) NEW_LINE
Sum of the series 1.2 . 3 + 2.3 . 4 + ... + n ( n + 1 ) ( n + 2 ) | function to calculate sum of series ; Driver program
def sumofseries ( n ) : NEW_LINE INDENT return int ( n * ( n + 1 ) * ( n + 2 ) * ( n + 3 ) / 4 ) NEW_LINE DEDENT print ( sumofseries ( 3 ) ) NEW_LINE
Largest number in [ 2 , 3 , . . n ] which is co | Python3 code to find Largest number in [ 2 , 3 , . . n ] which is co - prime with numbers in [ 2 , 3 , . . m ] ; Returns true if i is co - prime with numbers in set [ 2 , 3 , ... m ] ; Running the loop till square root of n to reduce the time complexity from n ; Find th...
import math NEW_LINE def isValid ( i , m ) : NEW_LINE INDENT sq_i = math . sqrt ( i ) NEW_LINE sq = min ( m , sq_i ) NEW_LINE for j in range ( 2 , sq + 1 ) : NEW_LINE INDENT if ( i % j == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def findLargestNum ( n , m ) : NEW_LINE INDENT...
Check whether a given matrix is orthogonal or not | ; Find transpose ; Find product of a [ ] [ ] and its transpose ; Since we are multiplying with transpose of itself . We use ; Check if product is identity matrix ; Driver Code
/ * Function to check orthogonalilty * / NEW_LINE def isOrthogonal ( a , m , n ) : NEW_LINE INDENT if ( m != n ) : NEW_LINE INDENT return False NEW_LINE DEDENT trans = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT trans...
Check if given number is perfect square | Python program to find if x is a perfect square . ; Find floating point value of square root of x . ; sqrt function returns floating value so we have to convert it into integer return boolean T / F ; Driver code
import math NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT if ( x >= 0 ) : NEW_LINE INDENT sr = math . sqrt ( x ) NEW_LINE return ( ( sr * sr ) == float ( x ) ) NEW_LINE DEDENT return false NEW_LINE DEDENT x = 2502 NEW_LINE if ( isPerfectSquare ( x ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NE...
Program to print GP ( Geometric Progression ) | function to print GP ; starting number ; Common ratio ; N th term to be find
def printGP ( a , r , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT curr_term = a * pow ( r , i ) NEW_LINE print ( curr_term , end = " ▁ " ) NEW_LINE DEDENT DEDENT a = 2 NEW_LINE r = 3 NEW_LINE n = 5 NEW_LINE printGP ( a , r , n ) NEW_LINE
HCF of array of fractions ( or rational numbers ) | Python 3 program to find HCF of array of ; find hcf of numerator series ; return hcf of numerator ; find lcm of denominator series ; ans contains LCM of arr [ 0 ] [ 1 ] , . . arr [ i ] [ 1 ] ; return lcm of denominator ; Core Function ; found hcf of numerator ; found ...
from math import gcd NEW_LINE def findHcf ( arr , size ) : NEW_LINE INDENT ans = arr [ 0 ] [ 0 ] NEW_LINE for i in range ( 1 , size , 1 ) : NEW_LINE INDENT ans = gcd ( ans , arr [ i ] [ 0 ] ) NEW_LINE DEDENT return ( ans ) NEW_LINE DEDENT def findLcm ( arr , size ) : NEW_LINE INDENT ans = arr [ 0 ] [ 1 ] NEW_LINE for i...
Space efficient iterative method to Fibonacci number | get second MSB ; consectutively set all the bits ; returns the second MSB ; Multiply function ; Function to calculate F [ ] [ ] raise to the power n ; Base case ; take 2D array to store number 's ; run loop till MSB > 0 ; To return fibonacci number ; Given n
def getMSB ( n ) : NEW_LINE INDENT n |= n >> 1 NEW_LINE n |= n >> 2 NEW_LINE n |= n >> 4 NEW_LINE n |= n >> 8 NEW_LINE n |= n >> 16 NEW_LINE return ( ( n + 1 ) >> 2 ) NEW_LINE DEDENT def multiply ( F , M ) : NEW_LINE INDENT x = F [ 0 ] [ 0 ] * M [ 0 ] [ 0 ] + F [ 0 ] [ 1 ] * M [ 1 ] [ 0 ] NEW_LINE y = F [ 0 ] [ 0 ] * M...
Stern | Python program to print Brocot Sequence ; loop to create sequence ; adding sum of considered element and it 's precedent ; adding next considered element ; printing sequence . . ; Driver code ; adding first two element in the sequence
import math NEW_LINE def SternSequenceFunc ( BrocotSequence , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT considered_element = BrocotSequence [ i ] NEW_LINE precedent = BrocotSequence [ i - 1 ] NEW_LINE BrocotSequence . append ( considered_element + precedent ) NEW_LINE BrocotSequence . append ( co...
Counting numbers whose difference from reverse is a product of k | Python 3 program to Count the numbers within a given range in which when you subtract a number from its reverse , the difference is a product of k ; function to check if the number and its reverse have their absolute difference divisible by k ; Reverse ...
def isRevDiffDivisible ( x , k ) : NEW_LINE INDENT n = x ; m = 0 NEW_LINE while ( x > 0 ) : NEW_LINE INDENT m = m * 10 + x % 10 NEW_LINE x = x // 10 NEW_LINE DEDENT return ( abs ( n - m ) % k == 0 ) NEW_LINE DEDENT def countNumbers ( l , r , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LI...
Program to print non square numbers | Python 3 program to print first n non - square numbers . ; Function to check perfect square ; function to print all non square number ; variable which stores the count ; Not perfect square ; Driver code
import math NEW_LINE def isPerfectSquare ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT root = round ( math . sqrt ( n ) ) NEW_LINE return ( n == root * root ) NEW_LINE DEDENT def printnonsquare ( n ) : NEW_LINE INDENT count = 0 NEW_LINE i = 1 NEW_LINE while ( count < n ) : NEW_LINE...
Program to print non square numbers | Python 3 program to print first n non - square numbers . ; Returns n - th non - square number . ; loop to print non squares below n ; Driver code
import math NEW_LINE def nonsquare ( n ) : NEW_LINE INDENT return n + ( int ) ( 0.5 + math . sqrt ( n ) ) NEW_LINE DEDENT def printNonSquare ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( nonsquare ( i ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT n = 10 NEW_LINE printNonSquare ( n ) NEW_LINE
Ludic Numbers | Returns a list containing all Ludic numbers smaller than or equal to n . ; ludics list contain all the ludic numbers ; Here we have to start with index 1 and will remove nothing from the list ; Here first item should be included in the list and the deletion is referred by this first item in the loop . ;...
def getLudic ( n ) : NEW_LINE INDENT ludics = [ ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ludics . append ( i ) NEW_LINE DEDENT index = 1 NEW_LINE while ( index != len ( ludics ) ) : NEW_LINE INDENT first_ludic = ludics [ index ] NEW_LINE remove_index = index + first_ludic NEW_LINE while ( remove_index ...
Prime Triplet | function to detect prime number using sieve method https : www . geeksforgeeks . org / sieve - of - eratosthenes / to detect prime number ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; function to print prime triplets ; Finding all primes from 1 to n ; triplets of for...
def sieve ( n , prime ) : NEW_LINE INDENT p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT i = p * 2 NEW_LINE while ( i <= n ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE i = i + p NEW_LINE DEDENT DEDENT p = p + 1 NEW_LINE DEDENT DEDENT def printPrimeTriplets ( n ) :...
Program to compare two fractions | Get max of the two fractions ; Declare nume1 and nume2 for get the value of first numerator and second numerator ; Compute ad - bc ; Driver Code
def maxFraction ( first , sec ) : NEW_LINE INDENT a = first [ 0 ] ; b = first [ 1 ] NEW_LINE c = sec [ 0 ] ; d = sec [ 1 ] NEW_LINE Y = a * d - b * c NEW_LINE return first if Y else sec NEW_LINE DEDENT first = ( 3 , 2 ) NEW_LINE sec = ( 3 , 4 ) NEW_LINE res = maxFraction ( first , sec ) NEW_LINE print ( str ( res [ 0 ]...
Find the nearest odd and even perfect squares of odd and even array elements respectively | Python3 program for the above approach ; Function to find the nearest even and odd perfect squares for even and odd array elements ; Traverse the array ; Calculate square root of current array element ; If both are of same parit...
import math NEW_LINE def nearestPerfectSquare ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT sr = int ( math . sqrt ( arr [ i ] ) ) NEW_LINE if ( ( sr & 1 ) == ( arr [ i ] & 1 ) ) : NEW_LINE INDENT print ( sr * sr , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT sr += 1 NEW_LINE print ( sr *...
Program to check if N is a Pentagonal Number | python3 program to check pentagonal numbers . ; Function to determine if N is pentagonal or not . ; Substitute values of i in the formula . ; Driver method
import math NEW_LINE def isPentagonal ( N ) : NEW_LINE INDENT i = 1 NEW_LINE while True : NEW_LINE INDENT M = ( 3 * i * i - i ) / 2 NEW_LINE i += 1 NEW_LINE if ( M >= N ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ( M == N ) NEW_LINE DEDENT N = 12 NEW_LINE if ( isPentagonal ( N ) ) : NEW_LINE INDENT print ( ...
Sum of fourth powers of the first n natural numbers | Python3 Program to find the sum of forth powers of first n natural numbers ; Return the sum of forth power of first n natural numbers ; Driver method
import math NEW_LINE def fourthPowerSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum = sum + ( i * i * i * i ) NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 6 NEW_LINE print ( fourthPowerSum ( n ) ) NEW_LINE
Sum of fourth powers of the first n natural numbers | Python3 Program to find the sum of forth powers of first n natural numbers ; Return the sum of forth power of first n natural numbers ; Driver method
import math NEW_LINE def fourthPowerSum ( n ) : NEW_LINE INDENT return ( ( 6 * n * n * n * n * n ) + ( 15 * n * n * n * n ) + ( 10 * n * n * n ) - n ) / 30 NEW_LINE DEDENT n = 6 NEW_LINE print ( fourthPowerSum ( n ) ) NEW_LINE
Find unit digit of x raised to power y | Python3 code to find the unit digit of x raised to power y . ; Find unit digit ; Get last digit of x ; Last cyclic modular value ; Here we simply return the unit digit or the power of a number ; Driver code ; Get unit digit number here we pass the unit digit of x and the last cy...
import math NEW_LINE def unitnumber ( x , y ) : NEW_LINE INDENT x = x % 10 NEW_LINE if y != 0 : NEW_LINE INDENT y = y % 4 + 4 NEW_LINE DEDENT return ( ( ( int ) ( math . pow ( x , y ) ) ) % 10 ) NEW_LINE DEDENT x = 133 ; y = 5 NEW_LINE print ( unitnumber ( x , y ) ) NEW_LINE
Aliquot sum | Function to calculate sum of all proper divisors ; Driver Code
def aliquotSum ( n ) : NEW_LINE INDENT sm = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT sm = sm + i NEW_LINE DEDENT DEDENT return sm NEW_LINE DEDENT n = 12 NEW_LINE print ( aliquotSum ( n ) ) NEW_LINE
Average of Squares of Natural Numbers | Function to get the average ; Driver Code
def AvgofSquareN ( n ) : NEW_LINE INDENT return ( ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ; NEW_LINE DEDENT n = 2 ; NEW_LINE print ( AvgofSquareN ( n ) ) ; NEW_LINE
Program to implement Simpson 's 3/8 rule | Given function to be integrated ; Function to perform calculations ; Calculates value till integral limit ; driver function
def func ( x ) : NEW_LINE INDENT return ( float ( 1 ) / ( 1 + x * x ) ) NEW_LINE DEDENT def calculate ( lower_limit , upper_limit , interval_limit ) : NEW_LINE INDENT interval_size = ( float ( upper_limit - lower_limit ) / interval_limit ) NEW_LINE sum = func ( lower_limit ) + func ( upper_limit ) ; NEW_LINE for i in r...
Container with Most Water | Python3 code for Max Water Container ; Calculating the max area ; Driver code
def maxArea ( A , Len ) : NEW_LINE INDENT area = 0 NEW_LINE for i in range ( Len ) : NEW_LINE INDENT for j in range ( i + 1 , Len ) : NEW_LINE INDENT area = max ( area , min ( A [ j ] , A [ i ] ) * ( j - i ) ) NEW_LINE DEDENT DEDENT return area NEW_LINE DEDENT a = [ 1 , 5 , 4 , 3 ] NEW_LINE b = [ 3 , 1 , 2 , 4 , 5 ] NE...
Program for focal length of a lens | Function to determine the focal length of a lens ; Variable to store the distance between the lens and the image ; Variable to store the distance between the lens and the object
def focal_length ( image_distance , object_distance ) NEW_LINE INDENT : return 1 / ( ( 1 / image_distance ) + ( 1 / object_distance ) ) NEW_LINE DEDENT image_distance = 2 NEW_LINE object_distance = 50 NEW_LINE result = focal_length ( image_distance , object_distance ) NEW_LINE print ( " Focal ▁ length ▁ of ▁ a ▁ lens ▁...
Count numbers in range L | check if the number is divisible by the digits . ; function to calculate the number of numbers ; Driver function
def check ( n ) : NEW_LINE INDENT m = n NEW_LINE while ( n != 0 ) : NEW_LINE INDENT r = n % 10 NEW_LINE if ( r > 0 ) : NEW_LINE INDENT if ( ( m % r ) != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = n // 10 NEW_LINE DEDENT return True NEW_LINE DEDENT def count ( l , r ) : NEW_LINE INDENT ans = 0 NEW_LIN...
Sum of the Series 1 / ( 1 * 2 ) + 1 / ( 2 * 3 ) + 1 / ( 3 * 4 ) + 1 / ( 4 * 5 ) + . . . . . | Function to find the sum of given series ; Computing sum term by term ; Driver function
def sumOfTheSeries ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum += 1.0 / ( i * ( i + 1 ) ) ; NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ans = sumOfTheSeries ( 10 ) NEW_LINE print ( round ( ans , 6 ) ) NEW_LINE DEDENT
Sum of series ( n / 1 ) + ( n / 2 ) + ( n / 3 ) + ( n / 4 ) + ... ... . + ( n / n ) | Python 3 program to find sum of given series ; function to find sum of series ; driver code
import math NEW_LINE def sum ( n ) : NEW_LINE INDENT root = ( int ) ( math . sqrt ( n ) ) NEW_LINE ans = 0 NEW_LINE for i in range ( 1 , root + 1 ) : NEW_LINE INDENT ans = ans + n // i NEW_LINE DEDENT ans = 2 * ans - ( root * root ) NEW_LINE return ans NEW_LINE DEDENT n = 35 NEW_LINE print ( sum ( n ) ) NEW_LINE
Sum of the series 2 + ( 2 + 4 ) + ( 2 + 4 + 6 ) + ( 2 + 4 + 6 + 8 ) + Γ’ €¦ Γ’ €¦ + ( 2 + 4 + 6 + 8 + Γ’ €¦ . + 2 n ) | function to find the sum of the given series ; sum of 1 st n natural numbers ; sum of squares of 1 st n natural numbers ; required sum ; Driver program to test above
def sumOfTheSeries ( n ) : NEW_LINE INDENT sum_n = int ( ( n * ( n + 1 ) / 2 ) ) ; NEW_LINE sum_sq_n = int ( ( n * ( n + 1 ) / 2 ) * ( 2 * n + 1 ) / 3 ) NEW_LINE return ( sum_n + sum_sq_n ) ; NEW_LINE DEDENT n = 5 NEW_LINE ans = sumOfTheSeries ( n ) NEW_LINE print ( ans ) NEW_LINE
Sum of squares of binomial coefficients | Return the sum of square of binomial coefficient ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Finding the sum of square of binomial coefficient . ; Driver Code
def sumofsquare ( n ) : NEW_LINE INDENT C = [ [ 0 for i in range ( n + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT for j in range ( 0 , min ( i , n ) + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT C ...
Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | Python3 Program to find sum of series 1 + 2 + 2 + 3 + . . . + n ; Function that find sum of series . ; Driver method ; Function call
import math NEW_LINE def sumOfSeries ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum = sum + i * i NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 10 NEW_LINE print ( sumOfSeries ( n ) ) NEW_LINE
Find sum of even index binomial coefficients | Python Program to find sum of even index term ; Return the sum of even index term ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Finding sum of even index term ; Driver method
import math NEW_LINE def evenSum ( n ) : NEW_LINE INDENT C = [ [ 0 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT for j in range ( 0 , min ( i , n + 1 ) ) : NEW_LINE INDENT if j == 0 or j == i : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_L...
Program to print triangular number series till n | Function to find triangular number ; Driver code
def triangular_series ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( i * ( i + 1 ) // 2 , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE triangular_series ( n ) NEW_LINE
Check if a number can be written as sum of three consecutive integers | function to check if a number can be written as sum of three consecutive integers . ; if n is multiple of 3 ; else print " - 1" . ; Driver Code
def checksum ( n ) : NEW_LINE INDENT n = int ( n ) NEW_LINE if n % 3 == 0 : NEW_LINE INDENT print ( int ( n / 3 - 1 ) , " ▁ " , int ( n / 3 ) , " ▁ " , int ( n / 3 + 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT n = 6 NEW_LINE checksum ( n ) NEW_LINE
Sum of all divisors from 1 to n | Python3 code to find sum of all divisor of number up to 'n ; Utility function to find sum of all divisor of number up to 'n ; Driver code
' NEW_LINE ' NEW_LINE def divisorSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum += int ( n / i ) * i NEW_LINE DEDENT return int ( sum ) NEW_LINE DEDENT n = 4 NEW_LINE print ( divisorSum ( n ) ) NEW_LINE n = 5 NEW_LINE print ( divisorSum ( n ) ) NEW_LINE
Sum of all divisors from 1 to n | ; t1 = i * ( num / i - i + 1 ) adding i every time it appears with numbers greater than or equal to itself t2 = ( ( ( num / i ) * ( num / i + 1 ) ) / 2 ) - ( ( i * ( i + 1 ) ) / 2 ) adding numbers that appear with i and are greater than i ; Driver code
import math NEW_LINE def sum_all_divisors ( num ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( 1 , math . floor ( math . sqrt ( num ) ) + 1 ) : NEW_LINE INDENT sum += t1 + t2 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT n = 1 NEW_LINE sum = sum_all_divisors ( n ) NEW_LINE print ( sum ) NEW_LINE