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 DEDENT else : NEW_LINE INDENT print ( " false " ) NEW_LINE DEDENT
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 code ; num will store closest tidy number
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 , 3 , 4 , 4 , 5 , 5 , 3 , 8 ] NEW_LINE len = len ( str ) NEW_LINE num = tidyNum ( str , len ) NEW_LINE for i in range ( 0 , len ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) NEW_LINE DEDENT
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 ; n = 6 NEW_LINE print ( findCount ( m , n ) ) NEW_LINE
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 it does not have 1 , 3 , 5 , 7 , 9 ; If nth such number is found , return it ; Driver Code
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 INDENT isCurrEvenDigit = False ; NEW_LINE DEDENT curr = curr // 10 ; NEW_LINE DEDENT if ( isCurrEvenDigit == True ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( count == n ) : NEW_LINE INDENT return i ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT DEDENT print ( findNthEvenDigitNumber ( 2 ) ) ; NEW_LINE print ( findNthEvenDigitNumber ( 10 ) ) ; NEW_LINE
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. Since the digits are be in reverse order , we traverse vector from back ; return 2 * result ( to convert digits 0 , 1 , 2 , 3 , 4 to 0 , 2 , 4 , 6 , 8. ; Driver Code
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 result = result * 10 NEW_LINE result = result + v [ i ] NEW_LINE DEDENT return 2 * result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( findNthEvenDigitNumber ( 2 ) ) NEW_LINE print ( findNthEvenDigitNumber ( 10 ) ) NEW_LINE DEDENT
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 if ( isDivisibleBy25 ( st ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 - 3 ] ) * 100 + ( int ) ( st [ n - 2 ] ) * 10 + ( int ) ( st [ n - 1 ] ) ) % 16 == 0 ) NEW_LINE DEDENT last = ( int ) ( st [ n - 1 ] ) NEW_LINE second_last = ( int ) ( st [ n - 2 ] ) NEW_LINE third_last = ( int ) ( st [ n - 3 ] ) NEW_LINE fourth_last = ( int ) ( st [ n - 4 ] ) NEW_LINE return ( ( fourth_last * 1000 + third_last * 100 + second_last * 10 + last ) % 16 == 0 ) NEW_LINE DEDENT st = "769528" NEW_LINE if ( check ( st ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 fibonacci number ; Driver program to test above function
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 ) NEW_LINE print ( result ) NEW_LINE
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 going to store result year and offset2 is going to store offset days in result year . ; x may store thousands of days . We find correct year and offset in the year . ; Find values of day and month from offset of result year . ; Driven Program
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 , 1 : 28 , 0 : 31 } NEW_LINE if ( isLeap ( y ) and m > 1 ) : NEW_LINE INDENT offset += 1 NEW_LINE DEDENT offset += switcher . get ( m ) NEW_LINE return offset NEW_LINE DEDENT def revoffsetDays ( offset , y , d , m ) : NEW_LINE INDENT month = [ 0 , 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ] NEW_LINE if ( isLeap ( y ) ) : NEW_LINE INDENT month [ 2 ] = 29 NEW_LINE DEDENT for i in range ( 1 , 13 ) : NEW_LINE INDENT if ( offset <= month [ i ] ) : NEW_LINE INDENT break NEW_LINE DEDENT offset = offset - month [ i ] NEW_LINE DEDENT d [ 0 ] = offset NEW_LINE m [ 0 ] = i + 1 NEW_LINE DEDENT def addDays ( d1 , m1 , y1 , x ) : NEW_LINE INDENT offset1 = offsetDays ( d1 , m1 , y1 ) NEW_LINE if isLeap ( y1 ) : NEW_LINE INDENT remDays = 366 - offset1 NEW_LINE DEDENT else : NEW_LINE INDENT remDays = 365 - offset1 NEW_LINE DEDENT if ( x <= remDays ) : NEW_LINE INDENT y2 = y1 NEW_LINE offset2 = offset1 + x NEW_LINE DEDENT else : NEW_LINE INDENT x -= remDays NEW_LINE y2 = y1 + 1 NEW_LINE if isLeap ( y2 ) : NEW_LINE INDENT y2days = 366 NEW_LINE DEDENT else : NEW_LINE INDENT y2days = 365 NEW_LINE DEDENT while ( x >= y2days ) : NEW_LINE INDENT x -= y2days NEW_LINE y2 += 1 NEW_LINE if isLeap ( y2 ) : NEW_LINE INDENT y2days = 366 NEW_LINE DEDENT else : NEW_LINE INDENT y2days = 365 NEW_LINE DEDENT DEDENT offset2 = x NEW_LINE DEDENT m2 = [ 0 ] NEW_LINE d2 = [ 0 ] NEW_LINE revoffsetDays ( offset2 , y2 , d2 , m2 ) NEW_LINE print ( " d2 ▁ = ▁ " , * d2 , " , ▁ m2 ▁ = ▁ " , * m2 , " , ▁ y2 ▁ = ▁ " , y2 , sep = " " ) NEW_LINE DEDENT d = 14 NEW_LINE m = 3 NEW_LINE y = 2015 NEW_LINE x = 366 NEW_LINE addDays ( d , m , y , x ) NEW_LINE
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 take the values i and N / i as long as i divides N ; Function to check whether the given number is prime ; Base and corner cases ; Since integers can be represented as some 6 * k + y where y >= 0 , we can eliminate all integers that can be expressed in this form ; Start from 5 as this is the next prime number ; Returns true if N is a K - Hyperperfect number . Else returns false . ; Condition from the definition of hyperperfect ; Driver code ; First two statements test against the condition N = 1 + K * ( sum ( proper divisors ) )
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 or n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def isHyperPerfect ( N , K ) : NEW_LINE INDENT Sum = divisorSum ( N , K ) NEW_LINE if ( ( 1 + K * ( Sum ) ) == N ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT N1 = 1570153 NEW_LINE K1 = 12 NEW_LINE N2 = 321 NEW_LINE K2 = 3 NEW_LINE if ( isHyperPerfect ( N1 , K1 ) ) : NEW_LINE INDENT print ( N1 , " ▁ is ▁ " , K1 , " - HyperPerfect " , sep = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( N1 , " ▁ is ▁ not ▁ " , K1 , " - HyperPerfect " , sep = " " ) NEW_LINE DEDENT if ( isHyperPerfect ( N2 , K2 ) ) : NEW_LINE INDENT print ( N2 , " ▁ is ▁ " , K2 , " - HyperPerfect " , sep = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( N2 , " ▁ is ▁ not ▁ " , K2 , " - HyperPerfect " , sep = " " ) NEW_LINE DEDENT
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 integer less than or equal to the argument . So in this case , product - floor ( product ) will give us the decimal part of product ; we now exponentiate this back by raising 10 to the power of decimal part ; We now try to find the power of 10 by which we will have to multiply the decimal part to obtain our final answer ; Driver Code
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_LINE DEDENT n = 1450 ; NEW_LINE k = 6 ; NEW_LINE print ( firstkdigits ( n , k ) ) ; NEW_LINE
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 INDENT printWellOrdered ( 0 , 0 , k ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k = 3 NEW_LINE generateWellOrdered ( k ) NEW_LINE DEDENT
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 = 10005412336548794 ; NEW_LINE print ( moduloMultiplication ( a , b , m ) ) ; NEW_LINE
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 ) % 10 ; NEW_LINE if ( digit < 2 ) : NEW_LINE INDENT return roundDown // 10 ; NEW_LINE DEDENT if ( digit == 2 ) : NEW_LINE INDENT return roundDown // 10 + right + 1 ; NEW_LINE DEDENT return roundup // 10 ; NEW_LINE DEDENT def numberOf2sinRange ( number ) : NEW_LINE INDENT s = str ( number ) ; NEW_LINE len1 = len ( s ) ; NEW_LINE count = 0 ; NEW_LINE for digit in range ( len1 ) : NEW_LINE INDENT count += count2sinRangeAtDigit ( number , digit ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT print ( numberOf2sinRange ( 22 ) ) ; NEW_LINE print ( numberOf2sinRange ( 100 ) ) ; NEW_LINE
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 " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 ( isSqFree == True ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE if ( cnt == n ) : NEW_LINE INDENT return i ; NEW_LINE DEDENT DEDENT i += 1 ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT n = 10 ; NEW_LINE print ( squareFree ( n ) ) ; NEW_LINE
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 list ; n must be odd at this point so we skip one element ( i = i + 2 ) ; This is to handle when n > 2 and n is prime ; if size ( a ) < k , k factors are not possible ; printing first k - 1 factors ; calculating and printing product of rest of numbers ; Driver code
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 ( i ) NEW_LINE DEDENT DEDENT if n > 2 : NEW_LINE INDENT a . append ( n ) NEW_LINE DEDENT if len ( a ) < k : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT for i in range ( k - 1 ) : NEW_LINE INDENT print ( a [ i ] , end = " , ▁ " ) NEW_LINE DEDENT product = 1 NEW_LINE for i in range ( k - 1 , len ( a ) ) : NEW_LINE INDENT product *= a [ i ] NEW_LINE DEDENT print ( product ) NEW_LINE DEDENT n , k = 54 , 3 NEW_LINE kFactors ( n , k ) NEW_LINE
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 //= 10 NEW_LINE DEDENT if ( flag == True ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 200 NEW_LINE print ( nondecdigits ( n ) ) NEW_LINE DEDENT
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 the digit is less than its left digit ; If first digit is 0 no need to print it ; Driver Code
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 - 1 ] -= 1 ; NEW_LINE level = i - 1 ; NEW_LINE DEDENT DEDENT if ( a [ 0 ] != 0 ) : NEW_LINE INDENT for i in range ( level + 1 ) : NEW_LINE INDENT print ( a [ i ] , end = " " ) ; NEW_LINE DEDENT for i in range ( level + 1 , m ) : NEW_LINE INDENT print ( "9" , end = " " ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 1 , level ) : NEW_LINE INDENT print ( a [ i ] , end = " " ) ; NEW_LINE DEDENT for i in range ( level + 1 , m ) : NEW_LINE INDENT print ( "9" , end = " " ) ; NEW_LINE DEDENT DEDENT DEDENT n = "200" ; NEW_LINE nondecdigits ( n ) ; NEW_LINE
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 print ( " Total ▁ distinct ▁ divisors ▁ of ▁ 100 ▁ are ▁ : ▁ " , countDivisors ( 100 ) ) NEW_LINE
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 of factors final status is closed ; else odd number of factors final status is open ; Driver program
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 ( hasEvenNumberOfFactors ( i ) == True ) : NEW_LINE INDENT print ( " closed " , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " open " , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT n = 5 NEW_LINE printStatusOfDoors ( n ) NEW_LINE
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 return 1 ; NEW_LINE DEDENT n = 1552793 ; NEW_LINE geek = " True " if validate ( n ) else " False " ; NEW_LINE print ( geek ) ; NEW_LINE
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 digits ; sum of digits is not divisible by 9 ; Number is divisible by 4 and 9 hence , number is divisible by 36 ; Driver program
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 ( two_digit_num % 4 != 0 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT sm = 0 NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT sm = sm + ( int ) ( num [ i ] ) NEW_LINE DEDENT if ( sm % 9 != 0 ) : NEW_LINE INDENT return ( " No " ) NEW_LINE DEDENT return ( " Yes " ) NEW_LINE DEDENT num = "92567812197966231384" NEW_LINE print ( divisibleBy36 ( num ) ) NEW_LINE
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 ) ) NEW_LINE DEDENT last = ( int ) ( st [ n - 1 ] ) NEW_LINE second_last = ( int ) ( st [ n - 2 ] ) NEW_LINE third_last = ( int ) ( st [ n - 3 ] ) NEW_LINE return ( ( third_last * 100 + second_last * 10 + last ) % 8 == 0 ) NEW_LINE DEDENT st = "76952" NEW_LINE if ( check ( st ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ " ) NEW_LINE DEDENT
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 ; As single and double digit numbers do not have left and right number pairs ; Finding all left and right pairs . Printing the prime points accordingly . Discarding first and last index point ; Calculating left number ; Calculating right number ; Prime point condition ; No prime point found ; Driver Program
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 DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT i = 5 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT i += 6 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def printPrimePoints ( n ) : NEW_LINE INDENT count = countDigits ( n ) NEW_LINE if ( count == 1 or count == 2 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT found = False NEW_LINE for i in range ( 1 , ( count - 1 ) ) : NEW_LINE INDENT left = n // ( pow ( 10 , count - i ) ) NEW_LINE right = n % ( pow ( 10 , count - i - 1 ) ) NEW_LINE if ( checkPrime ( left ) == 0 and checkPrime ( right ) == 0 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE found = True NEW_LINE DEDENT DEDENT if ( found == False ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2317 NEW_LINE printPrimePoints ( n ) NEW_LINE DEDENT
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 greater values of i ; If sum of powers is equal to x then increase the value of result . ; Return the final result ; Driver Code .
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 checkRecursive ( x , n , curr_num = 1 , curr_sum = 0 ) : NEW_LINE INDENT results = 0 NEW_LINE DEDENT ' NEW_LINE INDENT p = power ( curr_num , n ) NEW_LINE while ( p + curr_sum < x ) : NEW_LINE INDENT results += checkRecursive ( x , n , curr_num + 1 , p + curr_sum ) NEW_LINE curr_num = curr_num + 1 NEW_LINE p = power ( curr_num , n ) NEW_LINE DEDENT if ( p + curr_sum == x ) : NEW_LINE INDENT results = results + 1 NEW_LINE DEDENT return results NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 10 NEW_LINE n = 2 NEW_LINE print ( checkRecursive ( x , n ) ) NEW_LINE DEDENT
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 , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT n = 10 ; NEW_LINE printGenerators ( n ) ; NEW_LINE
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 : NEW_LINE INDENT print " No " NEW_LINE DEDENT
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 INDENT return perfectDiv [ n ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT precomputeCounts ( ) NEW_LINE n = 16 NEW_LINE print ( " Total ▁ perfect ▁ divisors ▁ of ▁ " , n , " ▁ = ▁ " , countPerfectDivisors ( n ) ) NEW_LINE n = 12 NEW_LINE print ( " Total ▁ perfect ▁ divisors ▁ of ▁ " , n , " ▁ = ▁ " , countPerfectDivisors ( n ) ) NEW_LINE DEDENT
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 ( nloglogn ) ; marking smallest prime factor for every number to be itself . ; separately marking spf for every even number as 2 ; checking if i is prime ; marking SPF for all numbers divisible by i ; marking spf [ j ] if it is not previously marked ; A O ( log n ) function returning prime factorization by dividing by smallest prime factor at every step ; precalculating Smallest Prime Factor ; calling getFactorization function
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 ( 3 , mt . ceil ( mt . sqrt ( MAXN ) ) ) : NEW_LINE INDENT if ( spf [ i ] == i ) : NEW_LINE INDENT for j in range ( i * i , MAXN , i ) : NEW_LINE INDENT if ( spf [ j ] == j ) : NEW_LINE INDENT spf [ j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def getFactorization ( x ) : NEW_LINE INDENT ret = list ( ) NEW_LINE while ( x != 1 ) : NEW_LINE INDENT ret . append ( spf [ x ] ) NEW_LINE x = x // spf [ x ] NEW_LINE DEDENT return ret NEW_LINE DEDENT sieve ( ) NEW_LINE x = 12246 NEW_LINE print ( " prime ▁ factorization ▁ for " , x , " : ▁ " , end = " " ) NEW_LINE p = getFactorization ( x ) NEW_LINE for i in range ( len ( p ) ) : NEW_LINE INDENT print ( p [ i ] , end = " ▁ " ) NEW_LINE DEDENT
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 prime factors ; Traverse all elements , ; For every divisor of current element , find closest element . ; Visit divisor if not visited ; Fetch the index of visited divisor ; Update the divisor index to current index ; Set the minimum distance ; Set the min distance of current index ' i ' to nearest one ; Add 1 as indexing starts from 0 ; Set the min distance of found index 'ind ; Add 1 as indexing starts from 0 ; Simple sieve to find smallest prime divisor of number from 2 to MAX ; function to calculate nearest distance of every array elements ; Print the nearest distance having GDC > 1
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_LINE INDENT for i in range ( 2 , MAX ) : NEW_LINE INDENT if i * i > MAX : NEW_LINE INDENT break NEW_LINE DEDENT if ( primedivisor [ i ] == 0 ) : NEW_LINE INDENT for j in range ( 2 * i , MAX , i ) : NEW_LINE INDENT primedivisor [ j ] = i NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , MAX ) : NEW_LINE INDENT if ( primedivisor [ i ] == 0 ) : NEW_LINE INDENT primedivisor [ i ] = i NEW_LINE DEDENT DEDENT DEDENT def findDivisors ( arr , n ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT pos [ i ] = divInd [ i ] = - 1 NEW_LINE dist [ i ] = 10 ** 9 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT num = arr [ i ] NEW_LINE while ( num > 1 ) : NEW_LINE INDENT div = primedivisor [ num ] NEW_LINE divisors [ i ] . append ( div ) NEW_LINE while ( num % div == 0 ) : NEW_LINE INDENT num //= div NEW_LINE DEDENT DEDENT DEDENT DEDENT def nearestGCD ( arr , n ) : NEW_LINE INDENT findDivisors ( arr , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for div in divisors [ i ] : NEW_LINE INDENT if ( divInd [ div ] == - 1 ) : NEW_LINE INDENT divInd [ div ] = i NEW_LINE DEDENT else : NEW_LINE INDENT ind = divInd [ div ] NEW_LINE divInd [ div ] = i NEW_LINE if ( dist [ i ] > abs ( ind - i ) ) : NEW_LINE INDENT dist [ i ] = abs ( ind - i ) NEW_LINE pos [ i ] = ind + 1 NEW_LINE DEDENT if ( dist [ ind ] > abs ( ind - i ) ) : NEW_LINE DEDENT DEDENT DEDENT DEDENT ' NEW_LINE INDENT dist [ ind ] = abs ( ind - i ) NEW_LINE pos [ ind ] = i + 1 NEW_LINE DEDENT sieveOfEratosthenes ( ) NEW_LINE arr = [ 2 , 9 , 4 , 3 , 13 ] NEW_LINE n = len ( arr ) NEW_LINE nearestGCD ( arr , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( pos [ i ] , end = " ▁ " ) NEW_LINE DEDENT
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_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 2 , 5 , 4 ] NEW_LINE size = len ( arr ) NEW_LINE print ( largestGCDSubsequence ( arr , size ) ) NEW_LINE DEDENT
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 function mainly uses count [ ] which is filled by Sieve ( ) ; finding the sum of number of prime factor of numbers in a range . ; Driver Code
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 ; NEW_LINE DEDENT DEDENT def query ( l , r ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT sum += count [ i ] ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT sieve ( ) ; NEW_LINE print ( query ( 6 , 10 ) , query ( 1 , 5 ) ) ; NEW_LINE
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 equal to current value ( to avoid the duplicates ) ; incrementing the current value by the respective factor ; Driver code
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 != next [ toincrement ] ) : NEW_LINE INDENT output = next [ toincrement ] ; NEW_LINE print ( next [ toincrement ] , end = " ▁ " ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT next [ toincrement ] += factor [ toincrement ] ; NEW_LINE DEDENT DEDENT factor = [ 3 , 5 , 7 ] ; NEW_LINE n = 10 ; NEW_LINE k = len ( factor ) ; NEW_LINE generateNumbers ( factor , n , k ) ; NEW_LINE
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 //= 10 NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT print ( " Reversible ▁ Number " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Non - Reversible ▁ Number " ) NEW_LINE DEDENT DEDENT n = 36 NEW_LINE checkReversible ( n ) NEW_LINE
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 INDENT result = ( result * A ) % N NEW_LINE if ( result == 1 ) : NEW_LINE INDENT return K NEW_LINE DEDENT K = K + 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT A = 4 NEW_LINE N = 7 NEW_LINE print ( multiplicativeOrder ( A , N ) ) NEW_LINE
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 . ; Finding the lower limit . ; Driven Code
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_LINE INDENT up = int ( n / i ) ; NEW_LINE low = max ( int ( n / ( i + 1 ) ) , root ) ; NEW_LINE sum += ( i * sumOfRange ( up , low ) ) ; NEW_LINE sum += ( i * int ( n / i ) ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT n = 10 ; NEW_LINE print ( sumofproduct ( n ) ) ; NEW_LINE
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 than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; Utility function to store prime factors of a number ; Print the number of 2 s that divide n ; n must be odd at this po . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Function to find smallest primitive root of n ; Check if n is prime or not ; Find value of Euler Totient function of n . Since n is a prime number , the value of Euler Totient function is n - 1 as there are n - 1 relatively prime numbers . ; Find prime factors of phi and store in a set ; Check for every number from 2 to phi ; Iterate through all prime factors of phi . and check if we found a power with value 1 ; Check if r ^ ( ( phi ) / primefactors ) mod n is 1 or not ; If there was no power with value 1. ; If no primitive root found ; Driver Code
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 if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def power ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def findPrimefactors ( s , n ) : NEW_LINE INDENT while ( n % 2 == 0 ) : NEW_LINE INDENT s . add ( 2 ) NEW_LINE n = n // 2 NEW_LINE DEDENT for i in range ( 3 , int ( sqrt ( n ) ) , 2 ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT s . add ( i ) NEW_LINE n = n // i NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT s . add ( n ) NEW_LINE DEDENT DEDENT def findPrimitive ( n ) : NEW_LINE INDENT s = set ( ) NEW_LINE if ( isPrime ( n ) == False ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT phi = n - 1 NEW_LINE findPrimefactors ( s , phi ) NEW_LINE for r in range ( 2 , phi + 1 ) : NEW_LINE INDENT flag = False NEW_LINE for it in s : NEW_LINE INDENT if ( power ( r , phi // it , n ) == 1 ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT return r NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT n = 761 NEW_LINE print ( " Smallest ▁ primitive ▁ root ▁ of " , n , " is " , findPrimitive ( n ) ) NEW_LINE
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 sum NEW_LINE DEDENT n = 9 NEW_LINE print ( calSum ( n ) ) NEW_LINE
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 DEDENT x = 4 NEW_LINE y = 24 NEW_LINE k = 3 NEW_LINE print ( findKHCF ( x , y , k ) ) NEW_LINE
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 removed by dividing n by prime number . ; If count is odd , it must be removed by dividing n by prime number . ; Driver Code
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 INDENT count = 0 NEW_LINE while n % i == 0 : NEW_LINE INDENT count += 1 NEW_LINE n //= i NEW_LINE DEDENT if count % 2 is not 0 : NEW_LINE INDENT ans *= i NEW_LINE DEDENT DEDENT if n > 2 : NEW_LINE INDENT ans *= n NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 72 NEW_LINE print ( findMinNumber ( n ) ) NEW_LINE
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 DEDENT DEDENT def isToOne ( n : int ) -> bool : NEW_LINE INDENT s = set ( ) NEW_LINE return isToOneRec ( n , s ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE if isToOne ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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_LINE findgcd ( n , x , y ) NEW_LINE
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 . ; Return difference between first natural number whose factorial is divisible by y and first natural number whose factorial is divisible by x . ; Driver code
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 ( new_x == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return i NEW_LINE DEDENT def countFactorialXNotY ( x , y ) : NEW_LINE INDENT return ( firstFactorialDivisibleNumber ( y ) - firstFactorialDivisibleNumber ( x ) ) NEW_LINE DEDENT x = 15 NEW_LINE y = 25 NEW_LINE print ( countFactorialXNotY ( x , y ) ) NEW_LINE
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 ; Prints a prime pair with given sum ; Generating primes using Sieve ; Traversing all numbers to find first pair ; Driven program
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 <= n ) : NEW_LINE INDENT isPrime [ i ] = False NEW_LINE i += p NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def findPrimePair ( n ) : NEW_LINE INDENT isPrime = [ 0 ] * ( n + 1 ) NEW_LINE SieveOfEratosthenes ( n , isPrime ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( isPrime [ i ] and isPrime [ n - i ] ) : NEW_LINE INDENT print ( i , ( n - i ) ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT n = 74 NEW_LINE findPrimePair ( n ) NEW_LINE
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 decrease count by 1 ; Method to return count of numbers with same starting and ending digit between start and end ; Driver Code
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 ( x ) NEW_LINE lastDigit = x % 10 NEW_LINE if ( lastDigit < firstDigit ) : NEW_LINE INDENT res = res - 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def getCountWithSameStartAndEnd ( start , end ) : NEW_LINE INDENT return ( getCountWithSameStartAndEndFrom1 ( end ) - getCountWithSameStartAndEndFrom1 ( start - 1 ) ) NEW_LINE DEDENT start = 5 NEW_LINE end = 40 NEW_LINE print ( getCountWithSameStartAndEnd ( start , end ) ) NEW_LINE
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 - truncatable , else false ; Generating primes using Sieve ; Checking whether the number remains prime when the last ( " right " ) digit is successively removed ; Driven program
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 <= n ) : NEW_LINE INDENT isPrime [ i ] = False NEW_LINE i = i + p NEW_LINE DEDENT DEDENT p = p + 1 NEW_LINE DEDENT DEDENT def rightTruPrime ( n ) : NEW_LINE INDENT isPrime = [ None ] * ( n + 1 ) NEW_LINE sieveOfEratosthenes ( n , isPrime ) NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( isPrime [ n ] ) : NEW_LINE INDENT n = n // 10 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT n = 59399 NEW_LINE if ( rightTruPrime ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 primes less than or equal to n ; Create a boolean array " prime [ 0 . . n ] " ; Generating primes using Sieve ; Generate all numbers of the form 2 ^ k - 1 and smaller than or equal to n . ; Checking whether number is prime and is one less then the power of 2 ; Driver Code
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 DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def mersennePrimes ( n ) : NEW_LINE INDENT prime = [ 0 ] * ( n + 1 ) NEW_LINE SieveOfEratosthenes ( n , prime ) NEW_LINE k = 2 NEW_LINE while ( ( ( 1 << k ) - 1 ) <= n ) : NEW_LINE INDENT num = ( 1 << k ) - 1 NEW_LINE if ( prime [ num ] ) : NEW_LINE INDENT print ( num , end = " ▁ " ) NEW_LINE DEDENT k += 1 NEW_LINE DEDENT DEDENT n = 31 NEW_LINE print ( " Mersenne ▁ prime ▁ numbers ▁ smaller " , " than ▁ or ▁ equal ▁ to ▁ " , n ) NEW_LINE mersennePrimes ( n ) 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 , . . , K - 1 , 0 sequence occurs and sum of first k natural number and sequence from case 1. ; Driver Code
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 of string representing a floating point number . ; Below is used to find denominator in fraction form . ; Used to find value of count_after_dot ; To find numerator in fraction form of given number . For example , for 30.25 , numerator would be 3025. ; If there was no dot , then number is already a natural . ; Find denominator in fraction form . For example , for 30.25 , denominator is 100 ; Result is denominator divided by GCD - of - numerator - and - denominator . For example , for 30.25 , result is 100 / GCD ( 3025 , 100 ) = 100 / 25 = 4 ; Driver Program
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 INDENT if ( str [ i ] != ' . ' ) : NEW_LINE INDENT num = num * 10 + int ( str [ i ] ) NEW_LINE if ( dot_seen == 1 ) : NEW_LINE INDENT count_after_dot += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT dot_seen = 1 NEW_LINE DEDENT DEDENT if ( dot_seen == 0 ) : NEW_LINE return 1 NEW_LINE dem = int ( math . pow ( 10 , count_after_dot ) ) NEW_LINE return ( dem / gcd ( num , dem ) ) NEW_LINE DEDENT str = "5.125" NEW_LINE print findnum ( str ) NEW_LINE
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 frequency of digits which divide N ; We initialize all digits of N as not divisible by N . ; start checking divisibility of N by digits 2 to 9 ; if digit divides N then mark it as true ; Now traverse the number string to find and increment result whenever a digit divides N . ; Driver Code
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 for digit in range ( 2 , 10 ) : NEW_LINE INDENT if ( divisible ( N , digit ) ) : NEW_LINE INDENT divide [ digit ] = True ; NEW_LINE DEDENT DEDENT result = 0 ; NEW_LINE for i in range ( len ( N ) ) : NEW_LINE INDENT if ( divide [ ( ord ( N [ i ] ) - ord ( '0' ) ) ] == True ) : NEW_LINE INDENT result += 1 ; NEW_LINE DEDENT DEDENT return result ; NEW_LINE DEDENT N = "122324" ; NEW_LINE print ( allDigits ( N ) ) ; 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 print Aliquot Sequence for an input n . ; Print the first term ; Calculate next term from previous term ; Print next term ; Driver Code
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 - n NEW_LINE DEDENT def printAliquot ( n ) : NEW_LINE INDENT print ( n , end = " ▁ " ) NEW_LINE s = set ( ) NEW_LINE s . add ( n ) NEW_LINE nextt = 0 NEW_LINE while n > 0 : NEW_LINE INDENT n = getSum ( n ) NEW_LINE if n in s : NEW_LINE INDENT print ( " Repeats ▁ with " , n ) NEW_LINE break NEW_LINE DEDENT print ( n , end = " ▁ " ) NEW_LINE s . add ( n ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT printAliquot ( 12 ) NEW_LINE DEDENT
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 result ; Traverse all numbers and increment result if a number can be formed using x and y . ; If i can be formed using x and y ; Then i + x and i + y can also be formed using x and y . ; Increment result ; Driver code
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 ] ) : NEW_LINE INDENT if ( i + x <= n ) : NEW_LINE INDENT arr [ i + x ] = True NEW_LINE DEDENT if ( i + y <= n ) : NEW_LINE INDENT arr [ i + y ] = True NEW_LINE DEDENT result = result + 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT n = 15 NEW_LINE x = 5 NEW_LINE y = 7 NEW_LINE print ( countNums ( n , x , y ) ) NEW_LINE
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 not changed , then it is a prime ; Update all multiples of p ; Traverse all prime numbers ; Find reverse a number ; A number is emrip if it is not a palindrome number and its reverse is also prime . ; Mark reverse prime as false so that it 's not printed again ; Driver Code
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 INDENT if ( prime [ p ] == 1 ) : NEW_LINE INDENT for i in range ( p * 2 , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = 0 ; NEW_LINE DEDENT DEDENT p += 1 ; NEW_LINE DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ p ] == 1 ) : NEW_LINE INDENT rev = reverse ( p ) ; NEW_LINE if ( p != rev and rev <= n and prime [ rev ] == 1 ) : NEW_LINE INDENT print ( p , rev , end = " ▁ " ) ; NEW_LINE prime [ rev ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT n = 100 ; NEW_LINE printEmirp ( n ) ; NEW_LINE
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 ; Return true if sum of divisors is greater than n . ; Driver program to test above function
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 sum = sum - n NEW_LINE return sum NEW_LINE DEDENT def checkAbundant ( n ) : NEW_LINE INDENT if ( getSum ( n ) > n ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( checkAbundant ( 12 ) == 1 ) : NEW_LINE INDENT print " YES " NEW_LINE DEDENT else : NEW_LINE INDENT print " NO " NEW_LINE DEDENT if ( checkAbundant ( 15 ) == 1 ) : NEW_LINE INDENT print " YES " NEW_LINE DEDENT else : NEW_LINE INDENT print " NO " 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 power of " factor " that divides n ; If only factor ^ 1 divides n ( not higher powers ) , then return false ; n must be 1 now if it is not a prime numenr . Since prime numbers are not powerful , we return false if n is not 1. ; Driver code
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 . sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT power = 0 NEW_LINE while ( n % factor == 0 ) : NEW_LINE INDENT n = n // factor NEW_LINE power = power + 1 NEW_LINE DEDENT if ( power == 1 ) : NEW_LINE INDENT return false NEW_LINE DEDENT DEDENT return ( n == 1 ) NEW_LINE DEDENT print ( " YES " if isPowerful ( 20 ) else " NO " ) NEW_LINE print ( " YES " if isPowerful ( 27 ) else " NO " ) NEW_LINE
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 ) < 2 * n ; Driver program to test above function
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 sum NEW_LINE DEDENT def isDeficient ( n ) : NEW_LINE INDENT return ( divisorsSum ( n ) < ( 2 * n ) ) NEW_LINE DEDENT if ( isDeficient ( 12 ) ) : NEW_LINE INDENT print " YES " NEW_LINE DEDENT else : NEW_LINE INDENT print " NO " NEW_LINE DEDENT if ( isDeficient ( 15 ) ) : NEW_LINE INDENT print " YES " NEW_LINE DEDENT else : NEW_LINE INDENT print " NO " NEW_LINE DEDENT
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 NEW_LINE print ( checkHarshad ( number ) ) NEW_LINE
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 than MAX , we reduce MAX to half This array is used to separate numbers of the form i + j + 2 ij from others where 1 <= i <= j ; Main logic of Sundaram . Mark all numbers which do not generate prime number by doing 2 * i + 1 ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Returns true if n is a Smith number , else false . ; Find sum the digits of prime factors of n ; If primes [ i ] is a prime factor , add its digits to pDigitSum . ; If n != 1 then one prime factor still to be summed up ; All prime factors digits summed up Now sum the original number digits ; If sum of digits in prime factors and sum of digits in original number are same , then return true . Else return false . ; Driver method Finding all prime numbers before limit . These numbers are used to find prime factors .
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 ] = 1 NEW_LINE j = j + 2 * i + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT primes . append ( 2 ) NEW_LINE i = 1 NEW_LINE while i <= MAX / 2 : NEW_LINE INDENT if marked [ i ] == 0 : NEW_LINE INDENT primes . append ( 2 * i + 1 ) NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT DEDENT def isSmith ( n ) : NEW_LINE INDENT original_no = n NEW_LINE pDigitSum = 0 ; NEW_LINE i = 0 NEW_LINE while ( primes [ i ] <= n / 2 ) : NEW_LINE INDENT while n % primes [ i ] == 0 : NEW_LINE INDENT p = primes [ i ] NEW_LINE n = n / p NEW_LINE while p > 0 : NEW_LINE INDENT pDigitSum += ( p % 10 ) NEW_LINE p = p / 10 NEW_LINE DEDENT DEDENT i = i + 1 NEW_LINE DEDENT if not n == 1 and not n == original_no : NEW_LINE INDENT while n > 0 : NEW_LINE INDENT pDigitSum = pDigitSum + n % 10 NEW_LINE n = n / 10 NEW_LINE DEDENT DEDENT sumDigits = 0 NEW_LINE while original_no > 0 : NEW_LINE INDENT sumDigits = sumDigits + original_no % 10 NEW_LINE original_no = original_no / 10 NEW_LINE DEDENT return pDigitSum == sumDigits NEW_LINE DEDENT sieveSundaram ( ) ; NEW_LINE print " Printing ▁ first ▁ few ▁ Smith ▁ Numbers ▁ using ▁ isSmith ( ) " NEW_LINE i = 1 NEW_LINE while i < 500 : NEW_LINE INDENT if isSmith ( i ) : NEW_LINE INDENT print i , NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT
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 are not Karprekar numbers ; Find sum of current parts and compare with n ; compare with original number ; Driver method
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_digits : NEW_LINE INDENT r_digits = r_digits + 1 NEW_LINE eq_parts = ( int ) ( math . pow ( 10 , r_digits ) ) NEW_LINE if eq_parts == n : NEW_LINE INDENT continue NEW_LINE DEDENT sum = sq_n / eq_parts + sq_n % eq_parts NEW_LINE if sum == n : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT i = 1 NEW_LINE while i < 10000 : NEW_LINE INDENT if ( iskaprekar ( i ) ) : NEW_LINE INDENT print i , " ▁ " , NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT
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 either reach x or a number greate than x ; Next term is sum of previous n terms ; When the control comes out of the while loop , either the next_term is equal to the number or greater than it . If next_term is equal to x , then x is a Keith number , else not ; Driver Code
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_LINE INDENT next_term = 0 ; NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT next_term += terms [ i - j ] ; NEW_LINE DEDENT terms . append ( next_term ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT return ( next_term == x ) ; NEW_LINE DEDENT print ( " Yes " ) if ( isKeith ( 14 ) ) else print ( " No " ) ; NEW_LINE print ( " Yes " ) if ( isKeith ( 12 ) ) else print ( " No " ) ; NEW_LINE print ( " Yes " ) if ( isKeith ( 197 ) ) else print ( " No " ) ; NEW_LINE
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 number and update sum ; Driver code
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 NEW_LINE sm = sm + ef2 NEW_LINE DEDENT return sm NEW_LINE DEDENT limit = 400 NEW_LINE print ( evenFibSum ( limit ) ) NEW_LINE
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 only once ; Otherwise print both ; Function to calculate all divisors having exactly k divisors between a and b ; calculate only for perfect square numbers ; check if number is perfect square or not ; total divisors of number equals to k or not ; Driver program to run the case
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 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = count + 2 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT def kDivisors ( a , b , k ) : NEW_LINE INDENT for i in range ( a , b + 1 ) : NEW_LINE INDENT if ( isPerfect ( i ) ) : NEW_LINE INDENT if ( divisorsCount ( i ) == k ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT a = 2 NEW_LINE b = 49 NEW_LINE k = 3 NEW_LINE print ( kDivisors ( a , b , k ) ) NEW_LINE
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 the smallest prime that divides i ; Initialize the smallest_prime factors of all to infinity ; to be built like eratosthenes sieve ; prime number will have its smallest_prime equal to itself ; if ' i ' is the first prime number reaching 'j ; number of divisors of n = ( p1 ^ k1 ) * ( p2 ^ k2 ) . . . ( pn ^ kn ) are equal to ( k1 + 1 ) * ( k2 + 1 ) . . . ( kn + 1 ) . This functionfinds the number of divisors of all numbersin range [ 1 , maxn ) and stores it in divisors [ ] divisors [ i ] stores the number of divisors i has ; we can obtain the prime factorization of the number n n = ( p1 ^ k1 ) * ( p2 ^ k2 ) . . . ( pn ^ kn ) using the smallest_prime [ ] array , we keep dividing n by its smallest_prime until it becomes 1 , whilst we check if we have need to set k zero ; use p ^ k , initialize k to 0 ; builds segment tree for divisors [ ] array ; leaf node ; build left and right subtree ; combine the information from left and right subtree at current node ; returns the maximum number of divisors in [ l , r ] ; If current node 's range is disjoint with query range ; If the current node stores information for the range that is completely inside the query range ; Returns maximum number of divisors from left or right subtree ; Driver code ; First find smallest prime divisors for all the numbers ; Then build the divisors [ ] array to store the number of divisors ; Build segment tree for the divisors [ ] array
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 , maxn ) : NEW_LINE INDENT if ( smallest_prime [ i ] == INF ) : NEW_LINE INDENT smallest_prime [ i ] = i NEW_LINE for j in range ( i * i , maxn , i ) : NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT if ( smallest_prime [ j ] > i ) : NEW_LINE INDENT smallest_prime [ j ] = i NEW_LINE DEDENT DEDENT def buildDivisorsArray ( ) : NEW_LINE INDENT for i in range ( 1 , maxn ) : NEW_LINE INDENT divisors [ i ] = 1 NEW_LINE n = i NEW_LINE p = smallest_prime [ i ] NEW_LINE k = 0 NEW_LINE while ( n > 1 ) : NEW_LINE INDENT n = n // p NEW_LINE k += 1 NEW_LINE if ( smallest_prime [ n ] != p ) : NEW_LINE INDENT divisors [ i ] = divisors [ i ] * ( k + 1 ) NEW_LINE k = 0 NEW_LINE DEDENT p = smallest_prime [ n ] NEW_LINE DEDENT DEDENT DEDENT def buildSegtmentTree ( node , a , b ) : NEW_LINE INDENT if ( a == b ) : NEW_LINE INDENT segmentTree [ node ] = divisors [ a ] NEW_LINE return NEW_LINE DEDENT buildSegtmentTree ( 2 * node , a , ( a + b ) // 2 ) NEW_LINE buildSegtmentTree ( 2 * node + 1 , ( ( a + b ) // 2 ) + 1 , b ) NEW_LINE segmentTree [ node ] = max ( segmentTree [ 2 * node ] , segmentTree [ 2 * node + 1 ] ) NEW_LINE DEDENT def query ( node , a , b , l , r ) : NEW_LINE INDENT if ( l > b or a > r ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( a >= l and b <= r ) : NEW_LINE INDENT return segmentTree [ node ] NEW_LINE DEDENT return max ( query ( 2 * node , a , ( a + b ) // 2 , l , r ) , query ( 2 * node + 1 , ( ( a + b ) // 2 ) + 1 , b , l , r ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT findSmallestPrimeFactors ( ) NEW_LINE buildDivisorsArray ( ) NEW_LINE buildSegtmentTree ( 1 , 1 , maxn - 1 ) NEW_LINE print ( " Maximum ▁ divisors ▁ that ▁ a ▁ number ▁ has ▁ " , " ▁ in ▁ [ 1 , ▁ 100 ] ▁ are ▁ " , query ( 1 , 1 , maxn - 1 , 1 , 100 ) ) NEW_LINE print ( " Maximum ▁ divisors ▁ that ▁ a ▁ number ▁ has " , " ▁ in ▁ [ 10 , ▁ 48 ] ▁ are ▁ " , query ( 1 , 1 , maxn - 1 , 10 , 48 ) ) NEW_LINE print ( " Maximum ▁ divisors ▁ that ▁ a ▁ number ▁ has " , " ▁ in ▁ [ 1 , ▁ 10 ] ▁ are ▁ " , query ( 1 , 1 , maxn - 1 , 1 , 10 ) ) NEW_LINE DEDENT
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 non prime ; If i is the third prime factor of j then add it to result as it has at least three prime factors . ; Sort all smart numbers ; return n 'th smart number ; Driver Code
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 if ( ( primes [ j ] + 3 ) == 0 ) : NEW_LINE INDENT result . append ( j ) ; NEW_LINE DEDENT j = j + i ; NEW_LINE DEDENT DEDENT DEDENT result . sort ( ) ; NEW_LINE return result [ n - 1 ] ; NEW_LINE DEDENT n = 50 ; NEW_LINE print ( smartNumber ( n ) ) ; 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 y because in that case first recursive call exchanges roles of x and y . ; Driver code
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 of a ; stores number of common divisors ; Find the count of prime factors of b using distinct prime factors of a ; Prime factor of common divisor has minimum cnt of both a and b ; Driver code
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_LINE INDENT ma [ a ] = 1 NEW_LINE DEDENT DEDENT def commDiv ( a , b ) : NEW_LINE INDENT primeFactorize ( a ) NEW_LINE res = 1 NEW_LINE for key , value in ma . items ( ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( b % key == 0 ) : NEW_LINE INDENT b /= key NEW_LINE cnt += 1 NEW_LINE DEDENT res *= ( min ( cnt , value ) + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT a = 12 NEW_LINE b = 24 NEW_LINE print ( commDiv ( a , b ) ) NEW_LINE
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 count all numbers of the form x + i * p such that x + i * p is in range [ 1 , n ] ; The largest number in the form of x + p * i in range [ 1 , n ] ; Add count of numbers of the form x + p * i . 1 is added for x itself . ; Driver code
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 int ( ans ) ; NEW_LINE DEDENT n = 10 ; NEW_LINE p = 5 ; NEW_LINE print ( findCountOfSolutions ( n , p ) ) ; NEW_LINE
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 form of number " asc " ; Get all four dgits in descending order in the form of number " desc " ; Get the difference of two numbers ; If difference is same as previous , we have reached kaprekar 's constant ; Else recur ; A wrapper over kaprekarRec ( ) ; Trying few four digit numbers , we always get 6174
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 in range ( 4 ) : NEW_LINE INDENT asc = asc * 10 + digits [ i ] ; NEW_LINE DEDENT digits . sort ( ) ; NEW_LINE desc = 0 ; NEW_LINE for i in range ( 3 , - 1 , - 1 ) : NEW_LINE INDENT desc = desc * 10 + digits [ i ] ; NEW_LINE DEDENT diff = abs ( asc - desc ) ; NEW_LINE if ( diff == prev ) : NEW_LINE INDENT return diff ; NEW_LINE DEDENT return kaprekarRec ( diff , prev ) ; NEW_LINE DEDENT def kaprekar ( n ) : NEW_LINE INDENT rev = 0 ; NEW_LINE return kaprekarRec ( n , rev ) ; NEW_LINE DEDENT print ( kaprekar ( 1000 ) ) ; NEW_LINE print ( kaprekar ( 1112 ) ) ; NEW_LINE print ( kaprekar ( 9812 ) ) ; NEW_LINE
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_LINE DEDENT DEDENT DEDENT d = s - pSq ; NEW_LINE P = d / ( 2.0 * N ) ; NEW_LINE A = N + P ; NEW_LINE INDENT sqrt_of_s = A - ( ( P * P ) / ( 2.0 * A ) ) ; NEW_LINE return sqrt_of_s ; NEW_LINE DEDENT num = 9.2345 ; NEW_LINE sqroot_of_num = sqroot ( num ) ; NEW_LINE print ( " Square ▁ root ▁ of ▁ " , num , " = " , round ( ( sqroot_of_num * 100000.0 ) / 100000.0 , 5 ) ) ; NEW_LINE
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 for remaining part ; If division gives mod as 2 , then break as 2 + power of 3 for remaining part ; Driver code to test above methods
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 == 3 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT maxProduct = 0 NEW_LINE if ( N % 3 == 0 ) : NEW_LINE INDENT maxProduct = power ( 3 , int ( N / 3 ) ) NEW_LINE return maxProduct NEW_LINE DEDENT elif ( N % 3 == 1 ) : NEW_LINE INDENT maxProduct = 2 * 2 * power ( 3 , int ( N / 3 ) - 1 ) NEW_LINE return maxProduct NEW_LINE DEDENT elif ( N % 3 == 2 ) : NEW_LINE INDENT maxProduct = 2 * power ( 3 , int ( N / 3 ) ) NEW_LINE return maxProduct NEW_LINE DEDENT DEDENT maxProduct = breakInteger ( 10 ) NEW_LINE print ( maxProduct ) NEW_LINE
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 ( num ) : NEW_LINE INDENT rev_num = 0 NEW_LINE while ( num <= 4294967295 ) : NEW_LINE INDENT rev_num = reversDigits ( num ) NEW_LINE num = num + rev_num NEW_LINE if ( isPalindrome ( num ) ) : NEW_LINE INDENT print num NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT if ( num > 4294967295 ) : NEW_LINE INDENT print " No ▁ palindrome ▁ exist " NEW_LINE DEDENT DEDENT DEDENT DEDENT ReverseandAdd ( 195 ) NEW_LINE ReverseandAdd ( 265 ) NEW_LINE
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_LINE DEDENT else : NEW_LINE INDENT return ( gcd ( a >> 1 , b >> 1 ) << 1 ) NEW_LINE DEDENT DEDENT if ( ( ~ b & 1 ) == 1 ) : NEW_LINE INDENT return gcd ( a , b >> 1 ) NEW_LINE DEDENT if ( a > b ) : NEW_LINE INDENT return gcd ( ( a - b ) >> 1 , b ) NEW_LINE DEDENT return gcd ( ( b - a ) >> 1 , a ) NEW_LINE DEDENT a , b = 34 , 17 NEW_LINE print ( " Gcd ▁ of ▁ given ▁ numbers ▁ is ▁ " , gcd ( a , b ) ) NEW_LINE
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 ) : NEW_LINE INDENT if ( ( sum [ r + 1 ] - sum [ l ] ) % 3 == 0 ) : NEW_LINE INDENT print ( " Divisible ▁ by ▁ 3" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ divisible ▁ by ▁ 3" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = "12468236544" NEW_LINE prepareSum ( n ) NEW_LINE query ( 0 , 1 ) NEW_LINE query ( 1 , 2 ) NEW_LINE query ( 3 , 6 ) NEW_LINE query ( 0 , 10 ) NEW_LINE DEDENT
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 digits ; append current digit to number ; recurse for next digit with reduced sum ; This is mainly a wrapper over findNDigitNumsUtil . It explicitly handles leading digit ; output array to store N - digit numbers ; fill 1 st position by every digit from 1 to 9 and calls findNDigitNumsUtil ( ) for remaining positions ; Driver Code
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 , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT out [ index ] = chr ( i + ord ( '0' ) ) NEW_LINE findNDigitNumsUtil ( n , sum - i , out , index + 1 ) NEW_LINE DEDENT DEDENT def findNDigitNums ( n , sum ) : NEW_LINE INDENT out = [ False ] * ( n + 1 ) NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT out [ 0 ] = chr ( i + ord ( '0' ) ) NEW_LINE findNDigitNumsUtil ( n , sum - i , out , 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 NEW_LINE sum = 3 NEW_LINE findNDigitNums ( n , sum ) NEW_LINE DEDENT
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 DEDENT print ( armstrong ( 153 ) ) NEW_LINE print ( armstrong ( 120 ) ) NEW_LINE
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 copy of num . ; Base case ( needed for recursion termination ) : This statement / mainly compares the first digit with the last digit ; This is the key line in this method . Note that all recursive / calls have a separate copy of num , but they all share same copy of dupNum . We divide num while moving up the recursion tree ; The following statements are executed when we move up the recursion call tree ; At this point , if num % 10 contains ith digit from beginning , then ( dupNum ) % 10 contains ith digit from end ; The main function that uses recursive function isPalUtil ( ) to find out whether num is palindrome or not ; If num is negative , make it positive ; Create a separate copy of num , so that modifications made to address dupNum don 't change the input number. dupNum = num; dupNum = num ; Function to generate all primes and checking whether number is palindromic or not ; 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 ; Update all multiples of p ; Print all palindromic prime numbers ; checking whether the given number is prime palindromic or not ; Driver Code
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_LINE DEDENT dupNum = int ( dupNum / 10 ) ; NEW_LINE return ( num % 10 == ( dupNum ) % 10 ) ; NEW_LINE DEDENT def isPal ( num ) : NEW_LINE INDENT if ( num < 0 ) : NEW_LINE INDENT num = - num ; NEW_LINE DEDENT return isPalUtil ( num , dupNum ) ; NEW_LINE DEDENT def printPalPrimesLessThanN ( n ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT p += 1 ; NEW_LINE DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ p ] and isPal ( p ) ) : NEW_LINE INDENT print ( p , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT n = 100 ; NEW_LINE print ( " Palindromic ▁ primes ▁ smaller " , " than ▁ or ▁ equal ▁ to " , n , " are ▁ : " ) ; NEW_LINE printPalPrimesLessThanN ( n ) ; NEW_LINE
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 is to handle the case when n is a prime number greater than 2 ; A function to print the first n numbers that are k - almost primes . ; Print this number if it is k - prime ; Increment count of k - primes printed so far ; Driver Code
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 ; NEW_LINE DEDENT i = i + 2 ; NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT return ( count ) ; NEW_LINE DEDENT def printKAlmostPrimes ( k , n ) : NEW_LINE INDENT i = 1 ; NEW_LINE num = 2 NEW_LINE while ( i <= n ) : NEW_LINE INDENT if ( countPrimeFactors ( num ) == k ) : NEW_LINE INDENT print ( num , end = " " ) ; NEW_LINE print ( " ▁ " , end = " " ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT num += 1 ; NEW_LINE DEDENT return ; NEW_LINE DEDENT n = 10 ; NEW_LINE k = 2 ; NEW_LINE print ( " First ▁ n ▁ k - almost ▁ prime ▁ numbers : " ) ; NEW_LINE printKAlmostPrimes ( k , n ) ; NEW_LINE
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 final fraction obtained finding LCM of den1 and den2 LCM * GCD = a * b ; Changing the fractions to have same denominator Numerator of the final fraction obtained ; Calling function to convert final fraction into it 's simplest form ; Driver Code
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b ; NEW_LINE DEDENT return gcd ( b % a , a ) ; NEW_LINE DEDENT def lowest ( den3 , num3 ) : NEW_LINE INDENT common_factor = gcd ( num3 , den3 ) ; NEW_LINE den3 = int ( den3 / common_factor ) ; NEW_LINE num3 = int ( num3 / common_factor ) ; NEW_LINE print ( num3 , " / " , den3 ) ; NEW_LINE DEDENT def addFraction ( num1 , den1 , num2 , den2 ) : NEW_LINE INDENT den3 = gcd ( den1 , den2 ) ; NEW_LINE den3 = ( den1 * den2 ) / den3 ; NEW_LINE num3 = ( ( num1 ) * ( den3 / den1 ) + ( num2 ) * ( den3 / den2 ) ) ; NEW_LINE lowest ( den3 , num3 ) ; NEW_LINE DEDENT num1 = 1 ; den1 = 500 ; NEW_LINE num2 = 2 ; den2 = 1500 ; NEW_LINE print ( num1 , " / " , den1 , " ▁ + ▁ " , num2 , " / " , den2 , " ▁ is ▁ equal ▁ to ▁ " , end = " " ) ; NEW_LINE addFraction ( num1 , den1 , num2 , den2 ) ; NEW_LINE
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 number of digits ; 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 x = ( ( n * math . log10 ( n / math . e ) + math . log10 ( 2 * math . pi * n ) / 2.0 ) ) ; NEW_LINE return math . floor ( x ) + 1 ; NEW_LINE DEDENT print ( findDigits ( 1 ) ) ; NEW_LINE print ( findDigits ( 50000000 ) ) ; NEW_LINE print ( findDigits ( 1000000000 ) ) ; NEW_LINE print ( findDigits ( 120 ) ) ; NEW_LINE
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 ( digits ) + 1 ; NEW_LINE DEDENT print ( findDigits ( 1 ) ) ; NEW_LINE print ( findDigits ( 5 ) ) ; NEW_LINE print ( findDigits ( 10 ) ) ; NEW_LINE print ( findDigits ( 120 ) ) ; NEW_LINE
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_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 3 , 4 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " The ▁ Number ▁ of ▁ Subarrays " , " with ▁ even ▁ sum ▁ is " , countEvenSum ( arr , n ) ) NEW_LINE DEDENT
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 initialized as 1 because there a single even element is also counted as a subarray ; Initialize count . sum is sum of elements under modulo 2 and ending with arr [ i ] . ; i ' th ▁ iteration ▁ computes ▁ sum ▁ of ▁ arr [ 0 . . i ] ▁ ▁ under ▁ modulo ▁ 2 ▁ and ▁ increments ▁ even / odd ▁ ▁ count ▁ according ▁ to ▁ sum ' s value ; 2 is added to handle negative numbers ; Increment even / odd count ; Use handshake lemma to count even subarrays ( Note that an even cam be formed by two even or two odd ) ; Driver code
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 + ( temp [ 1 ] * ( temp [ 1 ] - 1 ) // 2 ) NEW_LINE return ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 3 , 4 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " The ▁ Number ▁ of ▁ Subarrays ▁ with ▁ even " " ▁ sum ▁ is " , countEvenSum ( arr , n ) ) NEW_LINE DEDENT