text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Check if LCM of array elements is divisible by a prime number or not | Function to check any number of array is divisible by k or not ; If any array element is divisible by k , then LCM of whole array should also be divisible . ; Driver Code
def func ( a , k , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( a [ i ] % k == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT a = [ 14 , 27 , 38 , 76 , 84 ] NEW_LINE k = 19 NEW_LINE res = func ( a , k , 5 ) NEW_LINE if ( res ) : NEW_LINE INDENT print ( " true " ) NEW_LINE DEDEN...
Find the closest and smaller tidy number | Python 3 program to find closest tidy number smaller than the given number ; check whether string violates tidy property ; if string violates tidy property , then decrease the value stored at that index by 1 and replace all the value stored right to that index by 9 ; Driver co...
def tidyNum ( str , len ) : NEW_LINE INDENT for i in range ( len - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] > str [ i + 1 ] ) : NEW_LINE INDENT str [ i ] -= 1 NEW_LINE for j in range ( i + 1 , len ) : NEW_LINE INDENT str [ j ] = 9 NEW_LINE DEDENT DEDENT DEDENT return str NEW_LINE DEDENT str = [ 1 , 1 , 3 , 3 , ...
Count of m digit integers that are divisible by an integer n | Returns count of m digit numbers having n as divisor ; Generating largest number of m digit ; Generating largest number of m - 1 digit ; returning number of dividend ; Driver code
def findCount ( m , n ) : NEW_LINE INDENT num1 = 0 NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT num1 = ( num1 * 10 ) + 9 NEW_LINE DEDENT num2 = 0 NEW_LINE for i in range ( 0 , ( m - 1 ) ) : NEW_LINE INDENT num2 = ( num2 * 10 ) + 9 NEW_LINE DEDENT return int ( ( num1 / n ) - ( num2 / n ) ) NEW_LINE DEDENT m = 2 ;...
Find the n | function to calculate nth number made of even digits only ; variable to note how many such numbers have been found till now ; bool variable to check if 1 , 3 , 5 , 7 , 9 is there or not ; checking each digit of the number ; If 1 , 3 , 5 , 7 , 9 is found temp is changed to false ; temp is true it means that...
def findNthEvenDigitNumber ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( True ) : NEW_LINE INDENT curr = i ; NEW_LINE isCurrEvenDigit = True ; NEW_LINE while ( curr != 0 ) : NEW_LINE INDENT if ( curr % 10 == 1 or curr % 10 == 3 or curr % 10 == 5 or curr % 10 == 7 or curr % 10 == 9 ) : NEW_LINE I...
Find the n | function to find nth number made of even digits only ; If n = 1 return 0 ; vector to store the digits when converted into base 5 ; Reduce n to n - 1 to exclude 0 ; Reduce n to base 5 number and store digits ; pushing the digits into vector ; variable to represent the number after converting it to base 5. S...
def findNthEvenDigitNumber ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT v = [ ] NEW_LINE n = n - 1 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT v . append ( n % 5 ) NEW_LINE n = n // 5 NEW_LINE DEDENT result = 0 NEW_LINE for i in range ( len ( v ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT re...
Check if a large number is divisible by 25 or not | Function to find that number divisible by 25 or not . ; If length of string is single digit then it 's not divisible by 25 ; Driver code
def isDivisibleBy25 ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( ( int ) ( st [ n - 1 ] ) == 0 and ( ( int ) ( st [ n - 2 ] ) == 0 ) or ( ( int ) ( st [ n - 2 ] ) * 10 + ( int ) ( st [ n - 1 ] ) % 25 == 0 ) ) NEW_LINE DEDENT st = "76955" NEW_LINE...
Check a large number is divisible by 16 or not | Function to find that number divisible by 16 or not ; Empty string ; If there is double digit ; If there is triple digit ; If number formed by last four digits is divisible by 16. ; Driver code
def check ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE if ( n == 0 and n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return ( ( int ) ( st [ n - 2 ] ) * 10 + ( ( int ) ( st [ n - 1 ] ) % 16 == 0 ) ) NEW_LINE DEDENT if ( n == 3 ) : NEW_LINE INDENT return ( ( ( int ) ( st [ n...
Find Index of given fibonacci number in constant time | A simple Python 3 program to find index of given Fibonacci number . ; if Fibonacci number is less than 2 , its index will be same as number ; iterate until generated fibonacci number is less than given fibonacci number ; res keeps track of number of generated fibo...
def findIndex ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT a = 0 NEW_LINE b = 1 NEW_LINE c = 1 NEW_LINE res = 1 NEW_LINE while ( c < n ) : NEW_LINE INDENT c = a + b NEW_LINE res = res + 1 NEW_LINE a = b NEW_LINE b = c NEW_LINE DEDENT return res NEW_LINE DEDENT result = findIndex ( 21...
Date after adding given number of days to the given date | Return if year is leap year or not . ; Given a date , returns number of days elapsed from the beginning of the current year ( 1 stjan ) . ; Given a year and days elapsed in it , finds date by storing results in d and m . ; Add x days to the given date . ; y2 is...
def isLeap ( y ) : NEW_LINE INDENT if ( y % 100 != 0 and y % 4 == 0 or y % 400 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def offsetDays ( d , m , y ) : NEW_LINE INDENT offset = d NEW_LINE switcher = { 10 : 30 , 9 : 31 , 8 : 30 , 7 : 31 , 6 : 31 , 5 : 30 , 4 : 31 , 3 : 30 , 2 : 31...
Determine whether a given number is a Hyperperfect Number | Python3 program to check whether a given number is k - hyperperfect ; Function to find the sum of all proper divisors ( excluding 1 and N ) ; Iterate only until sqrt N as we are going to generate pairs to produce divisors ; As divisors occur in pairs , we can ...
import math NEW_LINE def divisorSum ( N , K ) : NEW_LINE INDENT Sum = 0 NEW_LINE for i in range ( 2 , math . ceil ( math . sqrt ( N ) ) ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT Sum += ( i + int ( N / i ) ) NEW_LINE DEDENT DEDENT return Sum NEW_LINE DEDENT def isPrime ( n ) : NEW_LINE INDENT if ( n == 1 o...
Given a number n , find the first k digits of n ^ n | Python3 program to generate k digits of n ^ n ; function to calculate first k digits of n ^ n ; take log10 of n ^ n . log10 ( n ^ n ) = n * log10 ( n ) ; We now try to separate the decimal and integral part of the / product . The floor function returns the smallest ...
import math NEW_LINE def firstkdigits ( n , k ) : NEW_LINE INDENT product = n * math . log ( n , 10 ) ; NEW_LINE decimal_part = product - math . floor ( product ) ; NEW_LINE decimal_part = pow ( 10 , decimal_part ) ; NEW_LINE digits = pow ( 10 , k - 1 ) ; NEW_LINE return math . floor ( decimal_part * digits ) ; NEW_LIN...
Generate k digit numbers with digits in strictly increasing order | number -- > Current value of number . x -- > Current digit to be considered k -- > Remaining number of digits ; Try all possible greater digits ; Generates all well ordered numbers of length k . ; Driver code
def printWellOrdered ( number , x , k ) : NEW_LINE INDENT if ( k == 0 ) : NEW_LINE INDENT print ( number , end = " ▁ " ) NEW_LINE return NEW_LINE DEDENT for i in range ( ( x + 1 ) , 10 ) : NEW_LINE INDENT printWellOrdered ( number * 10 + i , i , k - 1 ) NEW_LINE DEDENT DEDENT def generateWellOrdered ( k ) : NEW_LINE IN...
Multiply large integers under large modulo | Returns ( a * b ) % mod ; Update a if it is more than or equal to mod ; If b is odd , add a with result ; Here we assume that doing 2 * a doesn 't cause overflow ; b >>= 1 ; b = b / 2 ; Driver Code
def moduloMultiplication ( a , b , mod ) : NEW_LINE INDENT a = a % mod ; NEW_LINE while ( b ) : NEW_LINE INDENT if ( b & 1 ) : NEW_LINE INDENT res = ( res + a ) % mod ; NEW_LINE DEDENT a = ( 2 * a ) % mod ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT a = 10123465234878998 ; NEW_LINE b = 65746311545646431 ; NEW_LINE m ...
Number of occurrences of 2 as a digit in numbers from 0 to n | Write Python3 code here ; Driver code
def numberOf2sinRange ( n ) : NEW_LINE INDENT s = " " NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT s += str ( i ) NEW_LINE DEDENT return ( list ( s ) . count ( '2' ) ) NEW_LINE DEDENT n = 30 NEW_LINE print ( numberOf2sinRange ( n ) ) NEW_LINE
Number of occurrences of 2 as a digit in numbers from 0 to n | Counts the number of 2 s in a number at d - th digit ; if the digit in spot digit is ; Counts the number of '2' digits between 0 and n ; Convert integer to String to find its length ; Traverse every digit and count for every digit ; Driver Code
def count2sinRangeAtDigit ( number , d ) : NEW_LINE INDENT powerOf10 = int ( pow ( 10 , d ) ) ; NEW_LINE nextPowerOf10 = powerOf10 * 10 ; NEW_LINE right = number % powerOf10 ; NEW_LINE roundDown = number - number % nextPowerOf10 ; NEW_LINE roundup = roundDown + nextPowerOf10 ; NEW_LINE digit = ( number // powerOf10 ) %...
Modulo 10 ^ 9 + 7 ( 1000000007 ) | ; f = f * i WRONG APPROACH as f may exceed ( 2 ^ 64 - 1 )
def factorial ( n ) : NEW_LINE INDENT M = 1000000007 NEW_LINE f = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE return f % M NEW_LINE DEDENT
Modulo 10 ^ 9 + 7 ( 1000000007 ) | ; f = ( f * i ) % M Now f never can exceed 10 ^ 9 + 7
def factorial ( n ) : NEW_LINE INDENT M = 1000000007 NEW_LINE f = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE return f NEW_LINE DEDENT
Modulo 10 ^ 9 + 7 ( 1000000007 ) |
def mod ( a , m ) : NEW_LINE INDENT return ( a % m + m ) % m NEW_LINE DEDENT
Program to find Star number | Returns n - th star number ; Driver code
def findStarNum ( n ) : NEW_LINE INDENT return ( 6 * n * ( n - 1 ) + 1 ) NEW_LINE DEDENT n = 3 NEW_LINE print ( findStarNum ( n ) ) NEW_LINE
Check if a large number is divisible by 5 or not | Function to find that number divisible by 5 or not . The function assumes that string length is at least one . ; Driver code
def isDivisibleBy5 ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE return ( ( st [ n - 1 ] == '0' ) or ( st [ n - 1 ] == '5' ) ) NEW_LINE DEDENT st = "76955" NEW_LINE if isDivisibleBy5 ( st ) : NEW_LINE INDENT print " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT print " No ▁ " NEW_LINE DEDENT
Tidy Number ( Digits in non | Returns true if num is Tidy ; To store previous digit ( Assigning initial value which is more than any digit ) ; Traverse all digits from right to left and check if any digit is smaller than previous . ; Driver code
def isTidy ( num ) : NEW_LINE INDENT prev = 10 NEW_LINE while ( num ) : NEW_LINE INDENT rem = num % 10 NEW_LINE num /= 10 NEW_LINE if rem > prev : NEW_LINE INDENT return False NEW_LINE DEDENT prev = rem NEW_LINE DEDENT return True NEW_LINE DEDENT num = 1556 NEW_LINE if isTidy ( num ) : NEW_LINE INDENT print ( " Yes " )...
Nth Square free number | Function to find nth square free number ; To maintain count of square free number ; Loop for square free numbers ; Checking whether square of a number is divisible by any number which is a perfect square ; If number is square free ; If the cnt becomes n , return the number ; Driver Code
def squareFree ( n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE i = 1 ; NEW_LINE while ( True ) : NEW_LINE INDENT isSqFree = True ; NEW_LINE j = 2 ; NEW_LINE while ( j * j <= i ) : NEW_LINE INDENT if ( i % ( j * j ) == 0 ) : NEW_LINE INDENT isSqFree = False ; NEW_LINE break ; NEW_LINE DEDENT j += 1 ; NEW_LINE DEDENT if ( isS...
Find if n can be written as product of k numbers | Python3 program to find if it is possible to write a number n as product of exactly k positive numbers greater than 1. ; Prints k factors of n if n can be written as multiple of k numbers . Else prints - 1 ; list to store all prime factors of n ; insert all 2 's in lis...
import math as mt NEW_LINE def kFactors ( n , k ) : NEW_LINE INDENT a = list ( ) NEW_LINE while n % 2 == 0 : NEW_LINE INDENT a . append ( 2 ) NEW_LINE n = n // 2 NEW_LINE DEDENT for i in range ( 3 , mt . ceil ( mt . sqrt ( n ) ) , 2 ) : NEW_LINE INDENT while n % i == 0 : NEW_LINE INDENT n = n / i ; NEW_LINE a . append ...
Largest number smaller than or equal to n and digits in non | Returns the required number ; loop to recursively check the numbers less than or equal to given number ; Keep traversing digits from right to left . For every digit check if it is smaller than prev_dig ; We found the required number ; Driver Code
def nondecdigits ( n ) : NEW_LINE INDENT x = 0 NEW_LINE for x in range ( n , 0 , - 1 ) : NEW_LINE INDENT no = x NEW_LINE prev_dig = 11 NEW_LINE flag = True NEW_LINE while ( no != 0 ) : NEW_LINE INDENT if ( prev_dig < no % 10 ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT prev_dig = no % 10 NEW_LINE no ...
Largest number smaller than or equal to n and digits in non | Prints the largest number smaller than s and digits in non - decreasing order . ; array to store digits of number ; conversion of characters of string int number ; variable holds the value of index after which all digits are set 9 ; Checking the condition if...
def nondecdigits ( s ) : NEW_LINE INDENT m = len ( s ) ; NEW_LINE a = [ 0 ] * m ; NEW_LINE for i in range ( m ) : NEW_LINE INDENT a [ i ] = ord ( s [ i ] ) - ord ( '0' ) ; NEW_LINE DEDENT level = m - 1 ; NEW_LINE for i in range ( m - 1 , 0 , - 1 ) : NEW_LINE INDENT if ( a [ i ] < a [ i - 1 ] ) : NEW_LINE INDENT a [ i -...
Count Divisors of n in O ( n ^ 1 / 3 ) | Python3 implementation of Naive method to count all divisors ; function to count the divisors ; If divisors are equal , count only one ; else : Otherwise count both ; Driver program to test above function
import math NEW_LINE def countDivisors ( 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 INDENT if ( n / i == i ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE cnt = cnt + 2 NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT...
Check if the door is open or closed | Python 3 implementation of doors open or closed ; Function to check whether ' n ' has even number of factors or not ; if ' n ' is a perfect square it has odd number of factors ; else ' n ' has even number of factors ; Function to find and print status of each door ; If even number ...
import math NEW_LINE def hasEvenNumberOfFactors ( n ) : NEW_LINE INDENT root_n = math . sqrt ( n ) NEW_LINE if ( ( root_n * root_n ) == n ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def printStatusOfDoors ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( hasEve...
Check if frequency of each digit is less than the digit | Function to validate number ( Check iffrequency of a digit is less than thedigit itself or not ) ; If current digit of temp is same as i ; if frequency is greater than digit value , return false ; Driver Code
def validate ( n ) : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT temp = n ; NEW_LINE count = 0 ; NEW_LINE while ( temp ) : NEW_LINE INDENT if ( temp % 10 == i ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( count > i ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT temp //= 10 ; NEW_LINE DEDENT DEDENT...
Check if a larger number divisible by 36 | Function to check whether a number is divisible by 36 or not ; null number cannot be divisible by 36 ; single digit number other than 0 is not divisible by 36 ; number formed by the last 2 digits ; if number is not divisible by 4 ; number is divisible by 4 calculate sum of dig...
def divisibleBy36 ( num ) : NEW_LINE INDENT l = len ( num ) NEW_LINE if ( l == 0 ) : NEW_LINE INDENT return ( " No " ) NEW_LINE DEDENT if ( l == 1 and num [ 0 ] != '0' ) : NEW_LINE INDENT return ( " No " ) NEW_LINE DEDENT two_digit_num = ( ( ( int ) ( num [ l - 2 ] ) ) * 10 + ( int ) ( num [ l - 1 ] ) ) NEW_LINE if ( t...
Check if a large number is divisible by 8 or not | Function to find that number divisible by 8 or not ; Empty string ; If there is single digit ; If there is double digit ; If number formed by last three digits is divisible by 8. ; Driver code
def check ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return ( ( int ) ( st [ 0 ] ) % 8 == 0 ) NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return ( ( int ) ( st [ n - 2 ] ) * 10 + ( ( int ) ( str [ n - 1 ] ) % 8 == 0 )...
Prime points ( Points that split a number into two primes ) | Function to count number of digits ; Function to check whether a number is prime or not . Returns 0 if prime else - 1 ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to print prime points ; counting digits ; ...
def countDigits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += 1 NEW_LINE n = n // 10 NEW_LINE DEDENT return count NEW_LINE DEDENT def checkPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return 0 NEW_LINE DE...
Find ways an Integer can be expressed as sum of n | Function to calculate and return the power of any given number ; Function to check power representations recursively ; Initialize number of ways to express x as n - th powers of different natural numbers ; Calling power of ' i ' raised to 'n ; Recursively check all gr...
def power ( num , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( n % 2 == 0 ) : NEW_LINE INDENT return power ( num , n // 2 ) * power ( num , n // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return num * power ( num , n // 2 ) * power ( num , n // 2 ) NEW_LINE DEDENT DEDENT def che...
Number Theory | Generators of finite cyclic group under addition | Function to return gcd of a and b ; Print generators of n ; 1 is always a generator ; A number x is generator of GCD is 1 ; 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 printGenerators ( n ) : NEW_LINE INDENT print ( "1" , end = " ▁ " ) ; NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( gcd ( i , n ) == 1 ) : NEW_LINE INDENT print ( i , ...
Check if a large number is divisible by 3 or not | Function to find that number divisible by 3 or not ; Compute sum of digits ; Check if sum of digits is divisible by 3. ; main function
def check ( num ) : NEW_LINE INDENT digitSum = 0 NEW_LINE while num > 0 : NEW_LINE INDENT rem = num % 10 NEW_LINE digitSum = digitSum + rem NEW_LINE num = num / 10 NEW_LINE DEDENT return ( digitSum % 3 == 0 ) NEW_LINE DEDENT num = 1332 NEW_LINE if ( check ( num ) ) : NEW_LINE INDENT print " Yes " NEW_LINE DEDENT else :...
Count all perfect divisors of a number | Below is Python3 code to count total perfect divisors ; Pre - compute counts of all perfect divisors of all numbers upto MAX . ; Iterate through all the multiples of i * i ; Increment all such multiples by 1 ; Returns count of perfect divisors of n . ; Driver code
MAX = 100001 NEW_LINE perfectDiv = [ 0 ] * MAX NEW_LINE def precomputeCounts ( ) : NEW_LINE INDENT i = 1 NEW_LINE while i * i < MAX : NEW_LINE INDENT for j in range ( i * i , MAX , i * i ) : NEW_LINE INDENT perfectDiv [ j ] += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT def countPerfectDivisors ( n ) : NEW_LINE IND...
Prime Factorization using Sieve O ( log n ) for multiple queries | Python3 program to find prime factorization of a number n in O ( Log n ) time with precomputation allowed . ; stores smallest prime factor for every number ; Calculating SPF ( Smallest Prime Factor ) for every number till MAXN . Time Complexity : O ( nl...
import math as mt NEW_LINE MAXN = 100001 NEW_LINE spf = [ 0 for i in range ( MAXN ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT spf [ 1 ] = 1 NEW_LINE for i in range ( 2 , MAXN ) : NEW_LINE INDENT spf [ i ] = i NEW_LINE DEDENT for i in range ( 4 , MAXN , 2 ) : NEW_LINE INDENT spf [ i ] = 2 NEW_LINE DEDENT for i in range...
Nearest element with at | Python3 program to print nearest element with at least one common prime factor . ; Pre - computation of smallest prime divisor of all numbers ; Prime number will have same divisor ; Function to calculate all divisors of input array ; Pre - compute all the divisors of array element by using pri...
MAX = 100001 NEW_LINE INF = 10 ** 9 NEW_LINE primedivisor = [ 0 for i in range ( MAX ) ] NEW_LINE dist = [ 0 for i in range ( MAX ) ] NEW_LINE pos = [ 0 for i in range ( MAX ) ] NEW_LINE divInd = [ 0 for i in range ( MAX ) ] NEW_LINE divisors = [ [ ] for i in range ( MAX ) ] NEW_LINE def sieveOfEratosthenes ( ) : NEW_L...
Largest subsequence having GCD greater than 1 | Returns length of the largest subsequence with GCD more than 1. ; Finding the Maximum value in arr [ ] ; Iterate from 2 to maximum possible divisor of all give values ; If we found divisor , increment count ; Driver code
def largestGCDSubsequence ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE maxele = max ( arr ) NEW_LINE for i in range ( 2 , maxele + 1 ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ j ] % i == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT ans = max ( ans , count ) NEW...
Queries on the sum of prime factor counts in a range | Python3 program to find sum prime factors in given range . ; using sieve method to evaluating the prime factor of numbers ; if i is prime ; setting number of prime factor of a prime number . ; Returns sum of counts of prime factors in range from l to r . This funct...
MAX = 100006 ; NEW_LINE count = [ 0 ] * MAX ; NEW_LINE def sieve ( ) : NEW_LINE INDENT i = 2 ; NEW_LINE while ( i * i <= MAX ) : NEW_LINE INDENT if ( count [ i ] == 0 ) : NEW_LINE INDENT for j in range ( 2 * i , MAX , i ) : NEW_LINE INDENT count [ j ] += 1 ; NEW_LINE DEDENT count [ i ] = 1 ; NEW_LINE DEDENT i += 1 ; NE...
Generation of n numbers with given set of factors | Generate n numbers with factors in factor [ ] ; array of k to store next multiples of given factors ; Prints n numbers output = 0 ; Next number to print as output ; Find the next smallest multiple ; Printing minimum in each iteration print the value if output is not e...
def generateNumbers ( factor , n , k ) : NEW_LINE INDENT next = [ 0 ] * k ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT toincrement = 0 ; NEW_LINE for j in range ( k ) : NEW_LINE INDENT if ( next [ j ] < next [ toincrement ] ) : NEW_LINE INDENT toincrement = j ; NEW_LINE DEDENT DEDENT if ( output != nex...
Reversible numbers | Function to check reversible number ; Calculate reverse of n ; Calculate sum of number and its reverse ; Check for reverse number reach digit must be odd ; Driver Code
def checkReversible ( n ) : NEW_LINE INDENT rev = 0 NEW_LINE flag = n NEW_LINE while ( flag != 0 ) : NEW_LINE INDENT rem = flag % 10 NEW_LINE rev *= 10 NEW_LINE rev += rem NEW_LINE flag //= 10 NEW_LINE DEDENT sum = rev + n NEW_LINE while ( sum and ( ( rem % 2 ) != 0 ) ) : NEW_LINE INDENT rem = sum % 10 NEW_LINE sum //=...
Multiplicative order | function for GCD ; Function return smallest + ve integer that holds condition A ^ k ( mod N ) = 1 ; result store power of A that rised to the power N - 1 ; modular arithmetic ; return smallest + ve integer ; increment power ; Driver program
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 def multiplicativeOrder ( A , N ) : NEW_LINE INDENT if ( GCD ( A , N ) != 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT result = 1 NEW_LINE K = 1 NEW_LINE while ( K < N ) : NEW_LINE I...
Sum of product of x and y such that floor ( n / x ) = y | Python3 program to find sum of product of x and y such that n / x = y ( Integer Division ) ; Return the sum of natural number in a range . ; n * ( n + 1 ) / 2. ; Return the sum of product x * y . ; Iterating i from 1 to sqrt ( n ) ; Finding the upper limit . ; F...
import math NEW_LINE def sumOfRange ( a , b ) : NEW_LINE INDENT i = ( a * ( a + 1 ) ) >> 1 ; NEW_LINE j = ( b * ( b + 1 ) ) >> 1 ; NEW_LINE return ( i - j ) ; NEW_LINE DEDENT def sumofproduct ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE root = int ( math . sqrt ( n ) ) ; NEW_LINE for i in range ( 1 , root + 1 ) : NEW_LIN...
Primitive root of a prime number n modulo n | Python3 program to find primitive root of a given number n ; Returns True if n is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Iterative Function to calculate ( x ^ n ) % p in O ( logy ) ; x = x % p Update x if it is more th...
from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT...
Minimum number of power terms with sum equal to n | Return minimum power terms of x required ; if x is 1 , return n since any power of 1 is 1 only . ; Consider n = a * x + b where a = n / x and b = n % x . ; Update count of powers for 1 's added ; Repeat the process for reduced n ; Driver code
def minPower ( n , x ) : NEW_LINE INDENT if ( x == 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT ans = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT ans += ( n % x ) NEW_LINE n //= x NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 5 NEW_LINE x = 3 NEW_LINE print ( minPower ( n , x ) ) NEW_LINE
Sum of Perrin Numbers | function for sum of first n Perrin number . ; if ( n == 0 ) : n = 0 ; if ( n == 1 ) : n = 1 ; if ( n == 2 ) : n = 2 ; calculate k = 5 sum of three previous step . ; Sum remaining numbers ; calculate next term ; Driver code
def calSum ( n ) : NEW_LINE INDENT a = 3 NEW_LINE b = 0 NEW_LINE c = 2 NEW_LINE INDENT return 3 NEW_LINE return 3 NEW_LINE return 5 NEW_LINE DEDENT sum = 5 NEW_LINE while ( n > 2 ) : NEW_LINE INDENT d = a + b NEW_LINE sum = sum + d NEW_LINE a = b NEW_LINE b = c NEW_LINE c = d NEW_LINE n = n - 1 NEW_LINE DEDENT return s...
Print the kth common factor of two numbers | Returns k 'th common factor of x and y. ; Find smaller of two numbers ; Count common factors until we either reach small or count becomes k . ; If we reached small ; Driver code
def findKHCF ( x , y , k ) : NEW_LINE INDENT small = min ( x , y ) NEW_LINE count = 1 NEW_LINE for i in range ( 2 , small + 1 ) : NEW_LINE INDENT if ( x % i == 0 and y % i == 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT if ( count == k ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE D...
Find minimum number to be divided to make a number a perfect square | Python program to find minimum number which divide n to make it a perfect square . ; Return the minimum number to be divided to make n a perfect square . ; Since 2 is only even prime , compute its power separately . ; If count is odd , it must be rem...
import math NEW_LINE def findMinNumber ( n ) : NEW_LINE INDENT count = 0 NEW_LINE ans = 1 NEW_LINE while n % 2 == 0 : NEW_LINE INDENT count += 1 NEW_LINE n //= 2 NEW_LINE DEDENT if count % 2 is not 0 : NEW_LINE INDENT ans *= 2 NEW_LINE DEDENT for i in range ( 3 , ( int ) ( math . sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDEN...
Program to implement Collatz Conjecture | Function to find if n reaches to 1 or not . ; If there is a cycle formed , we can 't reach 1. ; If n is odd then pass n = 3 n + 1 else n = n / 2 ; Wrapper over isToOneRec ( ) ; To store numbers visited using recursive calls . ; Driver Code
def isToOneRec ( n : int , s : set ) -> bool : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return True NEW_LINE DEDENT if n in s : NEW_LINE INDENT return False NEW_LINE DEDENT if n % 2 : NEW_LINE INDENT return isToOneRec ( 3 * n + 1 , s ) NEW_LINE DEDENT else : NEW_LINE INDENT return isToOneRec ( n // 2 , s ) NEW_LINE ...
Program to implement Collatz Conjecture | Function to find if n reaches to 1 or not . ; Return true if n is positive ; Drivers code
def isToOne ( n ) : NEW_LINE INDENT return ( n > 0 ) NEW_LINE DEDENT n = 5 NEW_LINE if isToOne ( n ) == True : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
GCD of two numbers formed by n repeating x and y times | Return the Greatest common Divisor of two numbers . ; Prints Greatest Common Divisor of number formed by n repeating x times and y times . ; Finding GCD of x and y . ; Print n , g times . ; 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 findgcd ( n , x , y ) : NEW_LINE INDENT g = gcd ( x , y ) NEW_LINE for i in range ( g ) : NEW_LINE INDENT print ( n ) NEW_LINE DEDENT DEDENT n = 123 NEW_LINE x = 5 NEW_LINE y = 2 NEW...
Count natural numbers whose factorials are divisible by x but not y | GCD function to compute the greatest divisor among a and b ; Returns first number whose factorial is divisible by x . ; Result ; Remove common factors ; We found first i . ; Count of natural numbers whose factorials are divisible by x but not y . ; R...
def gcd ( a , b ) : NEW_LINE INDENT if ( ( a % b ) == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def firstFactorialDivisibleNumber ( x ) : NEW_LINE INDENT i = 1 NEW_LINE new_x = x NEW_LINE for i in range ( 1 , x ) : NEW_LINE INDENT new_x /= gcd ( i , new_x ) NEW_LINE if ( ne...
Find the first natural number whose factorial is divisible by x | Returns first number whose factorial divides x . ; i = 1 ; Result ; Driver code
def firstFactorialDivisibleNumber ( x ) : NEW_LINE INDENT fact = 1 ; NEW_LINE for i in range ( 1 , x ) : NEW_LINE INDENT fact = fact * i NEW_LINE if ( fact % x == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return i NEW_LINE DEDENT x = 16 NEW_LINE print ( firstFactorialDivisibleNumber ( x ) ) NEW_LINE
Find two prime numbers with given sum | 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 not changed , then it is a prime ; Update all multiples of p ; ...
def SieveOfEratosthenes ( n , isPrime ) : NEW_LINE INDENT isPrime [ 0 ] = isPrime [ 1 ] = False NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT isPrime [ i ] = True NEW_LINE DEDENT p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( isPrime [ p ] == True ) : NEW_LINE INDENT i = p * p NEW_LINE while ( i <...
Count numbers with same first and last digits | Utility method to get first digit of x ; method to return count of numbers with same starting and ending digit from 1 upto x ; get ten - spans from 1 to x ; add 9 to consider all 1 digit numbers ; Find first and last digits ; If last digit is greater than first digit then...
def getFirstDigit ( x ) : NEW_LINE INDENT while ( x >= 10 ) : NEW_LINE INDENT x //= 10 NEW_LINE DEDENT return x NEW_LINE DEDENT def getCountWithSameStartAndEndFrom1 ( x ) : NEW_LINE INDENT if ( x < 10 ) : NEW_LINE INDENT return x NEW_LINE DEDENT tens = x // 10 NEW_LINE res = tens + 9 NEW_LINE firstDigit = getFirstDigit...
Right | 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 not changed , then it is a prime ; Update all multiples of p ; Returns true if n is right - t...
def sieveOfEratosthenes ( n , isPrime ) : NEW_LINE INDENT isPrime [ 0 ] = isPrime [ 1 ] = False NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT isPrime [ i ] = True NEW_LINE DEDENT p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( isPrime [ p ] == True ) : NEW_LINE INDENT i = p * 2 NEW_LINE while ( i <...
Mersenne Prime | Generate all prime numbers less than n . ; Initialize all entries of boolean array as true . A value in prime [ i ] will finally be false if i is Not a prime , else true bool prime [ n + 1 ] ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to generate mersenne...
def SieveOfEratosthenes ( n , prime ) : NEW_LINE INDENT for i in range ( 0 , n + 1 ) : NEW_LINE INDENT prime [ i ] = True NEW_LINE DEDENT 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...
Find sum of modulo K of first N natural number | Return sum of modulo K of first N natural numbers . ; Iterate from 1 to N && evaluating and adding i % K . ; Driver Code
def findSum ( N , K ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT ans += ( i % K ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT N = 10 ; NEW_LINE K = 2 ; NEW_LINE print ( findSum ( N , K ) ) ; NEW_LINE
Find sum of modulo K of first N natural number | Return sum of modulo K of first N natural numbers . ; Counting the number of times 1 , 2 , . . , K - 1 , 0 sequence occurs . ; Finding the number of elements left which are incomplete of sequence Leads to Case 1 type . ; adding multiplication of number of times 1 , 2 , ....
def findSum ( N , K ) : NEW_LINE INDENT ans = 0 ; NEW_LINE y = N / K ; NEW_LINE x = N % K ; NEW_LINE ans = ( ( K * ( K - 1 ) / 2 ) * y + ( x * ( x + 1 ) ) / 2 ) ; NEW_LINE return int ( ans ) ; NEW_LINE DEDENT N = 10 ; NEW_LINE K = 2 ; NEW_LINE print ( findSum ( N , K ) ) ; NEW_LINE
Smallest number to multiply to convert floating point to natural | Python program to find the smallest number to multiply to convert a floating point number into natural number . Finding GCD of two number ; Returns smallest integer k such that k * str becomes natural . str is an input floating point number ; Find size ...
import math NEW_LINE 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 def findnum ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE count_after_dot = 0 NEW_LINE dot_seen = 0 NEW_LINE num = 0 NEW_LINE for i in range ( n ) : NEW_LINE IN...
Find the maximum number of handshakes | Calculating the maximum number of handshake using derived formula . ; Driver Code
def maxHandshake ( n ) : NEW_LINE INDENT return int ( ( n * ( n - 1 ) ) / 2 ) NEW_LINE DEDENT n = 10 NEW_LINE print ( maxHandshake ( n ) ) NEW_LINE
Count digits in given number N which divide N | Utility function to check divisibility by digit ; ( N [ i ] - '0' ) gives the digit value and form the number ; Function to count digits which appears in N and divide N divide [ 10 ] -- > array which tells that particular digit divides N or not count [ 10 ] -- > counts fr...
def divisible ( N , digit ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( len ( N ) ) : NEW_LINE INDENT ans = ( ans * 10 + ( ord ( N [ i ] ) - ord ( '0' ) ) ) ; NEW_LINE ans %= digit ; NEW_LINE DEDENT return ( ans == 0 ) ; NEW_LINE DEDENT def allDigits ( N ) : NEW_LINE INDENT divide = [ False ] * 10 ; NEW_LINE ...
Aliquot Sequence | Python implementation of Optimized approach to generate Aliquot Sequence ; Function to calculate sum of all proper divisors ; Note that this loop runs till square root of n ; If divisors are equal , take only one of them ; Otherwise take both ; calculate sum of all proper divisors only ; Function to ...
from math import sqrt NEW_LINE def getSum ( n ) : NEW_LINE INDENT for i in range ( 1 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT if n // i == i : NEW_LINE INDENT summ += i NEW_LINE DEDENT else : NEW_LINE INDENT summ += i NEW_LINE summ += n // i NEW_LINE DEDENT DEDENT DEDENT return summ ...
Count numbers which can be constructed using two numbers | Returns count of numbers from 1 to n that can be formed using x and y . ; Create an auxiliary array and initialize it as false . An entry arr [ i ] = True is going to mean that i can be formed using x and y ; x and y can be formed using x and y . ; Initialize r...
def countNums ( n , x , y ) : NEW_LINE INDENT arr = [ False for i in range ( n + 2 ) ] NEW_LINE if ( x <= n ) : NEW_LINE INDENT arr [ x ] = True NEW_LINE DEDENT if ( y <= n ) : NEW_LINE INDENT arr [ y ] = True NEW_LINE DEDENT result = 0 NEW_LINE for i in range ( min ( x , y ) , n + 1 ) : NEW_LINE INDENT if ( arr [ i ] ...
Emirp numbers | Function to find reverse of any number ; Sieve method used for generating emirp number ( use of sieve ofEratosthenes ) ; 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...
def reverse ( x ) : NEW_LINE INDENT rev = 0 ; NEW_LINE while ( x > 0 ) : NEW_LINE INDENT rev = ( rev * 10 ) + x % 10 ; NEW_LINE x = int ( x / 10 ) ; NEW_LINE DEDENT return rev ; NEW_LINE DEDENT def printEmirp ( n ) : NEW_LINE INDENT prime = [ 1 ] * ( n + 1 ) ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= n ) : NEW_LINE I...
Abundant Number | An Optimized Solution to check Abundant Number in PYTHON ; Function to calculate sum of divisors ; Note that this loop runs till square root of n ; If divisors are equal , take only one of them ; else : Otherwise take both ; calculate sum of all proper divisors only ; Function to check Abundant Number...
import math NEW_LINE def getSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE i = 1 NEW_LINE while i <= ( math . sqrt ( n ) ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT if n / i == i : NEW_LINE INDENT sum = sum + i NEW_LINE sum = sum + i NEW_LINE sum = sum + ( n / i ) NEW_LINE DEDENT DEDENT i = i + 1 NEW_LINE DEDENT ...
Powerful Number | Python program to find if a number is powerful or not . ; function to check if the number is powerful ; First divide the number repeatedly by 2 ; If only 2 ^ 1 divides n ( not higher powers ) , then return false ; if n is not a power of 2 then this loop will execute repeat above process ; Find highest...
import math NEW_LINE def isPowerful ( n ) : NEW_LINE INDENT while ( n % 2 == 0 ) : NEW_LINE INDENT power = 0 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = n // 2 NEW_LINE power = power + 1 NEW_LINE DEDENT if ( power == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for factor in range ( 3 , int ( math ...
Deficient Number | Python program to implement an Optimized Solution to check Deficient Number ; Function to calculate sum of divisors ; Note that this loop runs till square root of n ; If divisors are equal , take only one of them ; else : Otherwise take both ; Function to check Deficient Number ; Check if sum ( n ) <...
import math NEW_LINE def divisorsSum ( n ) : NEW_LINE INDENT i = 1 NEW_LINE while i <= math . sqrt ( n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n / i == i ) : NEW_LINE INDENT sum = sum + i NEW_LINE sum = sum + i ; NEW_LINE sum = sum + ( n / i ) NEW_LINE DEDENT DEDENT i = i + 1 NEW_LINE DEDENT return...
Harshad ( Or Niven ) Number | Python implementation of above approach ; Converting integer to string ; Initialising sum to 0 ; Traversing through the string ; Converting character to int ; Comparing number and sum ; Driver Code ; passing this number to get result function
def checkHarshad ( n ) : NEW_LINE INDENT st = str ( n ) NEW_LINE sum = 0 NEW_LINE length = len ( st ) NEW_LINE for i in st : NEW_LINE INDENT sum = sum + int ( i ) NEW_LINE DEDENT if ( n % sum == 0 ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT number = 18 ...
Smith Number | Python program to to check whether a number is Smith Number or not . ; array to store all prime less than and equal to 10 ^ 6 ; 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 tha...
import math NEW_LINE MAX = 10000 NEW_LINE primes = [ ] NEW_LINE def sieveSundaram ( ) : NEW_LINE INDENT marked = [ 0 ] * ( ( MAX / 2 ) + 100 ) NEW_LINE i = 1 NEW_LINE while i <= ( ( math . sqrt ( MAX ) - 1 ) / 2 ) : NEW_LINE INDENT j = ( i * ( i + 1 ) ) << 1 NEW_LINE while j <= MAX / 2 : NEW_LINE INDENT marked [ j ] = ...
Kaprekar Number | Python program to check if a number is Kaprekar number or not ; Returns true if n is a Kaprekar number , else false ; Count number of digits in square ; Split the square at different poitns and see if sum of any pair of splitted numbers is equal to n . ; To avoid numbers like 10 , 100 , 1000 ( These a...
import math NEW_LINE def iskaprekar ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return True NEW_LINE DEDENT sq_n = n * n NEW_LINE count_digits = 1 NEW_LINE while not sq_n == 0 : NEW_LINE INDENT count_digits = count_digits + 1 NEW_LINE sq_n = sq_n / 10 NEW_LINE DEDENT r_digits = 0 NEW_LINE while r_digits < count...
Keith Number | Returns true if x is Keith , else false . ; Store all digits of x in a vector " terms " Also find number of digits and store in " n " . ; n = 0 ; n is number of digits in x ; To get digits in right order ( from MSB to LSB ) ; Keep finding next trms of a sequence generated using digits of x until we eithe...
def isKeith ( x ) : NEW_LINE INDENT terms = [ ] ; NEW_LINE temp = x ; NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT terms . append ( temp % 10 ) ; NEW_LINE temp = int ( temp / 10 ) ; NEW_LINE n += 1 ; NEW_LINE DEDENT terms . reverse ( ) ; NEW_LINE next_term = 0 ; NEW_LINE i = n ; NEW_LINE while ( next_term < x ) : NEW_...
Check if a number can be expressed as a sum of consecutive numbers | This function returns true if n can be expressed sum of consecutive . ; We basically return true if n is a power of two ; Driver code
def canBeSumofConsec ( n ) : NEW_LINE INDENT return ( ( n & ( n - 1 ) ) and n ) NEW_LINE DEDENT n = 15 NEW_LINE if ( canBeSumofConsec ( n ) ) : NEW_LINE INDENT print ( " true " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " false " ) NEW_LINE DEDENT
Even Fibonacci Numbers Sum | Returns sum of even Fibonacci numbers which are less than or equal to given limit . ; Initialize first two even prime numbers and their sum ; calculating sum of even Fibonacci value ; get next even value of Fibonacci sequence ; If we go beyond limit , we break loop ; Move to next even numbe...
def evenFibSum ( limit ) : NEW_LINE INDENT if ( limit < 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ef1 = 0 NEW_LINE ef2 = 2 NEW_LINE sm = ef1 + ef2 NEW_LINE while ( ef2 <= limit ) : NEW_LINE INDENT ef3 = 4 * ef2 + ef1 NEW_LINE if ( ef3 > limit ) : NEW_LINE INDENT break NEW_LINE DEDENT ef1 = ef2 NEW_LINE ef2 = ef3 N...
Find numbers with K odd divisors in a given range | Python3 program to count numbers with k odd divisors in a range . ; Utility function to check if number is perfect square or not ; Utility Function to return count of divisors of a number ; Note that this loop runs till square root ; If divisors are equal , counbt it ...
import math NEW_LINE def isPerfect ( n ) : NEW_LINE INDENT s = math . sqrt ( n ) NEW_LINE return ( s * s == n ) NEW_LINE DEDENT def divisorsCount ( 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 ) :...
Nth Even Fibonacci Number | Function which return nth even fibonnaci number ; calculation of Fn = 4 * ( Fn - 1 ) + Fn - 2 ; Driver Code
def evenFib ( n ) : NEW_LINE INDENT if ( n < 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT return ( ( 4 * evenFib ( n - 1 ) ) + evenFib ( n - 2 ) ) NEW_LINE DEDENT n = 7 NEW_LINE print ( evenFib ( n ) ) NEW_LINE
Querying maximum number of divisors that a number in a given range has | Python 3 implementation of the above idea to process queries of finding a number with maximum divisors . ; Finds smallest prime factor of allnumbers in range [ 1 , maxn ) and stores them in smallest_prime [ ] , smallest_prime [ i ] should contain ...
maxn = 1000005 NEW_LINE INF = 99999999 NEW_LINE smallest_prime = [ 0 ] * maxn NEW_LINE divisors = [ 0 ] * maxn NEW_LINE segmentTree = [ 0 ] * ( 4 * maxn ) NEW_LINE def findSmallestPrimeFactors ( ) : NEW_LINE INDENT for i in range ( maxn ) : NEW_LINE INDENT smallest_prime [ i ] = INF NEW_LINE DEDENT for i in range ( 2 ,...
N 'th Smart Number | Limit on result ; Function to calculate n 'th smart number ; Initialize all numbers as not prime ; iterate to mark all primes and smart number ; Traverse all numbers till maximum limit ; ' i ' is maked as prime number because it is not multiple of any other prime ; mark all multiples of ' i ' as n...
MAX = 3000 ; NEW_LINE def smartNumber ( n ) : NEW_LINE INDENT primes = [ 0 ] * MAX ; NEW_LINE result = [ ] ; NEW_LINE for i in range ( 2 , MAX ) : NEW_LINE INDENT if ( primes [ i ] == 0 ) : NEW_LINE INDENT primes [ i ] = 1 ; NEW_LINE j = i * 2 ; NEW_LINE while ( j < MAX ) : NEW_LINE INDENT primes [ j ] -= 1 ; NEW_LINE ...
Repeated subtraction among two numbers | Python3 program to count of steps until one of the two numbers become 0. ; Returns count of steps before one of the numbers become 0 after repeated subtractions . ; If y divides x , then simply return x / y . ; Else recur . Note that this function works even if x is smaller than...
import math NEW_LINE def countSteps ( x , y ) : NEW_LINE INDENT if ( x % y == 0 ) : NEW_LINE INDENT return math . floor ( x / y ) ; NEW_LINE DEDENT return math . floor ( ( x / y ) + countSteps ( y , x % y ) ) ; NEW_LINE DEDENT x = 100 ; NEW_LINE y = 19 ; NEW_LINE print ( countSteps ( x , y ) ) ; NEW_LINE
Common Divisors of Two Numbers | Python3 implementation of program ; Map to store the count of each prime factor of a ; Function that calculate the count of each prime factor of a number ; Function to calculate all common divisors of two given numbers a , b -- > input integer numbers ; Find count of each prime factor o...
import math NEW_LINE ma = { } NEW_LINE def primeFactorize ( a ) : NEW_LINE INDENT sqt = int ( math . sqrt ( a ) ) NEW_LINE for i in range ( 2 , sqt , 2 ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( a % i == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE a /= i NEW_LINE DEDENT ma [ i ] = cnt NEW_LINE DEDENT if ( a > 1 ) : NEW_L...
Count number of solutions of x ^ 2 = 1 ( mod p ) in given range | Program to count number of values that satisfy x ^ 2 = 1 mod p where x lies in range [ 1 , n ] ; Initialize result ; Traverse all numbers smaller than given number p . Note that we don 't traverse from 1 to n, but 1 to p ; If x is a solution , then coun...
def findCountOfSolutions ( n , p ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for x in range ( 1 , p ) : NEW_LINE INDENT if ( ( x * x ) % p == 1 ) : NEW_LINE INDENT last = x + p * ( n / p ) ; NEW_LINE if ( last > n ) : NEW_LINE INDENT last -= p ; NEW_LINE DEDENT ans += ( ( last - x ) / p + 1 ) ; NEW_LINE DEDENT DEDENT return...
Kaprekar Constant | This function checks validity of kaprekar ' s ▁ constant . ▁ It ▁ returns ▁ kaprekar ' s constant for any four digit number " n " such that all digits of n are not same . ; Store current n as previous number ; Get four digits of given number ; Sort all four dgits in ascending order And giet in the f...
def kaprekarRec ( n , prev ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT prev = n ; NEW_LINE digits = [ 0 ] * 4 ; NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT digits [ i ] = n % 10 ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE DEDENT digits . sort ( ) ; NEW_LINE asc = 0 ; NEW_LINE for i i...
Bakhshali Approximation for computing square roots | This Python3 program gives result approximated to 5 decimal places . ; This will be the nearest perfect square to s ; This is the sqrt of pSq ; Find the nearest perfect square to s ; calculate d ; calculate P ; calculate A ; calculate sqrt ( S ) . ; Driver Code
def sqroot ( s ) : NEW_LINE INDENT pSq = 0 ; NEW_LINE N = 0 ; NEW_LINE for i in range ( int ( s ) , 0 , - 1 ) : NEW_LINE INDENT for j in range ( 1 , i ) : NEW_LINE INDENT if ( j * j == i ) : NEW_LINE INDENT pSq = i ; NEW_LINE N = j ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( pSq > 0 ) : NEW_LINE INDENT break ; NEW_L...
Breaking an Integer to get Maximum Product | method return x ^ a in log ( a ) time ; Method returns maximum product obtained by breaking N ; base case 2 = 1 + 1 ; base case 3 = 2 + 1 ; breaking based on mod with 3 ; If divides evenly , then break into all 3 ; If division gives mod as 1 , then break as 4 + power of 3 fo...
def power ( x , a ) : NEW_LINE INDENT res = 1 NEW_LINE while ( a ) : NEW_LINE INDENT if ( a & 1 ) : NEW_LINE INDENT res = res * x NEW_LINE DEDENT x = x * x NEW_LINE a >>= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def breakInteger ( N ) : NEW_LINE INDENT if ( N == 2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( N...
Finding sum of digits of a number until sum becomes single digit | Python program to find sum of digits of a number until sum becomes single digit . ; method to find sum of digits of a number until sum becomes single digit ; Driver method
import math NEW_LINE def digSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( n > 0 or sum > 9 ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT n = sum NEW_LINE sum = 0 NEW_LINE DEDENT sum += n % 10 NEW_LINE n /= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 1234 NEW_LINE print ( digSum ( n ) ) NEW_LINE
Finding sum of digits of a number until sum becomes single digit | ''Driver program to test the above function
def digSum ( 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 return ( n % 9 ) NEW_LINE DEDENT n = 9999 NEW_LINE print ( digSum ( n ) ) NEW_LINE
Multiples of 3 or 7 | Returns count of all numbers smaller than or equal to n and multiples of 3 or 7 or both ; Driver code
def countMultiples ( n ) : NEW_LINE INDENT return n / 3 + n / 7 - n / 21 ; NEW_LINE DEDENT n = ( ( int ) ( countMultiples ( 25 ) ) ) ; NEW_LINE print ( " Count ▁ = " , n ) ; NEW_LINE
Reverse and Add Function | Iterative function to reverse digits of num ; Function to check whether the number is palindrome or not ; Reverse and Add Function ; Reversing the digits of the number ; Adding the reversed number with the original ; Checking whether the number is palindrome or not ; Driver Code
def reversDigits ( num ) : NEW_LINE INDENT rev_num = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT rev_num = rev_num * 10 + num % 10 NEW_LINE num = num / 10 NEW_LINE DEDENT return rev_num NEW_LINE DEDENT def isPalindrome ( num ) : NEW_LINE INDENT return ( reversDigits ( num ) == num ) NEW_LINE DEDENT def ReverseandAdd...
Stein 's Algorithm for finding GCD | Function to implement Stein 's Algorithm ; GCD ( 0 , b ) == b ; GCD ( a , 0 ) == a , GCD ( 0 , 0 ) == 0 ; look for factors of 2 a is even ; b is odd ; both a and b are even ; a is odd , b is even ; reduce larger number ; Driver code
def gcd ( a , b ) : NEW_LINE INDENT if ( a == b ) : NEW_LINE INDENT return a NEW_LINE DEDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT if ( ( ~ a & 1 ) == 1 ) : NEW_LINE INDENT if ( ( b & 1 ) == 1 ) : NEW_LINE INDENT return gcd ( a >> 1 , b ) NEW_L...
Sub | Array to store the sum of digits ; Utility function to evaluate a character 's integer value ; This function receives the string representation of the number and precomputes the sum array ; This function receives l and r representing the indices and prs the required output ; Driver function to check the program
sum = [ 0 for i in range ( 1000005 ) ] NEW_LINE def toInt ( x ) : NEW_LINE INDENT return int ( x ) NEW_LINE DEDENT def prepareSum ( s ) : NEW_LINE INDENT sum [ 0 ] = 0 NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT sum [ i + 1 ] = sum [ i ] + toInt ( s [ i ] ) NEW_LINE DEDENT DEDENT def query ( l , r ) : N...
Print all n | n , sum -- > value of inputs out -- > output array index -- > index of next digit to be filled in output array ; Base case ; If number becomes N - digit ; if sum of its digits is equal to given sum , print it ; Traverse through every digit . Note that here we ' re ▁ considering ▁ leading ▁ ▁ 0' s as digit...
def findNDigitNumsUtil ( n , sum , out , index ) : NEW_LINE INDENT if ( index > n or sum < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT f = " " NEW_LINE if ( index == n ) : NEW_LINE INDENT if ( sum == 0 ) : NEW_LINE INDENT out [ index ] = " \0" NEW_LINE for i in out : NEW_LINE INDENT f = f + i NEW_LINE DEDENT print ( f...
Program for Armstrong Numbers |
def armstrong ( n ) : NEW_LINE INDENT number = str ( n ) NEW_LINE n = len ( number ) NEW_LINE output = 0 NEW_LINE for i in number : NEW_LINE output = output + int ( i ) ** n NEW_LINE if output == int ( number ) : NEW_LINE INDENT return ( True ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( False ) NEW_LINE DEDENT DED...
Palindromic Primes | A function that returns true only if num contains one digit ; comparison operation is faster than division operation . So using following instead of " return ▁ num ▁ / ▁ 10 ▁ = = ▁ 0 ; " ; A recursive function to find out whether num is palindrome or not . Initially , dupNum contains address of a c...
def oneDigit ( num ) : NEW_LINE INDENT return ( num >= 0 and num < 10 ) ; NEW_LINE DEDENT def isPalUtil ( num , dupNum ) : NEW_LINE INDENT if ( oneDigit ( num ) ) : NEW_LINE INDENT return ( num == ( dupNum ) % 10 ) ; NEW_LINE DEDENT if ( not isPalUtil ( int ( num / 10 ) , dupNum ) ) : NEW_LINE INDENT return False ; NEW...
Almost Prime Numbers | Python3 Program to print first n numbers that are k - primes ; A function to count all prime factors of a given number ; Count the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , count i and divide n ; This condition ...
import math NEW_LINE def countPrimeFactors ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = n / 2 ; NEW_LINE count += 1 ; NEW_LINE DEDENT i = 3 ; NEW_LINE while ( i <= math . sqrt ( n ) ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT n = n / i ; NEW_LINE count += 1 ; NE...
Program to add two fractions | Function to return gcd of a and b ; Function to convert the obtained fraction into it 's simplest form ; Finding gcd of both terms ; Converting both terms into simpler terms by dividing them by common factor ; Function to add two fractions ; Finding gcd of den1 and den2 ; Denominator of f...
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b ; NEW_LINE DEDENT return gcd ( b % a , a ) ; NEW_LINE DEDENT def lowest ( den3 , num3 ) : NEW_LINE INDENT common_factor = gcd ( num3 , den3 ) ; NEW_LINE den3 = int ( den3 / common_factor ) ; NEW_LINE num3 = int ( num3 / common_factor ) ; NEW_L...
The Lazy Caterer 's Problem | This function receives an integer n and returns the maximum number of pieces that can be made form pancake using n cuts ; Use the formula ; Driver Code
def findPieces ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) ) // 2 + 1 NEW_LINE DEDENT print ( findPieces ( 1 ) ) NEW_LINE print ( findPieces ( 2 ) ) NEW_LINE print ( findPieces ( 3 ) ) NEW_LINE print ( findPieces ( 50 ) ) NEW_LINE
Count digits in a factorial | Set 2 | A optimised Python3 program to find the number of digits in a factorial ; Returns the number of digits present in n ! Since the result can be large long long is used as return type ; factorial of - ve number doesn 't exists ; base case ; Use Kamenetsky formula to calculate the numb...
import math NEW_LINE def findDigits ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n <= 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT x = ( ( n * math . log10 ( n / math . e ) + math . log10 ( 2 * math . pi * n ) / 2.0 ) ) ; NEW_LINE return math . floor ( x ) + 1 ; NEW_LINE DE...
Count digits in a factorial | Set 1 | Python3 program to find the number of digits in a factorial ; This function receives an integer n , and returns the number of digits present in n ! ; factorial exists only for n >= 0 ; base case ; else iterate through n and calculate the value ; Driver code
import math NEW_LINE def findDigits ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n <= 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT digits = 0 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT digits += math . log10 ( i ) ; NEW_LINE DEDENT return math . floor ( digit...
Find number of subarrays with even sum | Python 3 program to count number of sub - arrays whose sum is even using brute force Time Complexity - O ( N ^ 2 ) Space Complexity - O ( 1 ) ; Find sum of all subarrays and increment result if sum is even ; Driver code
def countEvenSum ( arr , n ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( i , n , 1 ) : NEW_LINE INDENT sum = sum + arr [ j ] NEW_LINE if ( sum % 2 == 0 ) : NEW_LINE INDENT result = result + 1 NEW_LINE DEDENT DEDENT DEDENT return ( result ) NEW_L...
Find number of subarrays with even sum | Python 3 program to count number of sub - arrays with even sum using an efficient algorithm Time Complexity - O ( N ) Space Complexity - O ( 1 ) ; A temporary array of size 2. temp [ 0 ] is going to store count of even subarrays and temp [ 1 ] count of odd . temp [ 0 ] is initia...
def countEvenSum ( arr , n ) : NEW_LINE INDENT temp = [ 1 , 0 ] NEW_LINE result = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = ( ( sum + arr [ i ] ) % 2 + 2 ) % 2 NEW_LINE temp [ sum ] += 1 NEW_LINE DEDENT result = result + ( temp [ 0 ] * ( temp [ 0 ] - 1 ) // 2 ) NEW_LINE result = result + ...