"0 | Returns the maximum value that can be put in a knapsack of capacity W ; Base Case ; If weight of the nth item is more than Knapsack capacity W , then this item cannot be included in the optimal solution ; Return the maximum of two cases : ( 1 ) nth item included ( 2 ) not included ; Driver Code"
Solution in php:

< ? php function knapSack ( $ W , $ wt , $ val , $ n ) { if ( $ n == 0 $ W == 0 ) return 0 ; if ( $ wt [ $ n - 1 ] > $ W ) return knapSack ( $ W , $ wt , $ val , $ n - 1 ) ; else return max ( $ val [ $ n - 1 ] + knapSack ( $ W - $ wt [ $ n - 1 ] , $ wt , $ val , $ n - 1 ) , knapSack ( $ W , $ wt , $ val , $ n - 1 ) ) ; } $ val = array ( 60 , 100 , 120 ) ; $ wt = array ( 10 , 20 , 30 ) ; $ W = 50 ; $ n = count ( $ val ) ; echo knapSack ( $ W , $ wt , $ val , $ n ) ; ? >


"0 | Returns the maximum value that can be put in a knapsack of capacity W ; Build table K [ ] [ ] in bottom up manner ; Driver Code"
Solution in php:


"1 to n bit numbers with no consecutive 1 s in binary representation | Print all numbers upto n bits with no consecutive set bits . ; Let us first compute 2 raised to power n . ; loop 1 to n to check all the numbers ; A number i doesn ' t ▁ contain ▁ ▁ consecutive ▁ set ▁ bits ▁ if ▁ ▁ bitwise ▁ and ▁ of ▁ i ▁ and ▁ left ▁ ▁ shifted ▁ i ▁ do ' t contain a commons set bit . ; Driver code"
Solution in php:

< ? php function printNonConsecutive ( $ n ) { $ p = ( 1 << $ n ) ; for ( $ i = 1 ; $ i < $ p ; $ i ++ ) if ( ( $ i & ( $ i << 1 ) ) == 0 ) echo $ i . " " ; } $ n = 3 ; printNonConsecutive ( $ n ) ; ? >


"10 's Complement of a decimal number | Function to find 10 's complement ; Calculating total digits in num ; restore num ; calculate 10 's complement ; Driver code"
Solution in php:

 < ? php function complement ( $ num ) { $ i ; $ len = 0 ; $ comp ; $ temp = $ num ; while ( 1 ) { $ len ++ ; $ num = ( int ) ( $ num / 10 ) ; if ( abs ( $ num ) == 0 ) break ; } $ num = $ temp ; $ comp = pow ( 10 , $ len ) - $ num ; return $ comp ; } echo complement ( 25 ) . "
 " ; echo complement ( 456 ) ; ? >


"2 's complement for a givin string using XOR | PHP program to find 2 's complement using XOR. ; A flag used to find if a 1 bit is seen or not . ; xor operator is used to flip the ; bits after converting in to ASCII values ; if there is no 1 in the string so just add 1 in starting of string and return ; Driver code"
Solution in php:

< ? php function TwoscomplementbyXOR ( $ str ) { $ n = strlen ( $ str ) ; $ check_bit = 0 ; for ( $ i = $ n - 1 ; $ i >= 0 ; $ i -- ) { if ( $ str [ $ i ] == '0' && $ check_bit == 0 ) { continue ; } else { if ( $ check_bit == 1 ) $ str [ $ i ] = ( $ str [ $ i ] - '0' ) ^ 1 + '0' ; $ check_bit = 1 ; } } if ( $ check_bit == 0 ) return "1" + $ str ; else return $ str ; } $ str = "101" ; echo TwoscomplementbyXOR ( $ str ) ; ? >


"3 | Function that returns true if n is an Osiris number ; 3 rd digit ; 2 nd digit ; 1 st digit ; Check the required condition ; Driver code"
Solution in php:

< ? php function isOsiris ( $ n ) { $ a = $ n % 10 ; $ b = floor ( $ n / 10 ) % 10 ; $ c = floor ( $ n / 100 ) ; $ digit_sum = $ a + $ b + $ c ; if ( $ n == ( 2 * ( $ digit_sum ) * 11 ) ) { return true ; } return false ; } $ n = 132 ; if ( isOsiris ( $ n ) ) echo " Yes " ; else echo " No " ; ? >


"9 's complement of a decimal number | PHP program to find 9 's complement of a number. ; Driver code"
Solution in php:

< ? php function complement ( $ number ) { for ( $ i = 0 ; $ i < strlen ( $ number ) ; $ i ++ ) if ( $ number [ $ i ] != ' . ' ) $ number [ $ i ] = '9' - $ number [ $ i ] + '0' ; echo "9 ' s ▁ complement ▁ is ▁ : ▁ " , $ number ; } $ number = "345.45" ; complement ( $ number ) ; ? >


"A Boolean Matrix Question | PHP Code For A Boolean Matrix Question ; Initialize all values of row [ ] as 0 ; Initialize all values of col [ ] as 0 ; Store the rows and columns to be marked as 1 in row [ ] and col [ ] arrays respectively ; Modify the input matrix mat [ ] using the above constructed row [ ] and col [ ] arrays ; A utility function to print a 2D matrix ; Driver code"
Solution in php:

 < ? php $ R = 3 ; $ C = 4 ; function modifyMatrix ( & $ mat ) { global $ R , $ C ; $ row = array ( ) ; $ col = array ( ) ; for ( $ i = 0 ; $ i < $ R ; $ i ++ ) { $ row [ $ i ] = 0 ; } for ( $ i = 0 ; $ i < $ C ; $ i ++ ) { $ col [ $ i ] = 0 ; } for ( $ i = 0 ; $ i < $ R ; $ i ++ ) { for ( $ j = 0 ; $ j < $ C ; $ j ++ ) { if ( $ mat [ $ i ] [ $ j ] == 1 ) { $ row [ $ i ] = 1 ; $ col [ $ j ] = 1 ; } } } for ( $ i = 0 ; $ i < $ R ; $ i ++ ) { for ( $ j = 0 ; $ j < $ C ; $ j ++ ) { if ( $ row [ $ i ] == 1 $ col [ $ j ] == 1 ) { $ mat [ $ i ] [ $ j ] = 1 ; } } } } function printMatrix ( & $ mat ) { global $ R , $ C ; for ( $ i = 0 ; $ i < $ R ; $ i ++ ) { for ( $ j = 0 ; $ j < $ C ; $ j ++ ) { echo $ mat [ $ i ] [ $ j ] . " " ; } echo "
 " ; } } $ mat = array ( array ( 1 , 0 , 0 , 1 ) , array ( 0 , 0 , 1 , 0 ) , array ( 0 , 0 , 0 , 0 ) ) ; echo " Input ▁ Matrix ▁
 " ; printMatrix ( $ mat ) ; modifyMatrix ( $ mat ) ; echo " Matrix ▁ after ▁ modification ▁
 " ; printMatrix ( $ mat ) ; ? >


"A Boolean Matrix Question | PHP Code For A Boolean Matrix Question ; variables to check if there are any 1 in first row and column ; updating the first row and col if 1 is encountered ; Modify the input matrix mat [ ] using the first row and first column of Matrix mat ; modify first row if there was any 1 ; modify first col if there was any 1 ; A utility function to print a 2D matrix ; Driver Code"
Solution in php:


"A Product Array Puzzle | Function to print product array for a given array arr [ ] of size n ; Base case ; Allocate memory for the productarray ; Initialize the product array as 1 ; In this loop , temp variable contains product of elements on left side excluding arr [ i ] ; Initialize temp to 1 for product on right side ; In this loop , temp variable contains product of elements on right side excluding arr [ i ] ; print the constructed prod array ; Driver Code"
Solution in php:

 < ? php function productArray ( $ arr , $ n ) { if ( $ n == 1 ) { echo "0" ; return ; } $ i ; $ temp = 1 ; $ prod = array ( ) ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) $ prod [ $ j ] = 1 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ prod [ $ i ] = $ temp ; $ temp *= $ arr [ $ i ] ; } $ temp = 1 ; for ( $ i = $ n - 1 ; $ i >= 0 ; $ i -- ) { $ prod [ $ i ] *= $ temp ; $ temp *= $ arr [ $ i ] ; } for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ prod [ $ i ] , " ▁ " ; return ; } $ arr = array ( 10 , 3 , 5 , 6 , 2 ) ; $ n = count ( $ arr ) ; echo " The ▁ product ▁ array ▁ is ▁ : ▁
 " ; productArray ( $ arr , $ n ) ; ? >


"A Space Optimized DP solution for 0 | val [ ] is for storing maximum profit for each weight wt [ ] is for storing weights n number of item W maximum capacity of bag mat [ 2 ] [ W + 1 ] to store final result ; matrix to store final result ; iterate through all items ; one by one traverse each element ; traverse all weights j <= W ; if i is odd that mean till now we have odd number of elements so we store result in 1 th indexed row ; check for each value ; include element ; exclude element ; if i is even that mean till now we have even number of elements so we store result in 0 th indexed row ; Return mat [ 0 ] [ W ] if n is odd , else mat [ 1 ] [ W ] ; Driver Code"
Solution in php:


"A Space Optimized Solution of LCS | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Find lengths of two strings ; Binary index , used to index current row and previous row . ; Compute current binary index ; Last filled entry contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; Driver code"
Solution in php:


"A Sum Array Puzzle | PHP implementation of above approach ; Allocate memory for temporary arrays leftSum [ ] , rightSum [ ] and Sum [ ] ; Left most element of left array is always 0 ; Rightmost most element of right array is always 0 ; Construct the left array ; Construct the right array ; Construct the sum array using left [ ] and right [ ] ; print the constructed prod array ; Driver Code"
Solution in php:

< ? php function sumArray ( $ arr , $ n ) { $ leftSum = array_fill ( 0 , $ n , 0 ) ; $ rightSum = array_fill ( 0 , $ n , 0 ) ; $ Sum = array_fill ( 0 , $ n , 0 ) ; $ leftSum [ 0 ] = 0 ; $ rightSum [ $ n - 1 ] = 0 ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) $ leftSum [ $ i ] = $ arr [ $ i - 1 ] + $ leftSum [ $ i - 1 ] ; for ( $ j = $ n - 2 ; $ j >= 0 ; $ j -- ) $ rightSum [ $ j ] = $ arr [ $ j + 1 ] + $ rightSum [ $ j + 1 ] ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ Sum [ $ i ] = $ leftSum [ $ i ] + $ rightSum [ $ i ] ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ Sum [ $ i ] . " ▁ " ; } $ arr = array ( 3 , 6 , 4 , 8 , 9 ) ; $ n = count ( $ arr ) ; sumArray ( $ arr , $ n ) ; ? >


"A product array puzzle | Set 2 ( O ( 1 ) Space ) | epsilon value to maintain precision ; to hold sum of all values ; output product for each index antilog to find original product value ; Driver code"
Solution in php:

 < ? php $ EPS = 1e-9 ; function productPuzzle ( $ a , $ n ) { global $ EPS ; $ sum = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ sum += ( double ) log10 ( $ a [ $ i ] ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo ( int ) ( $ EPS + pow ( ( double ) 10.00 , $ sum - log10 ( $ a [ $ i ] ) ) ) . " ▁ " ; } $ a = array ( 10 , 3 , 5 , 6 , 2 ) ; $ n = count ( $ a ) ; echo " The ▁ product ▁ array ▁ is : ▁
 " ; productPuzzle ( $ a , $ n ) ; ? >


"AKS Primality Test | array used to store coefficients . ; function to calculate the coefficients of ( x - 1 ) ^ n - ( x ^ n - 1 ) with the help of Pascal 's triangle . ; function to check whether the number is prime or not ; Calculating all the coefficients by the function coef and storing all the coefficients in c array . ; checking all the coefficients whether they are divisible by n or not . if n is not prime , then loop breaks and ( i > 0 ) . ; Return true if all coefficients are divisible by n . ; Driver Code"
Solution in php:


"Absolute Difference between the Sum of Non | Function to find the difference between the sum of non - primes and the sum of primes of an array . ; Find maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store the sum of primes in S1 and the sum of non primes in S2 ; the number is prime ; the number is non - prime ; Return the absolute difference ; Get the array ; Find the absolute difference"
Solution in php:

< ? php function CalculateDifference ( $ arr , $ n ) { $ max_val = PHP_INT_MIN ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] > $ max_val ) $ max_val = $ arr [ $ i ] ; } $ prime = array_fill ( 0 , $ max_val + 1 , true ) ; $ prime [ 0 ] = false ; $ prime [ 1 ] = false ; for ( $ p = 2 ; $ p * $ p <= $ max_val ; $ p ++ ) { if ( $ prime [ $ p ] == true ) { for ( $ i = $ p * 2 ; $ i <= $ max_val ; $ i += $ p ) $ prime [ $ i ] = false ; } } $ S1 = 0 ; $ S2 = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ prime [ $ arr [ $ i ] ] ) { $ S1 += $ arr [ $ i ] ; } else if ( $ arr [ $ i ] != 1 ) { $ S2 += $ arr [ $ i ] ; } } return abs ( $ S2 - $ S1 ) ; } $ arr = array ( 1 , 3 , 5 , 10 , 15 , 7 ) ; $ n = sizeof ( $ arr ) ; echo CalculateDifference ( $ arr , $ n ) ; ? >


"Absolute Difference of all pairwise consecutive elements in an array | Function to print pairwise absolute difference of consecutive elements ; absolute difference between consecutive numbers ; Driver Code"
Solution in php:

< ? php function pairwiseDifference ( $ arr , $ n ) { $ diff = 0 ; for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) { $ diff = abs ( $ arr [ $ i ] - $ arr [ $ i + 1 ] ) ; echo $ diff . " " ; } } $ arr = array ( 4 , 10 , 15 , 5 , 6 ) ; $ n = sizeof ( $ arr ) ; pairwiseDifference ( $ arr , $ n ) ; ? >


"Absolute difference between sum and product of roots of a quartic equation | Function taking coefficient of each term of equation as input ; Finding sum of roots ; Finding product of roots ; Absolute difference ; Driver code"
Solution in php:

< ? php function sumProductDifference ( $ a , $ b , $ c , $ d , $ e ) { $ rootSum = ( double ) ( -1 * $ b ) / $ a ; $ rootProduct = ( double ) $ e / $ a ; return abs ( $ rootSum - $ rootProduct ) ; } echo sumProductDifference ( 8 , 4 , 6 , 4 , 1 ) ; ? >


"Absolute difference between the Product of Non | Function to find the difference between the product of non - primes and the product of primes of an array . ; Find maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store the product of primes in P1 and the product of non primes in P2 ; the number is prime ; the number is non - prime ; Return the absolute difference ; Driver Code ; Find the absolute difference"
Solution in php:

< ? php function calculateDifference ( $ arr , $ n ) { $ max_val = max ( $ arr ) ; $ prime = array_fill ( 0 , $ max_val , true ) ; $ prime [ 0 ] = false ; $ prime [ 1 ] = false ; for ( $ p = 2 ; $ p * $ p <= $ max_val ; $ p ++ ) { if ( $ prime [ $ p ] == true ) { for ( $ i = $ p * 2 ; $ i <= $ max_val ; $ i += $ p ) $ prime [ $ i ] = false ; } } $ P1 = 1 ; $ P2 = 1 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ prime [ $ arr [ $ i ] ] ) { $ P1 *= $ arr [ $ i ] ; } else if ( $ arr [ $ i ] != 1 ) { $ P2 *= $ arr [ $ i ] ; } } return abs ( $ P2 - $ P1 ) ; } $ arr = array ( 1 , 3 , 5 , 10 , 15 , 7 ) ; $ n = count ( $ arr , COUNT_NORMAL ) ; echo CalculateDifference ( $ arr , $ n ) ; ? >


"Absolute difference between the first X and last X Digits of N | Function to find the number of digits in the integer ; Function to find the absolute difference ; Store the last x digits in last ; Count the no . of digits in N ; Remove the digits except the first x ; Store the first x digits in first ; Return the absolute difference between the first and last ; Driver code"
Solution in php:

< ? php function digitsCount ( $ n ) { $ len = 0 ; while ( $ n > 0 ) { $ len ++ ; $ n = ( int ) ( $ n / 10 ) ; } return $ len ; } function absoluteFirstLast ( $ n , $ x ) { $ i = 0 ; $ mod = 1 ; while ( $ i < $ x ) { $ mod *= 10 ; $ i ++ ; } $ last = $ n % $ mod ; $ len = digitsCount ( $ n ) ; while ( $ len != $ x ) { $ n = ( int ) ( $ n / 10 ) ; $ len -- ; } $ first = $ n ; return abs ( $ first - $ last ) ; } $ n = 21546 ; $ x = 2 ; echo absoluteFirstLast ( $ n , $ x ) ; ? >


"Absolute distinct count in a sorted array | The function returns return number of distinct absolute values among the elements of the array ; initialize count as number of elements ; Remove duplicate elements from the left of the current window ( i , j ) and also decrease the count ; Remove duplicate elements from the right of the current window ( i , j ) and also decrease the count ; break if only one element is left ; Now look for the zero sum pair in current window ( i , j ) ; decrease the count if ( positive , negative ) pair is encountered ; Driver code"
Solution in php:

< ? php function distinctCount ( $ arr , $ n ) { $ count = $ n ; $ i = 0 ; $ j = $ n - 1 ; $ sum = 0 ; while ( $ i < $ j ) { while ( $ i != $ j && $ arr [ $ i ] == $ arr [ $ i + 1 ] ) { $ count -- ; $ i ++ ; } while ( $ i != $ j && $ arr [ $ j ] == $ arr [ $ j - 1 ] ) { $ count -- ; $ j -- ; } if ( $ i == $ j ) break ; $ sum = $ arr [ $ i ] + $ arr [ $ j ] ; if ( $ sum == 0 ) { $ count -- ; $ i ++ ; $ j -- ; } else if ( $ sum < 0 ) $ i ++ ; else $ j -- ; } return $ count ; } $ arr = array ( -2 , -1 , 0 , 1 , 1 ) ; $ n = sizeof ( $ arr ) ; echo " Count ▁ of ▁ absolute ▁ distinct ▁ values ▁ : ▁ " . distinctCount ( $ arr , $ n ) ; ? >


"Abundant 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 ; 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 Code"
Solution in php:

 < ? php function getSum ( $ n ) { $ sum = 0 ; for ( $ i = 1 ; $ i <= sqrt ( $ n ) ; $ i ++ ) { if ( $ n % $ i == 0 ) { if ( $ n / $ i == $ i ) $ sum = $ sum + $ i ; else { $ sum = $ sum + $ i ; $ sum = $ sum + ( $ n / $ i ) ; } } } $ sum = $ sum - $ n ; return $ sum ; } function checkAbundant ( $ n ) { return ( getSum ( $ n ) > $ n ) ; } $ k = checkAbundant ( 12 ) ? " YES
 " : " NO
 " ; echo ( $ k ) ; $ k = checkAbundant ( 15 ) ? " YES
 " : " NO
 " ; echo ( $ k ) ; ? >


"Activity Selection Problem | Greedy Algo | Prints a maximum set of activities that can be done by a single person , one at a time . n -- > Total number of activities s [ ] -- > An array that contains start time of all activities f [ ] -- > An array that contains finish time of all activities ; The first activity always gets selected ; Consider rest of the activities ; If this activity has start time greater than or equal to the finish time of previously selected activity , then select it ; Driver Code"
Solution in php:

 < ? php function printMaxActivities ( $ s , $ f , $ n ) { echo " Following ▁ activities ▁ are ▁ selected ▁ " . "
 " ; $ i = 0 ; echo $ i . " " ; for ( $ j = 1 ; $ j < $ n ; $ j ++ ) { if ( $ s [ $ j ] >= $ f [ $ i ] ) { echo $ j . " " ; $ i = $ j ; } } } $ s = array ( 1 , 3 , 0 , 5 , 8 , 5 ) ; $ f = array ( 2 , 4 , 6 , 7 , 9 , 9 ) ; $ n = sizeof ( $ s ) ; printMaxActivities ( $ s , $ f , $ n ) ; ? >


"Adam Number | To reverse Digits of numbers ; To square number ; To check Adam Number ; Square first number and square reverse digits of second number ; If reverse of b equals a then given number is Adam number ; Driver Code"
Solution in php:

< ? php function reverseDigits ( $ num ) { $ rev = 0 ; while ( $ num > 0 ) { $ rev = $ rev * 10 + $ num % 10 ; $ num = ( int ) $ num / 10 ; } return $ rev ; } function square ( $ num ) { return ( $ num * $ num ) ; } function checkAdamNumber ( $ num ) { $ a = square ( $ num ) ; $ b = square ( reverseDigits ( $ num ) ) ; if ( $ a == reverseDigits ( $ b ) ) return 0 ; return -1 ; } $ num = 12 ; if ( checkAdamNumber ( $ num ) ) echo " Adam ▁ Number " ; else echo " Not ▁ a ▁ Adam ▁ Number " ; ? >


"Add 1 to a given number | PHP Code to Add 1 to a given number ; Driver Code"
Solution in php:

< ? php function addOne ( $ x ) { return ( - ( ~ $ x ) ) ; } echo addOne ( 13 ) ; ? >


"Add 1 to a given number | PHP code to add add one to a given number ; Flip all the set bits until we find a 0 ; flip the rightmost 0 bit ; Driver Code"
Solution in php:

< ? php function addOne ( $ x ) { $ m = 1 ; while ( $ x & $ m ) { $ x = $ x ^ $ m ; $ m <<= 1 ; } $ x = $ x ^ $ m ; return $ x ; } echo addOne ( 13 ) ; ? >


"Add N digits to A such that it is divisible by B after each addition | PHP implementation of the approach ; Try all digits from ( 0 to 9 ) ; Fails in the first move itself ; Add ( n - 1 ) 0 's ; Driver Code"
Solution in php:


"Add minimum number to an array so that the sum becomes even | Function to find out minimum number ; Count odd number of terms in array ; Driver code"
Solution in php:


 < ? php function minNum ( $ arr , $ n ) { $ odd = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) if ( $ arr [ $ i ] % 2 ) $ odd = ! $ odd ; if ( $ odd ) return 1 ; return 2 ; } $ arr = array ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ) ; $ n = sizeof ( $ arr ) ; echo minNum ( $ arr , $ n ) , "
 " ; ? >


"Add n binary strings | This function adds two binary strings and return result as a third string ; Initialize result ; Initialize digit sum ; Traverse both strings starting from last characters ; Compute sum of last digits and carry ; If current digit sum is 1 or 3 , add 1 to result ; Compute carry ; Move to next digits ; function to add n binary strings ; Driver code"
Solution in php:

 < ? php function addBinaryUtil ( $ a , $ b ) { $ result = " " ; $ s = 0 ; $ i = strlen ( $ a ) - 1 ; $ j = strlen ( $ b ) - 1 ; while ( $ i >= 0 $ j >= 0 $ s == 1 ) { $ s += ( ( $ i >= 0 ) ? ord ( $ a [ $ i ] ) - ord ( '0' ) : 0 ) ; $ s += ( ( $ j >= 0 ) ? ord ( $ b [ $ j ] ) - ord ( '0' ) : 0 ) ; $ result = chr ( $ s % 2 + ord ( '0' ) ) . $ result ; $ s = ( int ) ( $ s / 2 ) ; $ i -- ; $ j -- ; } return $ result ; } function addBinary ( $ arr , $ n ) { $ result = " " ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ result = addBinaryUtil ( $ result , $ arr [ $ i ] ) ; return $ result ; } $ arr = array ( "1" , "10" , "11" ) ; $ n = count ( $ arr ) ; echo addBinary ( $ arr , $ n ) . "
 " ; ? >


"Add two numbers represented by two arrays | Return sum of two number represented by the arrays . Size of a [ ] is greater than b [ ] . It is made sure be the wrapper function ; array to store sum . ; Until we reach beginning of array . we are comparing only for second array because we have already compare the size of array in wrapper function . ; find sum of corresponding element of both array . ; Finding carry for next sum . ; If second array size is less than the first array size . ; Add carry to first array elements . ; If there is carry on adding 0 index elements . append 1 to total sum . ; Converting array into number . ; Wrapper Function ; Making first array which have greater number of element ; Driven Code"
Solution in php:


"Add two numbers using ++ and / or | Returns value of x + y without using + ; If y is positive , y times add 1 to x ; If y is negative , y times subtract 1 from x ; Driver Code"
Solution in php:


"Addition of two numbers without propagating Carry | Function to print sum of 2 numbers without propagating carry ; Reverse a ; Reverse b ; Generate sum Since length of both a and b are same , take any one of them . ; Extract digits from a and b and add ; If sum is single digit ; If sum is not single digit reverse sum ; Extract digits from sum and append to result ; Driver code"
Solution in php:


"Aliquot sum | Function to calculate sum of all proper divisors ; Driver Code"
Solution in php:

< ? php function aliquotSum ( $ n ) { $ sum = 0 ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) if ( $ n % $ i == 0 ) $ sum += $ i ; return $ sum ; } $ n = 12 ; echo ( aliquotSum ( $ n ) ) ; ? >


"All possible co | Function to count possible pairs ; total count of numbers in range ; printing count of pairs ; Driver code"
Solution in php:

 < ? php function CountPair ( $ L , $ R ) { $ x = ( $ R - $ L + 1 ) ; echo $ x / 2 , "
 " ; } $ L = 1 ; $ R = 8 ; CountPair ( $ L , $ R ) ; ? >


"All possible numbers of N digits and base B without leading zeros | function to count all permutations ; count of all permutations ; count of permutations with leading zeros ; Return the permutations without leading zeros ; Driver code"
Solution in php:

 < ? php function countPermutations ( $ N , $ B ) { $ x = pow ( $ B , $ N ) ; $ y = pow ( $ B , $ N - 1 ) ; echo ( $ x - $ y ) , "
 " ; } $ N = 6 ; $ B = 4 ; countPermutations ( $ N , $ B ) ; ? >


"Allocate minimum number of pages | Utility function to check if current minimum value is feasible or not . ; iterate over all books ; check if current number of pages are greater than curr_min that means we will get the result after mid no . of pages ; count how many students are required to distribute curr_min pages ; increment student count ; update curr_sum ; if students required becomes greater than given no . of students , return false ; else update curr_sum ; function to find minimum pages ; return - 1 if no . of books is less than no . of students ; Count total number of pages ; initialize start as 0 pages and end as total pages ; traverse until start <= end ; check if it is possible to distribute books by using mid as current minimum ; update result to current distribution as it 's the best we have found till now ; as we are finding minimum and books are sorted so reduce end = mid - 1 that means ; if not possible means pages should be increased so update start = mid + 1 ; at - last return minimum no . of pages ; Number of pages in books ; $m = 2 ; No . of students"
Solution in php:

 < ? php function isPossible ( $ arr , $ n , $ m , $ curr_min ) { $ studentsRequired = 1 ; $ curr_sum = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] > $ curr_min ) return false ; if ( $ curr_sum + $ arr [ $ i ] > $ curr_min ) { $ studentsRequired ++ ; $ curr_sum = $ arr [ $ i ] ; if ( $ studentsRequired > $ m ) return false ; } else $ curr_sum += $ arr [ $ i ] ; } return true ; } function findPages ( $ arr , $ n , $ m ) { $ sum = 0 ; if ( $ n < $ m ) return -1 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ sum += $ arr [ $ i ] ; $ start = 0 ; $ end = $ sum ; $ result = PHP_INT_MAX ; while ( $ start <= $ end ) { $ mid = ( int ) ( $ start + $ end ) / 2 ; if ( isPossible ( $ arr , $ n , $ m , $ mid ) ) { $ result = $ mid ; $ end = $ mid - 1 ; } else $ start = $ mid + 1 ; } return $ result ; } $ arr = array ( 12 , 34 , 67 , 90 ) ; $ n = count ( $ arr ) ; echo " Minimum ▁ number ▁ of ▁ pages ▁ = ▁ " , findPages ( $ arr , $ n , $ m ) , "
 " ; ? >


"Almost Prime Numbers | 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"
Solution in php:

 < ? php function countPrimeFactors ( $ n ) { $ count = 0 ; while ( $ n % 2 == 0 ) { $ n = $ n / 2 ; $ count ++ ; } for ( $ i = 3 ; $ i <= sqrt ( $ n ) ; $ i = $ i + 2 ) { while ( $ n % $ i == 0 ) { $ n = $ n / $ i ; $ count ++ ; } } if ( $ n > 2 ) $ count ++ ; return ( $ count ) ; } function printKAlmostPrimes ( $ k , $ n ) { for ( $ i = 1 , $ num = 2 ; $ i <= $ n ; $ num ++ ) { if ( countPrimeFactors ( $ num ) == $ k ) { echo ( $ num ) ; echo ( " ▁ " ) ; $ i ++ ; } } return ; } $ n = 10 ; $ k = 2 ; echo " First ▁ $ n ▁ $ k - almost ▁ prime ▁ numbers :
 " ; printKAlmostPrimes ( $ k , $ n ) ; ? >


"Alternate Fibonacci Numbers | Alternate Fibonacci Series using Dynamic Programming ; 0 th and 1 st number of the series are 0 and 1 ; Driver Code"
Solution in php:


"Alternate Primes till N | Function for checking number is prime or not ; if flag = 0 then number is prime and return 1 otherwise return 0 ; Function for printing alternate prime number ; counter is initialize with 0 ; looping through 2 to n - 1 ; function calling along with if condition ; if counter is multiple of 2 then only print prime number ; Driver code ; Function calling"
Solution in php:

 < ? php function prime ( $ num ) { $ flag = 0 ; for ( $ i = 2 ; $ i <= $ num / 2 ; $ i ++ ) { if ( $ num % $ i == 0 ) { $ flag = 1 ; break ; } } if ( $ flag == 0 ) return 1 ; else return 0 ; } function print_alternate_prime ( $ n ) { $ counter = 0 ; for ( $ num = 2 ; $ num < $ n ; $ num ++ ) { if ( prime ( $ num ) == 1 ) { if ( $ counter % 2 == 0 ) echo $ num . " " ; $ counter += 1 ; } } } $ n = 15 ; echo " Following ▁ are ▁ the ▁ alternate ▁ prime ▁ " . " number ▁ smaller ▁ than ▁ or ▁ equal ▁ to ▁ " . $ n . "
 " ; print_alternate_prime ( $ n ) ; ? >


"Alternate Primes till N | PHP program to print all primes smaller than or equal to n using Sieve of Eratosthenes ; 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 prime numbers ; for next prime to get printed ; Driver Code"
Solution in php:

 < ? php function SieveOfEratosthenes ( $ n ) { $ prime = array ( ) ; for ( $ i = 0 ; $ i <= $ n ; $ i ++ ) $ prime [ $ i ] = true ; for ( $ p = 2 ; $ p * $ p <= $ n ; $ p ++ ) { if ( $ prime [ $ p ] == true ) { for ( $ i = $ p * 2 ; $ i <= $ n ; $ i += $ p ) $ prime [ $ i ] = false ; } } $ flag = true ; for ( $ p = 2 ; $ p <= $ n ; $ p ++ ) { if ( $ prime [ $ p ] ) { if ( $ flag ) { echo $ p . " " ; $ flag = false ; } else { $ flag = true ; } } } } $ n = 15 ; echo " Following ▁ are ▁ the ▁ alternate " . " ▁ prime ▁ numbers ▁ smaller ▁ " . " than ▁ or ▁ equal ▁ to ▁ " . $ n . "
 " ; SieveOfEratosthenes ( $ n ) ; ? >


"Alternate bits of two numbers to create a new number | set even bit of number n ; res for store 101010. . number ; generate number form of 101010. . ... till temp size ; if bit is even then generate number and or with res ; return set even bit number ; set odd bit of number m ; res for store 101010. . number ; generate number form of 101010. . . . till temp size ; if bit is even then generate number and or with res ; return set odd bit number ; set even bit of number n ; set odd bit of number m ; take OR with these number ; Driver code ; n = 1 0 1 0 ^ ^ m = 1 0 1 1 ^ ^ result = 1 0 1 1"
Solution in php:

< ? php function setevenbits ( $ n ) { $ temp = $ n ; $ count = 0 ; $ res = 0 ; for ( $ temp = $ n ; $ temp > 0 ; $ temp >>= 1 ) { if ( $ count % 2 == 1 ) $ res |= ( 1 << $ count ) ; $ count ++ ; } return ( $ n & $ res ) ; } function setoddbits ( $ m ) { $ count = 0 ; $ res = 0 ; for ( $ temp = $ m ; $ temp > 0 ; $ temp >>= 1 ) { if ( $ count % 2 == 0 ) $ res |= ( 1 << $ count ) ; $ count ++ ; } return ( $ m & $ res ) ; } function getAlternateBits ( $ n , $ m ) { $ tempn = setevenbits ( $ n ) ; $ tempm = setoddbits ( $ m ) ; return ( $ tempn $ tempm ) ; } $ n = 10 ; $ m = 11 ; echo getAlternateBits ( $ n , $ m ) ; ? >


"An application on Bertrand 's ballot theorem | PHP implementation of the approach ; Function to calculate factorial of a number mod 1000000007 ; Factorial of i = factorial of ( i - 1 ) * i ; ; Taking mod aint with calculation . ; Function for modular exponentiation ; If p is odd ; If p is even ; Function to return the count of required permutations ; Calculating multiplicative modular inverse for x ! and multiplying with ans ; Calculating multiplicative modular inverse for y ! and multiplying with ans ; Pre - compute factorials"
Solution in php:

< ? php $ mod = 1000000007 ; $ arr = array_fill ( 0 , 10001 , 0 ) ; function cal_factorial ( ) { global $ arr , $ mod ; $ arr [ 0 ] = 1 ; for ( $ i = 1 ; $ i <= 10000 ; $ i ++ ) { $ arr [ $ i ] = ( $ arr [ $ i - 1 ] * $ i ) % $ mod ; } } function mod_exponent ( $ num , $ p ) { global $ mod ; if ( $ p == 0 ) return 1 ; if ( ( $ p & 1 ) ) { return ( ( $ num % $ mod ) * ( mod_exponent ( ( $ num * $ num ) % $ mod , $ p / 2 ) ) % $ mod ) % $ mod ; } else if ( ! ( $ p & 1 ) ) return ( mod_exponent ( ( $ num * $ num ) % $ mod , $ p / 2 ) ) % $ mod ; } function getCount ( $ x , $ y ) { global $ arr , $ mod ; $ ans = $ arr [ $ x + $ y - 1 ] ; $ ans *= mod_exponent ( $ arr [ $ x ] , $ mod - 2 ) ; $ ans %= $ mod ; $ ans *= mod_exponent ( $ arr [ $ y ] , $ mod - 2 ) ; $ ans %= $ mod ; $ ans *= ( $ x - $ y ) ; $ ans %= $ mod ; return $ ans ; } cal_factorial ( ) ; $ x = 3 ; $ y = 1 ; print ( getCount ( $ x , $ y ) ) ; ? >


"An interesting solution to get all prime numbers smaller than n | PHP program to prints prime numbers smaller than n ; Compute factorials and apply Wilson 's  theorem. ; Driver code"
Solution in php:

 < ? php function primesInRange ( $ n ) { $ fact = 1 ; for ( $ k = 2 ; $ k < $ n ; $ k ++ ) { $ fact = $ fact * ( $ k - 1 ) ; if ( ( $ fact + 1 ) % $ k == 0 ) print ( $ k . "
 " ) ; } } $ n = 15 ; primesInRange ( $ n ) ; ? >


"Analysis of Algorithms | Set 2 ( Worst , Average and Best Cases ) | Linearly search x in arr [ ] . If x is present then return the index , otherwise return - 1 ; Driver Code"
Solution in php:

< ? php function search ( $ arr , $ n , $ x ) { for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] == $ x ) return $ i ; } return -1 ; } $ arr = array ( 1 , 10 , 30 , 15 ) ; $ x = 30 ; $ n = sizeof ( $ arr ) ; echo $ x . " ▁ is ▁ present ▁ at ▁ index ▁ " . search ( $ arr , $ n , $ x ) ;


"Angle between two Planes in 3D | Function to find Angle ; Driver Code"
Solution in php:


"Area of Circumcircle of a Right Angled Triangle | PHP program to find the area of Cicumscribed circle of right angled triangle ; Function to find area of circumscribed circle ; Driver code"
Solution in php:

< ? php $ PI = 3.14159265 ; function area_circumscribed ( $ c ) { global $ PI ; return ( $ c * $ c * ( $ PI / 4 ) ) ; } $ c = 8 ; echo ( area_circumscribed ( $ c ) ) ; ? >


"Area of Incircle of a Right Angled Triangle | PHP program to find the area of inscribed circle of right angled triangle ; Function to find area of inscribed circle ; Driver code"
Solution in php:


"Area of Largest rectangle that can be inscribed in an Ellipse | Function to find the area of the rectangle ; a and b cannot be negative ; area of the rectangle ; Driver code"
Solution in php:

< ? php function rectanglearea ( $ a , $ b ) { if ( $ a < 0 or $ b < 0 ) return -1 ; return 2 * $ a * $ b ; } $ a = 10 ; $ b = 8 ; echo rectanglearea ( $ a , $ b ) ; ? >


"Area of Reuleaux Triangle | Function to find the Area of the Reuleaux triangle ; Side cannot be negative ; Area of the Reuleaux triangle ; Driver code"
Solution in php:

< ? php function ReuleauxArea ( $ a ) { if ( $ a < 0 ) return -1 ; $ A = 0.70477 * pow ( $ a , 2 ) ; return $ A ; } $ a = 6 ; echo ReuleauxArea ( $ a ) ;


"Area of a largest square fit in a right angle triangle | Function to find the area of the biggest square ; the height or base or hypotenuse cannot be negative ; side of the square ; squaring to get the area ; Driver code"
Solution in php:

< ? php function squareArea ( $ l , $ b , $ h ) { if ( $ l < 0 $ b < 0 $ h < 0 ) return -1 ; $ a = ( $ l * $ b ) / ( $ l + $ b ) ; return $ a * $ a ; } $ l = 5 ; $ b = 12 ; $ h = 13 ; echo round ( squareArea ( $ l , $ b , $ h ) , 4 ) ; ? >


"Area of a leaf inside a square | PHP program to find the area of leaf inside a square ; Function to find area of leaf ; Driver code"
Solution in php:

< ? php $ PI = 3.14159265 ; function area_leaf ( $ a ) { global $ PI ; return ( $ a * $ a * ( $ PI / 2 - 1 ) ) ; } $ a = 7 ; echo ( area_leaf ( $ a ) ) ; ? >


"Area of a polygon with given n ordered vertices | ( X [ i ] , Y [ i ] ) are coordinates of i 'th point. ; Initialize area ; Calculate value of shoelace formula ; j is previous vertex to i ; Return absolute value ; Driver Code"
Solution in php:


"Area of a square from diagonal length | Returns area of square from given diagonal ; Driver Code"
Solution in php:

< ? php function findArea ( $ d ) { return ( $ d * $ d ) / 2 ; } $ d = 10 ; echo ( findArea ( $ d ) ) ; ? >


"Area of a triangle inscribed in a rectangle which is inscribed in an ellipse | Function to find the area of the triangle ; length of a and b cannot be negative ; area of the triangle ; Driver code"
Solution in php:

< ? php function area ( $ a , $ b ) { if ( $ a < 0 $ b < 0 ) return -1 ; $ A = $ a * $ b ; return $ A ; } $ a = 5 ; $ b = 2 ; echo area ( $ a , $ b ) ; ? >


"Area of circle inscribed within rhombus | Function to find the area of the inscribed circle ; the diagonals cannot be negative ; area of the circle ; Driver code"
Solution in php:


"Area of circle which is inscribed in equilateral triangle | Function return the area of circle inscribed in equilateral triangle ; Driver code"
Solution in php:

< ? php function circle_inscribed ( $ a ) { return 3.14 * ( $ a * $ a ) / 12 ; } $ a = 4 ; echo circle_inscribed ( $ a ) ;


"Area of decagon inscribed within the circle | Function to find the area of the decagon ; radius cannot be negative ; area of the decagon ; Driver code"
Solution in php:


"Area of hexagon with given diagonal length | Function to calculate area ; Formula to find area ; Driver Code"
Solution in php:

< ? php function hexagonArea ( $ d ) { return ( 3 * sqrt ( 3 ) * pow ( $ d , 2 ) ) / 8 ; } $ d = 10 ; echo " Area ▁ of ▁ hexagon : ▁ " , hexagonArea ( $ d ) ; ? >


"Area of largest triangle that can be inscribed within a rectangle | Function to find the area of the triangle ; a and b cannot be negative ; area of the triangle ; Driver code"
Solution in php:

< ? php function trianglearea ( $ l , $ b ) { if ( $ l < 0 or $ b < 0 ) return -1 ; $ area = ( $ l * $ b ) / 2 ; return $ area ; } $ l = 5 ; $ b = 4 ; echo trianglearea ( $ l , $ b ) ; ? >


"Area of plot remaining at the end | Function to return the area of the remaining plot ; Continue while plot has positive area and there are persons left ; If length > breadth then subtract breadth from length ; Else subtract length from breadth ; Driver code"
Solution in php:

< ? php function remainingArea ( $ N , $ M , $ K ) { while ( $ K -- && $ N && $ M ) { if ( $ N > $ M ) $ N = $ N - $ M ; else $ M = $ M - $ N ; } if ( $ N > 0 && $ M > 0 ) return $ N * $ M ; else return 0 ; } $ N = 5 ; $ M = 3 ; $ K = 2 ; echo remainingArea ( $ N , $ M , $ K ) ; ? >


"Area of square Circumscribed by Circle | Function to find area of square ; Radius of a circle ; Call Function to find an area of square"
Solution in php:

< ? php function find_Area ( $ r ) { return ( 2 * $ r * $ r ) ; } $ r = 3 ; echo ( " Area ▁ of ▁ square ▁ = ▁ " ) ; echo ( find_Area ( $ r ) ) ; ? >


"Area of the Largest Triangle inscribed in a Hexagon | Function to find the area of the triangle ; side cannot be negative ; area of the triangle ; Driver code"
Solution in php:

< ? php function trianglearea ( $ a ) { if ( $ a < 0 ) return -1 ; $ area = ( 3 * sqrt ( 3 ) * pow ( $ a , 2 ) ) / 4 ; return $ area ; } $ a = 6 ; echo trianglearea ( $ a ) ; ? >


"Area of the Largest square that can be inscribed in an ellipse | Function to find the area of the square ; a and b cannot be negative ; area of the square ; Driver code"
Solution in php:

< ? php function squarearea ( $ a , $ b ) { if ( $ a < 0 or $ b < 0 ) return -1 ; $ area = 4 * ( ( ( pow ( $ a , 2 ) + pow ( $ b , 2 ) ) / ( pow ( $ a , 2 ) * pow ( $ b , 2 ) ) ) ) ; return $ area ; } $ a = 4 ; $ b = 2 ; print ( squarearea ( $ a , $ b ) ) ; ? >


"Area of the biggest ellipse inscribed within a rectangle | Function to find the area of the ellipse ; The sides cannot be negative ; Area of the ellipse ; Driver code"
Solution in php:


"Area of the circumcircle of any triangles with sides given | Function to find the area of the circumcircle ; the sides cannot be negative ; semi - perimeter of the circle ; area of triangle ; area of the circle ; Get the sides of the triangle ; Find and print the area of the circumcircle"
Solution in php:


"Arithmetic Mean | Prints N arithmetic means between A and B . ; calculate common difference ( d ) ; for finding N the arithmetic mean between A and B ; Driver Code"
Solution in php:


"Arithmetic Number | Sieve Of Eratosthenes ; 1 is not a prime number ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Storing primes in an array ; Update value in primesquare [ p * p ] , if p is prime . ; Function to count divisors ; If number is 1 , then it will have only 1 as a factor . So , total factors will be 1. ; for storing primes upto n ; Calling SieveOfEratosthenes to store prime factors of n and to store square of prime factors of n ; ans will contain total number of distinct divisors ; Loop for counting factors of n ; a [ i ] is not less than cube root n ; Calculating power of a [ i ] in n . cnt is power of prime a [ i ] in n . ; if a [ i ] is a factor of n ; incrementing power ; Calculating number of divisors . If n = a ^ p * b ^ q then total divisors of n are ( p + 1 ) * ( q + 1 ) ; First case ; Second case ; Third casse ; return $ans ; Total divisors ; Returns sum of all factors of n . ; Traversing through all prime factors . ; This condition is to handle the case when n is a prime number greater than 2. ; Check if number is Arithmetic Number or not . ; Driver code"
Solution in php:

< ? php function SieveOfEratosthenes ( $ n , & $ prime , & $ primesquare , & $ a ) { for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) $ prime [ $ i ] = true ; for ( $ i = 0 ; $ i <= ( $ n * $ n + 1 ) ; $ i ++ ) $ primesquare [ $ i ] = false ; $ prime [ 1 ] = false ; for ( $ p = 2 ; $ p * $ p <= $ n ; $ p ++ ) { if ( $ prime [ $ p ] == true ) { for ( $ i = $ p * 2 ; $ i <= $ n ; $ i += $ p ) $ prime [ $ i ] = false ; } } $ j = 0 ; for ( $ p = 2 ; $ p <= $ n ; $ p ++ ) { if ( $ prime [ $ p ] ) { $ a [ $ j ] = $ p ; $ primesquare [ $ p * $ p ] = true ; $ j ++ ; } } } function countDivisors ( $ n ) { if ( $ n == 1 ) return 1 ; $ prime = array_fill ( 0 , ( $ n + 1 ) , false ) ; $ primesquare = array_fill ( 0 , ( $ n * $ n + 1 ) , false ) ; $ a = array_fill ( 0 , $ n , 0 ) ; SieveOfEratosthenes ( $ n , $ prime , $ primesquare , $ a ) ; $ ans = 1 ; for ( $ i = 0 ; ; $ i ++ ) { if ( $ a [ $ i ] * $ a [ $ i ] * $ a [ $ i ] > $ n ) break ; $ cnt = 1 ; while ( $ n % $ a [ $ i ] == 0 ) { $ n = ( int ) ( $ n / $ a [ $ i ] ) ; $ cnt = $ cnt + 1 ; } $ ans = $ ans * $ cnt ; } if ( $ prime [ $ n ] ) $ ans = $ ans * 2 ; else if ( $ primesquare [ $ n ] ) $ ans = $ ans * 3 ; else if ( $ n != 1 ) $ ans = $ ans * 4 ; } function sumofFactors ( $ n ) { $ res = 1 ; for ( $ i = 2 ; $ i <= sqrt ( $ n ) ; $ i ++ ) { $ count = 0 ; $ curr_sum = 1 ; $ curr_term = 1 ; while ( $ n % $ i == 0 ) { $ count ++ ; $ n = ( int ) ( $ n / $ i ) ; $ curr_term *= $ i ; $ curr_sum += $ curr_term ; } $ res *= $ curr_sum ; } if ( $ n >= 2 ) $ res *= ( 1 + $ n ) ; return $ res ; } function checkArithmetic ( $ n ) { $ count = countDivisors ( $ n ) ; $ sum = sumofFactors ( $ n ) ; return ( $ sum % $ count == 0 ) ; } $ n = 6 ; echo ( checkArithmetic ( $ n ) ) ? " Yes " : " No " ; ? >


"Arithmetic Progression | Returns true if a permutation of arr [ 0. . n - 1 ] can form arithmetic progression ; Sort array ; After sorting , difference between consecutive elements must be same . ; Driver Code"
Solution in php:

< ? php function checkIsAP ( $ arr , $ n ) { if ( $ n == 1 ) return true ; sort ( $ arr ) ; $ d = $ arr [ 1 ] - $ arr [ 0 ] ; for ( $ i = 2 ; $ i < $ n ; $ i ++ ) if ( $ arr [ $ i ] - $ arr [ $ i - 1 ] != $ d ) return false ; return true ; } $ arr = array ( 20 , 15 , 5 , 0 , 10 ) ; $ n = count ( $ arr ) ; if ( checkIsAP ( $ arr , $ n ) ) echo " Yes " ; else echo " No " ; ? >


"Armstrong Numbers between two integers | Prints Armstrong Numbers in given range ; number of digits calculation ; compute sum of nth power of its digits ; checks if number i is equal to the sum of nth power of its digits ; Driver code"
Solution in php:


"Arrangement of the characters of a word such that all vowels are at odd places | Function to return the factorial of a number ; calculating nPr ; Function to find the number of $ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions ; Get total even positions ; Get total odd positions ; Store $frequency of each character of the string ; Count total number of vowels ; Count total number of consonants ; Calculate the total number of ways ; Driver code"
Solution in php:

< ? php function fact ( $ n ) { $ f = 1 ; for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) { $ f = $ f * $ i ; } return $ f ; } function npr ( $ n , $ r ) { return fact ( $ n ) / fact ( $ n - $ r ) ; } function countPermutations ( $ str ) { $ even = floor ( strlen ( $ str ) / 2 ) ; $ odd = strlen ( $ str ) - $ even ; $ ways = 0 ; $ freq = array_fill ( 0 , 26 , 0 ) ; for ( $ i = 0 ; $ i < strlen ( $ str ) ; $ i ++ ) { ++ $ freq [ ord ( $ str [ $ i ] ) - ord ( ' a ' ) ] ; } $ nvowels = $ freq [ 0 ] + $ freq [ 4 ] + $ freq [ 8 ] + $ freq [ 14 ] + $ freq [ 20 ] ; $ nconsonants = strlen ( $ str ) - $ nvowels ; $ ways = npr ( $ odd , $ nvowels ) * npr ( $ nconsonants , $ nconsonants ) ; return $ ways ; } $ str = " geeks " ; echo countPermutations ( $ str ) ; ? >


"Arrangement of words without changing the relative position of vowel and consonants | this function return n ! ; this will return total number of ways ; freq maintains frequency of each character in word ; check character is vowel or not ; the characters that are not vowel must be consonant ; number of ways to arrange vowel ; multiply both as these are independent ; string contains only capital letters ; this will contain ans"
Solution in php:

< ? php function factorial ( $ n ) { $ res = 1 ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) $ res = $ res * $ i ; return $ res ; } function count1 ( $ word ) { $ freq = array_fill ( 0 , 27 , 0 ) ; for ( $ i = 0 ; $ i < 27 ; $ i ++ ) $ freq [ $ i ] = 0 ; $ vowel = 0 ; $ consonant = 0 ; for ( $ i = 0 ; $ i < strlen ( $ word ) ; $ i ++ ) { $ freq [ ord ( $ word [ $ i ] ) - 65 ] ++ ; if ( $ word [ $ i ] == ' A ' $ word [ $ i ] == ' E ' $ word [ $ i ] == ' I ' $ word [ $ i ] == ' O ' $ word [ $ i ] == ' U ' ) { $ vowel ++ ; } else $ consonant ++ ; } $ vowelArrange = factorial ( $ vowel ) ; $ vowelArrange /= factorial ( $ freq [ 0 ] ) ; $ vowelArrange /= factorial ( $ freq [ 4 ] ) ; $ vowelArrange /= factorial ( $ freq [ 8 ] ) ; $ vowelArrange /= factorial ( $ freq [ 14 ] ) ; $ vowelArrange /= factorial ( $ freq [ 20 ] ) ; $ consonantArrange = factorial ( $ consonant ) ; for ( $ i = 0 ; $ i < 26 ; $ i ++ ) { if ( $ i != 0 && $ i != 4 && $ i != 8 && $ i != 14 && $ i != 20 ) $ consonantArrange /= factorial ( $ freq [ $ i ] ) ; } $ total = $ vowelArrange * $ consonantArrange ; return $ total ; } $ word = " COMPUTER " ; $ ans = count1 ( $ word ) ; echo ( $ ans ) ; ? >


"Array element moved by k using single moves | PHP program to find winner of game ; if the number of steps is more then n - 1 , ; initially the best is 0 and no . of wins is 0. ; traverse through all the numbers ; if the value of array is more then that of previous best ; best is replaced by a [ i ] ; if not the first index ; no of wins is 1 now ; if it wins ; if any position has more then k wins then return ; Maximum element will be winner because we move smaller element at end and repeat the process . ; Driver Code"
Solution in php:

< ? php function winner ( $ a , $ n , $ k ) { if ( $ k >= $ n - 1 ) return $ n ; $ best = 0 ; $ times = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ a [ $ i ] > $ best ) { $ best = $ a [ $ i ] ; if ( $ i ) $ times = 1 ; } else $ times += 1 ; if ( $ times >= $ k ) return $ best ; } return $ best ; } $ a = array ( 2 , 1 , 3 , 4 , 5 ) ; $ n = sizeof ( $ a ) ; $ k = 2 ; echo ( winner ( $ a , $ n , $ k ) ) ; ? >


"Assembly Line Scheduling | DP | A PHP program to find minimum possible time by the car chassis to complete ; Utility function to find minimum of two numbers ; time taken to leave first station in line 1 ; time taken to leave first station in line 2 ; Fill tables T1 [ ] and T2 [ ] using the above given recursive relations ; Consider exit times and return minimum ; Driver Code"
Solution in php:


"Assign other value to a variable from two possible values | Function to alternate the values ; Driver Code"
Solution in php:

< ? php function alternate ( & $ a , & $ b , & $ x ) { $ x = $ a ^ $ b ^ $ x ; } $ a = -10 ; $ b = 15 ; $ x = $ a ; echo " x ▁ is ▁ : ▁ " , $ x ; alternate ( $ a , $ b , $ x ) ; echo " After exchange " ; echo " x is : " ? >


< ? php function alternate ( & $ a , & $ b , & $ x ) { $ x = $ a + $ b - $ x ; } $ a = -10 ; $ b = 15 ; $ x = $ a ; echo " x ▁ is ▁ : ▁ " , $ x ; alternate ( $ a , $ b , $ x ) ; echo " After change " ; echo " x is : " ? >


"Average of ASCII values of characters of a given string | Function to find average of ASCII value of chars ; loop to sum the ascii value of chars ; Returning average of chars ; Driver code"
Solution in php:

< ? php function averageValue ( $ s ) { $ sum_char = 0 ; for ( $ i = 0 ; $ i < strlen ( $ s ) ; $ i ++ ) { $ sum_char += ord ( $ s [ $ i ] ) ; } return ( int ) ( $ sum_char / strlen ( $ s ) ) ; } $ s = " GeeksforGeeks " ; echo averageValue ( $ s ) ; ? >


"Average of Squares of Natural Numbers | Function to calculate average of square number ; Driver code"
Solution in php:

< ? php function AvgofSquareN ( $ n ) { $ sum = 0 ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) $ sum += ( $ i * $ i ) ; return $ sum / $ n ; } $ n = 2 ; echo ( AvgofSquareN ( $ n ) ) ; ? >


"Average of Squares of Natural Numbers | Function to get the average ; Driver Code"
Solution in php:

< ? php function AvgofSquareN ( $ n ) { return ( ( $ n + 1 ) * ( 2 * $ n + 1 ) ) / 6 ; } $ n = 2 ; echo ( AvgofSquareN ( $ n ) ) ; ? >


"Average of first n even natural numbers | Return the average of sum of first n even numbers ; Driver Code"
Solution in php:

< ? php function avg_of_even_num ( $ n ) { return $ n + 1 ; } $ n = 8 ; echo ( avg_of_even_num ( $ n ) ) ; ? >


"Average of first n even natural numbers | function to find average of sum of first n even numbers ; sum of first n even numbers ; calculating Average ; Driver Code"
Solution in php:

< ? php function avg_of_even_num ( $ n ) { $ sum = 0 ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) $ sum += 2 * $ i ; return $ sum / $ n ; } $ n = 9 ; echo ( avg_of_even_num ( $ n ) ) ; ? >


"Average of remaining elements after removing K largest and K smallest elements from array | Function to find average ; base case if 2 * k >= n means all element get removed ; first sort all elements ; sum of req number ; find average ; Driver code"
Solution in php:

< ? php function average ( $ arr , $ n , $ k ) { $ total = 0 ; if ( 2 * $ k >= $ n ) return 0 ; sort ( $ arr ) ; $ start = $ k ; $ end = $ n - $ k - 1 ; for ( $ i = $ start ; $ i <= $ end ; $ i ++ ) $ total += $ arr [ $ i ] ; return ( $ total / ( $ n - 2 * $ k ) ) ; } $ arr = array ( 1 , 2 , 4 , 4 , 5 , 6 ) ; $ n = sizeof ( $ arr ) ; $ k = 2 ; echo average ( $ arr , $ n , $ k ) ; ? >


"Bakhshali Approximation for computing square roots | This PHP 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"
Solution in php:


"Balance a string after removing extra brackets | Print balanced and remove extra brackets from string ; Maintain a count for opening brackets Traversing string ; check if opening bracket ; print str [ i ] and increment count by 1 ; check if closing bracket and count != 0 ; decrement count by 1 ; if str [ i ] not a closing brackets print it ; balanced brackets if opening brackets are more then closing brackets ; print remaining closing brackets ; Driver code"
Solution in php:

< ? php function balancedString ( $ str ) { $ count = 0 ; $ n = strlen ( $ str ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ str [ $ i ] == ' ( ' ) { echo $ str [ $ i ] ; $ count ++ ; } else if ( $ str [ $ i ] == ' ) ' && $ count != 0 ) { echo $ str [ $ i ] ; $ count -- ; } else if ( $ str [ $ i ] != ' ) ' ) echo $ str [ $ i ] ; } if ( $ count != 0 ) for ( $ i = 0 ; $ i < $ count ; $ i ++ ) echo " ) " ; } $ str = " gau ) ra ) v ( ku ( mar ( rajput ) ) " ; balancedString ( $ str ) ; ? >


"Balance pans using given weights that are powers of a number | method returns true if balancing of scale is possible ; baseForm vector will store T 's  representation on base a in reverse order ; convert T to representation on base a ; make first digit of representation as 0 ; loop over base representation of T ; if any digit is not 0 , 1 , ( a - 1 ) or a then balancing is not possible ; if digit is a or ( a - 1 ) then increase left index ' s ▁ count / ▁ ( case , ▁ when ▁ this ▁ weight ▁ is ▁ transferred ▁ to ▁ T ' s side ) ; if representation is processed then balancing is possible ; Driver Code"
Solution in php:

 < ? php function isBalancePossible ( $ T , $ a ) { $ baseForm = array ( ) ; while ( $ T ) { array_push ( $ baseForm , $ T % $ a ) ; $ T = ( int ) ( $ T / $ a ) ; } array_push ( $ baseForm , 0 ) ; for ( $ i = 0 ; $ i < count ( $ baseForm ) ; $ i ++ ) { if ( $ baseForm [ $ i ] != 0 && $ baseForm [ $ i ] != 1 && $ baseForm [ $ i ] != ( $ a - 1 ) && $ baseForm [ $ i ] != $ a ) return false ; if ( $ baseForm [ $ i ] == $ a || $ baseForm [ $ i ] == ( $ a - 1 ) ) $ baseForm [ $ i + 1 ] += 1 ; } return true ; } $ T = 11 ; $ a = 4 ; $ balancePossible = isBalancePossible ( $ T , $ a ) ; if ( $ balancePossible ) echo " Balance ▁ is ▁ possible
 " ; else echo " Balance ▁ is ▁ not ▁ possible
 " ; ? >


"Balanced Prime | PHP Program to find Nth Balanced Prime ; Return the Nth balanced prime . ; Sieve of Eratosthenes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; storing all primes ; Finding the Nth balanced Prime ; Driven Program"
Solution in php:

< ? php $ MAX = 501 ; function balancedprime ( $ n ) { global $ MAX ; $ prime = array_fill ( 0 , $ MAX + 1 , true ) ; for ( $ p = 2 ; $ p * $ p <= $ MAX ; $ p ++ ) { if ( $ prime [ $ p ] == true ) { for ( $ i = $ p * 2 ; $ i <= $ MAX ; $ i += $ p ) $ prime [ $ i ] = false ; } } $ v = array ( ) ; for ( $ p = 3 ; $ p <= $ MAX ; $ p += 2 ) if ( $ prime [ $ p ] ) array_push ( $ v , $ p ) ; $ count = 0 ; for ( $ i = 1 ; $ i < count ( $ v ) ; $ i ++ ) { if ( $ v [ $ i ] == ( $ v [ $ i + 1 ] + $ v [ $ i - 1 ] ) / 2 ) $ count ++ ; if ( $ count == $ n ) return $ v [ $ i ] ; } } $ n = 4 ; echo balancedprime ( $ n ) ; ? >


"Balanced expressions such that given positions have opening brackets | Set 2 | Function to find Number of proper bracket expressions ; If open - closed brackets < 0 ; If index reaches the end of expression ; If brackets are balanced ; If already stored in dp ; If the current index has assigned open bracket ; Move forward increasing the length of open brackets ; Move forward by inserting open as well as closed brackets on that index ; return the answer ; DP array to precompute the answer ; Open brackets at position 1 ; Calling the find function to calculate the answer"
Solution in php:

 < ? php function find ( $ index , $ openbrk , $ n , & $ dp , & $ adj ) { if ( $ openbrk < 0 ) return 0 ; if ( $ index == $ n ) { if ( $ openbrk == 0 ) return 1 ; else return 0 ; } if ( $ dp [ $ index ] [ $ openbrk ] != -1 ) return $ dp [ $ index ] [ $ openbrk ] ; if ( $ adj [ $ index ] == 1 ) { $ dp [ $ index ] [ $ openbrk ] = find ( $ index + 1 , $ openbrk + 1 , $ n , $ dp , $ adj ) ; } else { $ dp [ $ index ] [ $ openbrk ] = find ( $ index + 1 , $ openbrk + 1 , $ n , $ dp , $ adj ) + find ( $ index + 1 , $ openbrk - 1 , $ n , $ dp , $ adj ) ; } return $ dp [ $ index ] [ $ openbrk ] ; } $ N = 1000 ; $ dp = array ( array ( ) ) ; $ n = 2 ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) { for ( $ j = 0 ; $ j < $ N ; $ j ++ ) { $ dp [ $ i ] [ $ j ] = -1 ; } } $ adj = array ( 1 , 0 , 0 , 0 ) ; echo find ( 0 , 0 , 2 * $ n , $ dp , $ adj ) . "
 " ; ? >


"Bell Numbers ( Number of ways to Partition a Set ) | function that returns n 'th bell number ; Explicitly fill for j = 0 ; Fill for remaining values of j ; Driver Code"
Solution in php:


"Bellman Ford Algorithm ( Simple Implementation ) | The main function that finds shortest distances from src to all other vertices using Bellman - Ford algorithm . The function also detects negative weight cycle The row graph [ i ] represents i - th edge with three values u , v and w . ; Initialize distance of all vertices as infinite . ; initialize distance of source as 0 ; Relax all edges | V | - 1 times . A simple shortest path from src to any other vertex can have at - most | V | - 1 edges ; check for negative - weight cycles . The above step guarantees shortest distances if graph doesn 't contain  negative weight cycle. If we get a  shorter path, then there is a cycle. ; Every edge has three values ( u , v , w ) where the edge is from vertex u to v . And weight of the edge is w ."
Solution in php:

 < ? php function BellmanFord ( $ graph , $ V , $ E , $ src ) { $ dis = array ( ) ; for ( $ i = 0 ; $ i < $ V ; $ i ++ ) $ dis [ $ i ] = PHP_INT_MAX ; $ dis [ $ src ] = 0 ; for ( $ i = 0 ; $ i < $ V - 1 ; $ i ++ ) { for ( $ j = 0 ; $ j < $ E ; $ j ++ ) { if ( $ dis [ $ graph [ $ j ] [ 0 ] ] != PHP_INT_MAX && $ dis [ $ graph [ $ j ] [ 0 ] ] + $ graph [ $ j ] [ 2 ] < $ dis [ $ graph [ $ j ] [ 1 ] ] ) $ dis [ $ graph [ $ j ] [ 1 ] ] = $ dis [ $ graph [ $ j ] [ 0 ] ] + $ graph [ $ j ] [ 2 ] ; } } for ( $ i = 0 ; $ i < $ E ; $ i ++ ) { $ x = $ graph [ $ i ] [ 0 ] ; $ y = $ graph [ $ i ] [ 1 ] ; $ weight = $ graph [ $ i ] [ 2 ] ; if ( $ dis [ $ x ] != PHP_INT_MAX && $ dis [ $ x ] + $ weight < $ dis [ $ y ] ) echo " Graph ▁ contains ▁ negative ▁ weight ▁ cycle ▁
 " ; } echo " Vertex ▁ Distance ▁ from ▁ Source ▁
 " ; for ( $ i = 0 ; $ i < $ V ; $ i ++ ) echo $ i , " 	 	 " , $ dis [ $ i ] , "
 " ; } $ graph = array ( array ( 0 , 1 , -1 ) , array ( 0 , 2 , 4 ) , array ( 1 , 2 , 3 ) , array ( 1 , 3 , 2 ) , array ( 1 , 4 , 2 ) , array ( 3 , 2 , 5 ) , array ( 3 , 1 , 1 ) , array ( 4 , 3 , -3 ) ) ; BellmanFord ( $ graph , $ V , $ E , 0 ) ; ? >


"Biggest Reuleaux Triangle inscirbed within a square inscribed in a semicircle | Function to find the biggest reuleaux triangle ; radius cannot be negative ; height of the reuleaux triangle ; area of the reuleaux triangle ; Driver code"
Solution in php:


"Biggest Reuleaux Triangle inscribed within a Square inscribed in an equilateral triangle | Function to find the biggest reuleaux triangle ; side cannot be negative ; height of the reuleaux triangle ; area of the reuleaux triangle ; Driver code"
Solution in php:


"Biggest Reuleaux Triangle inscribed within a square which is inscribed within a hexagon | Function to find the biggest reuleaux triangle ; side cannot be negative ; height of the reuleaux triangle ; area of the reuleaux triangle ; Driver code"
Solution in php:


"Biggest Reuleaux Triangle inscribed within a square which is inscribed within an ellipse | Function to find the biggest reuleaux triangle ; length of the axes cannot be negative ; height of the reuleaux triangle ; area of the reuleaux triangle ; Driver code"
Solution in php:


"Biggest Reuleaux Triangle within A Square | Function to find the Area of the Reuleaux triangle ; Side cannot be negative ; Area of the Reuleaux triangle ; Driver code"
Solution in php:

 < ? php function ReuleauxArea ( $ a ) { if ( $ a < 0 ) return -1 ; $ A = 0.70477 * pow ( $ a , 2 ) ; return $ A ; } $ a = 6 ; echo ReuleauxArea ( $ a ) . "
 " ; ? >


"Biggest Reuleaux Triangle within a Square which is inscribed within a Circle | Function to find the Area of the Reuleaux triangle ; radius cannot be negative ; Area of the Reuleaux triangle ; Driver code"
Solution in php:

 < ? php function ReuleauxArea ( $ r ) { if ( $ r < 0 ) return -1 ; $ A = 0.70477 * 2 * pow ( $ r , 2 ) ; return $ A ; } $ r = 6 ; echo ReuleauxArea ( $ r ) . "
 " ; ? >


"Biggest Reuleaux Triangle within a Square which is inscribed within a Right angle Triangle | Function to find the biggest reuleaux triangle ; the height or base or hypotenuse cannot be negative ; height of the reuleaux triangle ; area of the reuleaux triangle ; Driver code"
Solution in php:


"Binary Indexed Tree : Range Updates and Point Queries | Updates such that getElement ( ) gets an increased value when queried from l to r . ; Get the element indexed at i ; To get ith element sum of all the elements from 0 to i need to be computed ; Driver Code ; Find the element at Index 4 ; Find the element at Index 3"
Solution in php:

 < ? php function update ( & $ arr , $ l , $ r , $ val ) { $ arr [ $ l ] += $ val ; if ( $ r + 1 < sizeof ( $ arr ) ) $ arr [ $ r + 1 ] -= $ val ; } function getElement ( & $ arr , $ i ) { $ res = 0 ; for ( $ j = 0 ; $ j <= $ i ; $ j ++ ) $ res += $ arr [ $ j ] ; return $ res ; } $ arr = array ( 0 , 0 , 0 , 0 , 0 ) ; $ n = sizeof ( $ arr ) ; $ l = 2 ; $ r = 4 ; $ val = 2 ; update ( $ arr , $ l , $ r , $ val ) ; $ index = 4 ; echo ( " Element ▁ at ▁ index ▁ " . $ index . " ▁ is ▁ " . getElement ( $ arr , $ index ) . "
 " ) ; $ l = 0 ; $ r = 3 ; $ val = 4 ; update ( $ arr , $ l , $ r , $ val ) ; $ index = 3 ; echo ( " Element ▁ at ▁ index ▁ " . $ index . " ▁ is ▁ " . getElement ( $ arr , $ index ) ) ; ? >


"Binary Search a String | Returns index of x if it is present in arr [ ] , else return - 1 ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; Driver Code"
Solution in php:

< ? php function binarySearch ( $ arr , $ x ) { $ l = 0 ; $ r = count ( $ arr ) ; while ( $ l <= $ r ) { $ m = $ l + ( int ) ( ( $ r - $ l ) / 2 ) ; $ res = strcmp ( $ x , $ arr [ $ m ] ) ; if ( $ res == 0 ) return $ m - 1 ; if ( $ res > 0 ) $ l = $ m + 1 ; else $ r = $ m - 1 ; } return -1 ; } $ arr = array ( " contribute " , " geeks " , " ide " , " practice " ) ; $ x = " ide " ; $ result = binarySearch ( $ arr , $ x ) ; if ( $ result == -1 ) print ( " Element ▁ not ▁ present " ) ; else print ( " Element ▁ found ▁ at ▁ index ▁ " . $ result ) ; ? >


"Binary Search | A iterative binary search function . It returns location of x in given array arr [ l . . r ] if present , otherwise - 1 ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; if we reach here , then element was not present ; Driver Code"
Solution in php:

< ? php function binarySearch ( $ arr , $ l , $ r , $ x ) { while ( $ l <= $ r ) { $ m = $ l + ( $ r - $ l ) / 2 ; if ( $ arr [ $ m ] == $ x ) return floor ( $ m ) ; if ( $ arr [ $ m ] < $ x ) $ l = $ m + 1 ; else $ r = $ m - 1 ; } return -1 ; } $ arr = array ( 2 , 3 , 4 , 10 , 40 ) ; $ n = count ( $ arr ) ; $ x = 10 ; $ result = binarySearch ( $ arr , 0 , $ n - 1 , $ x ) ; if ( ( $ result == -1 ) ) echo " Element ▁ is ▁ not ▁ present ▁ in ▁ array " ; else echo " Element ▁ is ▁ present ▁ at ▁ index ▁ " , $ result ; ? >


"Binary Search | A recursive binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver Code"
Solution in php:

< ? php function binarySearch ( $ arr , $ l , $ r , $ x ) { if ( $ r >= $ l ) { $ mid = ceil ( $ l + ( $ r - $ l ) / 2 ) ; if ( $ arr [ $ mid ] == $ x ) return floor ( $ mid ) ; if ( $ arr [ $ mid ] > $ x ) return binarySearch ( $ arr , $ l , $ mid - 1 , $ x ) ; return binarySearch ( $ arr , $ mid + 1 , $ r , $ x ) ; } return -1 ; } $ arr = array ( 2 , 3 , 4 , 10 , 40 ) ; $ n = count ( $ arr ) ; $ x = 10 ; $ result = binarySearch ( $ arr , 0 , $ n - 1 , $ x ) ; if ( ( $ result == -1 ) ) echo " Element ▁ is ▁ not ▁ present ▁ in ▁ array " ; else echo " Element ▁ is ▁ present ▁ at ▁ index ▁ " , $ result ; ? >


"Binary array after M range toggle operations | function for toggle ; function for final processing of array ; function for printing result ; Driver Code ; function call for toggle ; process array ; print result"
Solution in php:

< ? php function command ( $ arr , $ a , $ b ) { $ arr [ $ a ] = $ arr [ $ a ] ^ 1 ; $ arr [ $ b + 1 ] ^= 1 ; } function process ( $ arr , $ n ) { for ( $ k = 1 ; $ k <= $ n ; $ k ++ ) { $ arr [ $ k ] = $ arr [ $ k ] ^ $ arr [ $ k - 1 ] ; } } function result ( $ arr , $ n ) { for ( $ k = 1 ; $ k <= $ n ; $ k ++ ) echo $ arr [ $ k ] . " ▁ " ; } $ n = 5 ; $ m = 3 ; $ arr = new SplFixedArray ( 7 ) ; $ arr [ 6 ] = array ( 0 ) ; command ( $ arr , 1 , 5 ) ; command ( $ arr , 2 , 5 ) ; command ( $ arr , 3 , 5 ) ; process ( $ arr , $ n ) ; result ( $ arr , $ n ) ; ? >


"Binary representation of a given number | Function to convert decimal to binary number ; Driver code"
Solution in php:


"Binomial Random Variables | function to calculate nCr i . e . , number of ways to choose r out of n objects ; Since nCr is same as nC ( n - r ) To decrease number of iterations ; function to calculate binomial r . v . probability ; Driver code"
Solution in php:

< ? php function nCr ( $ n , $ r ) { if ( $ r > $ n / 2 ) $ r = $ n - $ r ; $ answer = 1 ; for ( $ i = 1 ; $ i <= $ r ; $ i ++ ) { $ answer *= ( $ n - $ r + $ i ) ; $ answer /= $ i ; } return $ answer ; } function binomialProbability ( $ n , $ k , $ p ) { return nCr ( $ n , $ k ) * pow ( $ p , $ k ) * pow ( 1 - $ p , $ n - $ k ) ; } $ n = 10 ; $ k = 5 ; $ p = 1.0 / 3 ; $ probability = binomialProbability ( $ n , $ k , $ p ) ; echo " Probability ▁ of ▁ " . $ k ; echo " ▁ heads ▁ when ▁ a ▁ coin ▁ is ▁ tossed ▁ " . $ n ; echo " ▁ times ▁ where ▁ probability ▁ of ▁ " . " each ▁ head ▁ is ▁ " . $ p ; echo " is = " ? >


"Birthday Paradox | Returns approximate number of people for a given probability ; Driver Code"
Solution in php:

< ? php function find ( $ p ) { return ceil ( sqrt ( 2 * 365 * log ( 1 / ( 1 - $ p ) ) ) ) ; } echo find ( 0.70 ) ; ? >


"Bitwise AND of sub | Function to return the minimum possible value of | K - X | where X is the bitwise AND of the elements of some sub - array ; Check all possible sub - arrays ; Find the overall minimum ; Driver code"
Solution in php:

< ? php function closetAND ( & $ arr , $ n , $ k ) { $ ans = PHP_INT_MAX ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ X = $ arr [ $ i ] ; for ( $ j = $ i ; $ j < $ n ; $ j ++ ) { $ X &= $ arr [ $ j ] ; $ ans = min ( $ ans , abs ( $ k - $ X ) ) ; } } return $ ans ; } $ arr = array ( 4 , 7 , 10 ) ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; $ k = 2 ; echo closetAND ( $ arr , $ n , $ k ) ; return 0 ; ? >


"Bitwise OR ( or | ) of a range | Returns the Most Significant Bit Position ( MSB ) ; Returns the Bitwise OR of all integers between L and R ; Find the MSB position in L ; Find the MSB position in R ; Add this value until msb_p1 and msb_p2 are same ; ; Calculate msb_p1 and msb_p2 ; Find the max of msb_p1 and msb_p2 ; Set all the bits from msb_p1 upto 0 th bit in the result ; Driver Code"
Solution in php:

< ? php function MSBPosition ( $ N ) { $ msb_p = -1 ; while ( $ N ) { $ N = $ N >> 1 ; $ msb_p ++ ; } return $ msb_p ; } function findBitwiseOR ( $ L , $ R ) { $ res = 0 ; $ msb_p1 = MSBPosition ( $ L ) ; $ msb_p2 = MSBPosition ( $ R ) ; while ( $ msb_p1 == $ msb_p2 ) { $ res_val = ( 1 << $ msb_p1 ) ; $ res += $ res_val ; $ L -= $ res_val ; $ R -= $ res_val ; $ msb_p1 = MSBPosition ( $ L ) ; $ msb_p2 = MSBPosition ( $ R ) ; } $ msb_p1 = max ( $ msb_p1 , $ msb_p2 ) ; for ( $ i = $ msb_p1 ; $ i >= 0 ; $ i -- ) { $ res_val = ( 1 << $ i ) ; $ res += $ res_val ; } return $ res ; } $ L = 12 ; $ R = 18 ; echo findBitwiseOR ( $ L , $ R ) ; ? >


"Bitwise and ( or & ) of a range | Find position of MSB in n . For example if n = 17 , then position of MSB is 4. If n = 7 , value of MSB is 3 ; Function to find Bit - wise & of all numbers from x to y . ; $res = 0 ; Initialize result ; Find positions of MSB in x and y ; If positions are not same , return ; Add 2 ^ msb_p1 to result ; subtract 2 ^ msb_p1 from x and y . ; Driver code"
Solution in php:

< ? php function msbPos ( $ n ) { $ msb_p = -1 ; while ( $ n > 0 ) { $ n = $ n >> 1 ; $ msb_p ++ ; } return $ msb_p ; } function andOperator ( $ x , $ y ) { while ( $ x > 0 && $ y > 0 ) { $ msb_p1 = msbPos ( $ x ) ; $ msb_p2 = msbPos ( $ y ) ; if ( $ msb_p1 != $ msb_p2 ) break ; $ msb_val = ( 1 << $ msb_p1 ) ; $ res = $ res + $ msb_val ; $ x = $ x - $ msb_val ; $ y = $ y - $ msb_val ; } return $ res ; } $ x = 10 ; $ y = 15 ; echo andOperator ( $ x , $ y ) ; ? >


"Bitwise recursive addition of two integers | php program to do recursive addition of two integers ; If bitwise & is 0 , then there is not going to be any carry . Hence result of XOR is addition . ; Driver code"
Solution in php:

< ? php function add ( $ x , $ y ) { $ keep = ( $ x & $ y ) << 1 ; $ res = $ x ^ $ y ; if ( $ keep == 0 ) { echo $ res ; exit ( 0 ) ; } add ( $ keep , $ res ) ; } $ k = add ( 15 , 38 ) ; ? >


"Blum Integer | Function to cheek if number is Blum Integer ; to store prime numbers from 2 to n ; If prime [ i ] is not changed , then it is a prime ; Update all multiples of p ; to check if the given odd integer is Blum Integer or not ; checking the factors are of 4 t + 3 form or not ; give odd integer greater than 20"
Solution in php:


"Boundary elements of a Matrix | PHP program to find sum of boundary elements of matrix . ; Driver code"
Solution in php:

< ? php function getBoundarySum ( $ a , $ m , $ n ) { $ sum = 0 ; for ( $ i = 0 ; $ i < $ m ; $ i ++ ) { for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( $ i == 0 ) $ sum += $ a [ $ i ] [ $ j ] ; else if ( $ i == $ m - 1 ) $ sum += $ a [ $ i ] [ $ j ] ; else if ( $ j == 0 ) $ sum += $ a [ $ i ] [ $ j ] ; else if ( $ j == $ n - 1 ) $ sum += $ a [ $ i ] [ $ j ] ; } } return $ sum ; } $ a = array ( array ( 1 , 2 , 3 , 4 ) , array ( 5 , 6 , 7 , 8 ) , array ( 1 , 2 , 3 , 4 ) , array ( 5 , 6 , 7 , 8 ) ) ; $ sum = getBoundarySum ( $ a , 4 , 4 ) ; echo " Sum ▁ of ▁ boundary ▁ elements ▁ is ▁ " , $ sum ; ? >


"Boundary elements of a Matrix | PHP program to print boundary element of matrix . ; Driver code"
Solution in php:


"Brahmagupta Fibonacci Identity | PHP code to verify Brahmagupta Fibonacci identity ; represent the product as sum of 2 squares ; check identity criteria ; 1 ^ 2 + 2 ^ 2 ; 3 ^ 2 + 4 ^ 2 ; express product of sum of 2 squares as sum of ( sumof 2 squares )"
Solution in php:

 < ? php function find_sum_of_two_squares ( $ a , $ b ) { $ ab = $ a * $ b ; for ( $ i = 0 ; $ i * $ i <= $ ab ; $ i ++ ) { for ( $ j = $ i ; $ i * $ i + $ j * $ j <= $ ab ; $ j ++ ) { if ( $ i * $ i + $ j * $ j == $ ab ) echo $ i , " ^ 2 ▁ + ▁ " , $ j , " ^ 2 ▁ = ▁ " , $ ab , "
 " ; } } } $ a = 1 * 1 + 2 * 2 ; $ b = 3 * 3 + 4 * 4 ; echo " Representation ▁ of ▁ a ▁ * ▁ b ▁ " . " as ▁ sum ▁ of ▁ 2 ▁ squares :
 " ; find_sum_of_two_squares ( $ a , $ b ) ; ? >


"Break a number such that sum of maximum divisors of all parts is minimum | Function to check if a number is prime or not . ; If n is an even number ( we can write it as sum of two primes ) ; If n is odd and n - 2 is prime . ; If n is odd , n - 3 must be even . ; Driver code"
Solution in php:

< ? php function isPrime ( $ n ) { $ i = 2 ; while ( $ i * $ i <= $ n ) { if ( $ n % $ i == 0 ) return false ; $ i ++ ; } return true ; } function minimumSum ( $ n ) { if ( isPrime ( $ n ) ) return 1 ; if ( $ n % 2 == 0 ) return 2 ; if ( isPrime ( $ n - 2 ) ) return 2 ; return 3 ; } $ n = 27 ; echo minimumSum ( $ n ) ; ? >


"Break the number into three parts | Function to count number of ways to make the given number n ; Driver Code"
Solution in php:

< ? php function count_of_ways ( $ n ) { $ count ; $ count = ( $ n + 1 ) * ( $ n + 2 ) / 2 ; return $ count ; } $ n = 3 ; echo count_of_ways ( $ n ) ; ? >


"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"
Solution in php:

< ? php function power ( $ x , $ a ) { $ res = 1 ; while ( $ a ) { if ( $ a & 1 ) $ res = $ res * $ x ; $ x = $ x * $ x ; $ a >>= 1 ; } return $ res ; } function breakInteger ( $ N ) { if ( $ N == 2 ) return 1 ; if ( $ N == 3 ) return 2 ; $ maxProduct = 0 ; switch ( $ N % 3 ) { case 0 : $ maxProduct = power ( 3 , $ N / 3 ) ; break ; case 1 : $ maxProduct = 2 * 2 * power ( 3 , ( $ N / 3 ) - 1 ) ; break ; case 2 : $ maxProduct = 2 * power ( 3 , $ N / 3 ) ; break ; } return $ maxProduct ; } $ maxProduct = breakInteger ( 10 ) ; echo $ maxProduct ; ? >


"Buy minimum items without change and given coins | See if we can buy less than 10 items Using 10 Rs coins and one r Rs coin ; We can always buy 10 items ; Driver Code"
Solution in php:


"Calculate Volume of Dodecahedron | utility Function ; Driver Function"
Solution in php:

< ? php function vol_of_dodecahedron ( $ side ) { return ( ( ( 15 + ( 7 * ( sqrt ( 5 ) ) ) ) / 4 ) * ( pow ( $ side , 3 ) ) ) ; } $ side = 4 ; echo ( " Volume ▁ of ▁ dodecahedron ▁ = ▁ " ) ; echo ( vol_of_dodecahedron ( $ side ) ) ; ? >


"Calculate score for the given binary string | Function to return the score for the given binary string ; Traverse through string character ; Initialize current chunk 's size ; Get current character ; Calculate total chunk size of same characters ; Add / subtract pow ( chunkSize , 2 ) depending upon character ; Return the score ; Driver code"
Solution in php:

< ? php function calcScore ( $ str ) { $ score = 0 ; $ len = strlen ( $ str ) ; for ( $ i = 0 ; $ i < $ len { $ chunkSize = 1 ; $ currentChar = $ str [ $ i ++ ] ; while ( $ i < $ len && $ str [ $ i ] == $ currentChar ) { $ chunkSize ++ ; $ i ++ ; } if ( $ currentChar == '1' ) $ score += pow ( $ chunkSize , 2 ) ; else $ score -= pow ( $ chunkSize , 2 ) ; } return $ score ; } $ str = "11011" ; echo calcScore ( $ str ) ; ? >


"Calculate speed , distance and time | Function to calculate speed ; Function to calculate distance traveled ; Function to calculate time taken ; Calling function cal_speed ( ) ; Calling function cal_dis ( ) ; Calling function cal_time ( )"
Solution in php:

 < ? php function cal_speed ( $ dist , $ time ) { echo " Distance ( km ) : " echo " Time ( hr ) : " return $ dist / $ time ; } function cal_dis ( $ speed , $ time ) { echo " Time ( hr ) : " echo " Speed ( km / hr ) : " return $ speed * $ time ; } function cal_time ( $ dist , $ speed ) { echo " Distance ( km ) : " echo " Speed ( km / hr ) : " return $ speed * $ dist ; } echo " ▁ The ▁ calculated ▁ Speed ( km ▁ / ▁ hr ) ▁ is ▁ : ▁ " . cal_speed ( 45.9 , 2.0 ) . "
 " ; echo " The calculated Distance ( km ) : " . cal_dis ( 62.9 , 2.5 ) . " " ; echo " The calculated Time ( hr ) : " . cal_time ( 48.0 , 4.5 ) . " " ; ? >


"Calculate the angle between hour hand and minute hand | Utility function to find minimum of two integers ; Function to calculate the angle ; validate the input ; Calculate the angles moved by hour and minute hands with reference to 12 : 00 ; Find the difference between two angles ; Return the smaller angle of two possible angles ; Driver Code"
Solution in php:

 < ? php function mintwo ( $ x , $ y ) { return ( $ x < $ y ) ? $ x : $ y ; } function calcAngle ( $ h , $ m ) { if ( $ h < 0 $ m < 0 $ h > 12 $ m > 60 ) echo " Wrong ▁ input " ; if ( $ h == 12 ) $ h = 0 ; if ( $ m == 60 ) { $ m = 0 ; $ h += 1 ; if ( $ h > 12 ) $ h = $ h - 12 ; } $ hour_angle = 0.5 * ( $ h * 60 + $ m ) ; $ minute_angle = 6 * $ m ; $ angle = abs ( $ hour_angle - $ minute_angle ) ; $ angle = min ( 360 - $ angle , $ angle ) ; return $ angle ; } echo calcAngle ( 9 , 60 ) , "
 " ; echo calcAngle ( 3 , 30 ) , "
 " ; ? >


"Calculate the loss incurred in selling the given items at discounted price | Function to return the x % of n ; Function to return the total loss ; To store the total loss ; Original price of the item ; The price at which the item will be sold ; The discounted price of the item ; Loss incurred ; Driver code ; Total items"
Solution in php:

< ? php function percent ( $ n , $ x ) { $ p = ( int ) ( $ n ) * $ x ; $ p /= 100 ; return $ p ; } function getLoss ( $ price , $ quantity , $ X , $ n ) { $ loss = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ originalPrice = $ price [ $ i ] ; $ sellingPrice = $ originalPrice + percent ( $ originalPrice , $ X [ $ i ] ) ; $ afterDiscount = $ sellingPrice - percent ( $ sellingPrice , $ X [ $ i ] ) ; $ loss += ( ( $ originalPrice - $ afterDiscount ) * $ quantity [ $ i ] ) ; } return $ loss ; } $ price = array ( 20 , 48 , 200 , 100 ) ; $ quantity = array ( 20 , 48 , 1 , 1 ) ; $ X = array ( 0 , 48 , 200 , 5 ) ; $ n = count ( $ X ) ; echo getLoss ( $ price , $ quantity , $ X , $ n ) ; ? >


"Calculate volume and surface area of a cone | Function to calculate Volume of cone ; Function to calculate Surface area of cone ; Driver Code ; Printing value of volume and surface area"
Solution in php:

 < ? php function volume ( $ r , $ h ) { $ pi = 3.14159 ; return ( 1 / 3 ) * $ pi * $ r * $ r * $ h ; } function surface_area ( $ r , $ s ) { $ pi = 3.14159 ; return $ pi * $ r * $ s + $ pi * $ r * $ r ; } $ radius = 5 ; $ slant_height = 13 ; $ height = 12 ; echo ( " Volume ▁ Of ▁ Cone ▁ : ▁ " ) ; echo ( volume ( $ radius , $ height ) ) ; echo ( "
 " ) ; echo ( " Surface ▁ Area ▁ Of ▁ Cone ▁ : ▁ " ) ; echo ( surface_area ( $ radius , $ slant_height ) ) ; ? >


"Calculating Factorials using Stirling Approximation | Function for calculating factorial ; value of natural e ; evaluating factorial using stirling approximation ; Driver Code"
Solution in php:

 < ? php function stirlingFactorial ( $ n ) { if ( $ n == 1 ) return 1 ; $ z ; $ e = 2.71 ; $ z = sqrt ( 2 * 3.14 * $ n ) * pow ( ( $ n / $ e ) , $ n ) ; return floor ( $ z ) ; } echo stirlingFactorial ( 1 ) , "
 " ; echo stirlingFactorial ( 2 ) , "
 " ; echo stirlingFactorial ( 3 ) , "
 " ; echo stirlingFactorial ( 4 ) , "
 " ; echo stirlingFactorial ( 5 ) , "
 " ; echo stirlingFactorial ( 6 ) , " ▁
 " ; echo stirlingFactorial ( 7 ) , " ▁
 " ; ? >


"Capitalize the first and last character of each word in a string | PHP program to capitalise the first and last character of each word in a string . ; Create an equivalent string of the given string ; $k stores index of first character and $i is going to store index of last character . ; Check if the character is a small letter If yes , then Capitalise ; Driver code"
Solution in php:


"Cassiniâ €™ s Identity | Returns ( - 1 ) ^ n ; Driver Code"
Solution in php:

< ? php function cassini ( $ n ) { return ( $ n & 1 ) ? -1 : 1 ; } $ n = 5 ; echo ( cassini ( $ n ) ) ; ? >


"Ceiling in a sorted array | Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to first element , then return the first element ; Otherwise , linearly search for ceil value ; if x lies between arr [ i ] and arr [ i + 1 ] including arr [ i + 1 ] , then return arr [ i + 1 ] ; If we reach here then x is greater than the last element of the array , return - 1 in this case ; Driver Code"
Solution in php:

< ? php function ceilSearch ( $ arr , $ low , $ high , $ x ) { if ( $ x <= $ arr [ $ low ] ) return $ low ; for ( $ i = $ low ; $ i < $ high ; $ i ++ ) { if ( $ arr [ $ i ] == $ x ) return $ i ; if ( $ arr [ $ i ] < $ x && $ arr [ $ i + 1 ] >= $ x ) return $ i + 1 ; } return -1 ; } $ arr = array ( 1 , 2 , 8 , 10 , 10 , 12 , 19 ) ; $ n = sizeof ( $ arr ) ; $ x = 3 ; $ index = ceilSearch ( $ arr , 0 , $ n - 1 , $ x ) ; if ( $ index == -1 ) echo ( " Ceiling ▁ of ▁ " . $ x . " ▁ doesn ' t ▁ exist ▁ in ▁ array ▁ " ) ; else echo ( " ceiling ▁ of ▁ " . $ x . " ▁ is ▁ " . $ arr [ $ index ] ) ; ? >


"Ceiling in a sorted array | Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to the first element , then return the first element ; If x is greater than the last element , then return - 1 ; get the index of middle element of arr [ low . . high ] ; If x is same as middle element , then return mid ; If x is greater than arr [ mid ] , then either arr [ mid + 1 ] is ceiling of x or ceiling lies in arr [ mid + 1. . . high ] ; If x is smaller than arr [ mid ] , then either arr [ mid ] is ceiling of x or ceiling lies in arr [ low ... . mid - 1 ] ; Driver Code"
Solution in php:

< ? php function ceilSearch ( $ arr , $ low , $ high , $ x ) { $ mid ; if ( $ x <= $ arr [ $ low ] ) return $ low ; if ( $ x > $ arr [ $ high ] ) return -1 ; $ mid = ( $ low + $ high ) / 2 ; if ( $ arr [ $ mid ] == $ x ) return $ mid ; else if ( $ arr [ $ mid ] < $ x ) { if ( $ mid + 1 <= $ high && $ x <= $ arr [ $ mid + 1 ] ) return $ mid + 1 ; else return ceilSearch ( $ arr , $ mid + 1 , $ high , $ x ) ; } else { if ( $ mid - 1 >= $ low && $ x > $ arr [ $ mid - 1 ] ) return $ mid ; else return ceilSearch ( $ arr , $ low , $ mid - 1 , $ x ) ; } } $ arr = array ( 1 , 2 , 8 , 10 , 10 , 12 , 19 ) ; $ n = sizeof ( $ arr ) ; $ x = 20 ; $ index = ceilSearch ( $ arr , 0 , $ n - 1 , $ x ) ; if ( $ index == -1 ) echo ( " Ceiling ▁ of ▁ $ x ▁ doesn ' t ▁ exist ▁ in ▁ array ▁ " ) ; else echo ( " ceiling ▁ of ▁ $ x ▁ is " ) ; echo ( isset ( $ arr [ $ index ] ) ) ; ? >


"Center element of matrix equals sums of half diagonals | PHP Program to check if the center element is equal to the individual sum of all the half diagonals ; Function to Check center element is equal to the individual sum of all the half diagonals ; Find sums of half diagonals ; Driver code"
Solution in php:

< ? php $ MAX = 100 ; function HalfDiagonalSums ( $ mat , $ n ) { global $ MAX ; $ diag1_left = 1 ; $ diag1_right = 1 ; $ diag2_left = 1 ; $ diag2_right = 1 ; for ( $ i = 0 , $ j = $ n - 1 ; $ i < $ n ; $ i ++ , $ j -- ) { if ( $ i < $ n / 2 ) { $ diag1_left += $ mat [ $ i ] [ $ i ] ; $ diag2_left += $ mat [ $ j ] [ $ i ] ; } else if ( $ i > $ n / 2 ) { $ diag1_right += $ mat [ $ i ] [ $ i ] ; $ diag2_right += $ mat [ $ j ] [ $ i ] ; } } return ( $ diag1_left == $ diag2_right && $ diag2_right == $ diag2_left && $ diag1_right == $ diag2_left && $ diag2_right == $ mat [ $ n / 2 ] [ $ n / 2 ] ) ; } $ a = array ( array ( 2 , 9 , 1 , 4 , -2 ) , array ( 6 , 7 , 2 , 11 , 4 ) , array ( 4 , 2 , 9 , 2 , 4 ) , array ( 1 , 9 , 2 , 4 , 4 ) , array ( 0 , 2 , 4 , 2 , 5 ) ) ; if ( HalfDiagonalSums ( $ a , 5 ) == 0 ) echo " Yes " ; else echo " No " ; ? >


"Centered Hexadecagonal Number | centered hexadecagonal function ; Formula to calculate nth centered hexadecagonal number ; Driver Code"
Solution in php:

 < ? php function center_hexadecagonal_num ( $ n ) { return 8 * $ n * $ n - 8 * $ n + 1 ; } $ n = 2 ; echo $ n , " th ▁ centered ▁ hexadecagonal ▁ number ▁ : ▁ " , center_hexadecagonal_num ( $ n ) ; echo "
 " ; $ n = 12 ; echo $ n , " th ▁ centered ▁ hexadecagonal ▁ numbe ▁ : ▁ " , center_hexadecagonal_num ( $ n ) ; ? >


"Centered Octadecagonal Number | centered octadecagon function ; Formula to calculate nth centered octadecagonal number ; Driver Code"
Solution in php:

 < ? php function center_octadecagon_num ( $ n ) { return ( 9 * $ n * $ n - 9 * $ n + 1 ) ; } $ n = 3 ; echo $ n , " th ▁ centered ▁ octadecagonal ▁ " . " number ▁ : ▁ " , center_octadecagon_num ( $ n ) ; echo "
 " ; $ n = 13 ; echo $ n , " th ▁ centered ▁ octadecagonal ▁ " . " number ▁ : ▁ " , center_octadecagon_num ( $ n ) ; ? >


"Centered Octagonal Number | Centered octagonal number function ; Formula to calculate nth centered octagonal number & return it into main function . ; Driver Code"
Solution in php:

 < ? php function cen_octagonalnum ( $ n ) { return ( 4 * $ n * $ n - 4 * $ n + 1 ) ; } $ n = 6 ; echo $ n , " th ▁ centered " , " ▁ octagonal ▁ number ▁ : ▁ " ; echo cen_octagonalnum ( $ n ) ; echo "
 " ; $ n = 11 ; echo $ n , " th ▁ centered " , " ▁ octagonal ▁ number ▁ : ▁ " ; echo cen_octagonalnum ( $ n ) ; ? >


"Centered Pentadecagonal Number | centered pentadecagonal function ; Formula to calculate nth centered pentadecagonal number ; Driver Code"
Solution in php:

 < ? php function center_pentadecagonal_num ( $ n ) { return ( 15 * $ n * $ n - 15 * $ n + 2 ) / 2 ; } $ n = 3 ; echo $ n , " th ▁ number ▁ : ▁ " , center_pentadecagonal_num ( $ n ) ; echo "
 " ; $ n = 10 ; echo $ n , " th ▁ number ▁ : ▁ " , center_pentadecagonal_num ( $ n ) ; ? >


"Centered Square Number | Function to calculate Centered square number function ; Formula to calculate nth Centered square number ; Driver Code"
Solution in php:

< ? php function centered_square_num ( $ n ) { return $ n * $ n + ( ( $ n - 1 ) * ( $ n - 1 ) ) ; } $ n = 7 ; echo $ n , " th ▁ Centered ▁ square ▁ number : ▁ " ; echo centered_square_num ( $ n ) ; ? >


"Centered cube number | Function to find Centered cube number ; Formula to calculate nth Centered cube number & return it into main function . ; Driver Code"
Solution in php:

 < ? php function centered_cube ( $ n ) { return ( 2 * $ n + 1 ) * ( $ n * $ n + $ n + 1 ) ; } $ n = 3 ; echo $ n , " th ▁ Centered ▁ cube ▁ number : ▁ " ; echo centered_cube ( $ n ) ; echo "
 " ; $ n = 10 ; echo $ n , " th ▁ Centered ▁ cube ▁ number : ▁ " ; echo centered_cube ( $ n ) ; ? >


"Centered decagonal number | Centered decagonal number function ; Formula to calculate nth centered decagonal number & return it into main function . ; Driver Code"
Solution in php:

 < ? php function centereddecagonalnum ( $ n ) { return ( 5 * $ n * $ n + 5 * $ n + 1 ) ; } $ n = 5 ; echo $ n , " th ▁ centered ▁ decagonal " , " number : ▁ " ; echo centereddecagonalnum ( $ n ) ; echo "
 " ; $ n = 9 ; echo $ n , " th ▁ centered ▁ decagonal " , " number : ▁ " ; echo centereddecagonalnum ( $ n ) ; ? >


"Centered heptagonal number | Function to find Centered heptagonal number ; Formula to calculate nth Centered heptagonal number ; Driver Code"
Solution in php:

< ? php function centered_heptagonal_num ( $ n ) { return ( 7 * $ n * $ n - 7 * $ n + 2 ) / 2 ; } $ n = 5 ; echo $ n , " th ▁ Centered ▁ heptagonal ▁ number ▁ : ▁ " ; echo centered_heptagonal_num ( $ n ) ; ? >


"Centered hexagonal number | Function to find centered hexadecimal number . ; Formula to calculate nth centered hexadecimal number and return it into main function . ; Driver Code"
Solution in php:

< ? php function centeredHexagonalNumber ( $ n ) { return 3 * $ n * ( $ n - 1 ) + 1 ; } $ n = 10 ; echo $ n , " th ▁ centered ▁ hexagonal ▁ number : ▁ " ; echo centeredHexagonalNumber ( $ n ) ; ? >


"Centered nonadecagonal number | centered nonadecagonal function ; Formula to calculate nth centered nonadecagonal number ; Driver Code"
Solution in php:

 < ? php function center_nonadecagon_num ( $ n ) { return ( 19 * $ n * $ n - 19 * $ n + 2 ) / 2 ; } $ n = 2 ; echo $ n , " th ▁ centered ▁ " + " nonadecagonal ▁ number ▁ : ▁ " , center_nonadecagon_num ( $ n ) ; echo "
 " ; $ n = 7 ; echo $ n , " th ▁ centered ▁ " + " nonadecagonal ▁ number ▁ : ▁ " , center_nonadecagon_num ( $ n ) ; ? >


"Centered pentagonal number | Centered pentagonal number function ; Formula to calculate nth Centered pentagonal number and return it into main function . ; Driver Code"
Solution in php:

< ? php function centered_pentagonal_Num ( $ n ) { return ( 5 * $ n * $ n - 5 * $ n + 2 ) / 2 ; } $ n = 7 ; echo $ n , " th ▁ Centered ▁ pentagonal ▁ number : ▁ " ; echo centered_pentagonal_Num ( $ n ) ; ? >


"Centered tetrahedral number | Function to find centered Centered tetrahedral number ; Formula to calculate nth Centered tetrahedral number and return it into main function . ; Driver Code"
Solution in php:

< ? php function centeredTetrahedralNumber ( $ n ) { return ( 2 * $ n + 1 ) * ( $ n * $ n + $ n + 3 ) / 3 ; } $ n = 6 ; echo centeredTetrahedralNumber ( $ n ) ; ? >


"Centered triangular number | function for Centered Triangular number ; formula for find Centered Triangular number nth term ; For 3 rd Centered Triangular number ; For 12 th Centered Triangular number"
Solution in php:

 < ? php function Centered_Triangular_num ( $ n ) { return ( 3 * $ n * $ n + 3 * $ n + 2 ) / 2 ; } $ n = 3 ; echo Centered_Triangular_num ( $ n ) , "
 " ; $ n = 12 ; echo Centered_Triangular_num ( $ n ) , "
 " ; ? >


"Centered tridecagonal number | Function to find nth centered tridecagonal number ; Formula to calculate nth centered tridecagonal number ; Driver Code"
Solution in php:

 < ? php function centeredTridecagonalNum ( $ n ) { return ( 13 * $ n * ( $ n - 1 ) + 2 ) / 2 ; } $ n = 3 ; echo centeredTridecagonalNum ( $ n ) ; echo "
 " ; $ n = 10 ; echo centeredTridecagonalNum ( $ n ) ; ? >


"Centrosymmetric Matrix | PHP Program to check whether given matrix is centrosymmetric or not . ; Finding the middle row of the matrix ; for each row upto middle row . ; If each element and its corresponding element is not equal then return false . ; Driver Code"
Solution in php:

< ? php function checkCentrosymmetricted ( $ n , $ m ) { $ mid_row ; if ( $ n & 1 ) $ mid_row = $ n / 2 + 1 ; else $ mid_row = $ n / 2 ; for ( $ i = 0 ; $ i < $ mid_row ; $ i ++ ) { for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( $ m [ $ i ] [ $ j ] != $ m [ $ n - $ i - 1 ] [ $ n - $ j - 1 ] ) return false ; } } return true ; } $ n = 3 ; $ m = array ( array ( 1 , 3 , 5 ) , array ( 6 , 8 , 6 ) , array ( 5 , 3 , 1 ) ) ; if ( checkCentrosymmetricted ( $ n , $ m ) ) echo " Yes " ; else echo " No " ; ? >


"Change all even bits in a number to 0 | Returns modified number with all even bits 0. ; To store sum of bits at even positions . ; To store bits to shift ; One by one put all even bits to end ; If current last bit is set , add it to ans ; Next shift position ; Driver code"
Solution in php:

< ? php function changeEvenBits ( $ n ) { $ to_subtract = 0 ; $ m = 0 ; for ( $ x = $ n ; $ x ; $ x >>= 2 ) { if ( $ x & 1 ) $ to_subtract += ( 1 << $ m ) ; $ m += 2 ; } return $ n - $ to_subtract ; } $ n = 30 ; echo changeEvenBits ( $ n ) ; ? >


"Change bits to make specific OR value | Returns max of three numbers ; Returns count of bits in N ; Returns bit at ' pos ' position ; Utility method to toggle bit at ' pos ' position ; method returns minimum number of bit flip to get T as OR value of A and B ; Loop over maximum number of bits among A , B and T ; T 's bit is set, try to toggle  bit of B, if not already ; if A 's bit is set,   flip that ; if B 's bit is set,  flip that ; if K is less than 0 then we can make A | B == T ; Loop over bits one more time to minimise A further ; If both bit are set , then Unset A 's bit to minimise it ; If A ' s ▁ bit ▁ is ▁ 1 ▁ and ▁ B ' s bit is 0 , toggle both ; Output changed value of A and B ; Driver Code"
Solution in php:

 < ? php function maxDD ( $ a , $ b , $ c ) { return max ( $ a , ( max ( $ b , $ c ) ) ) ; } function bitCount ( $ N ) { $ cnt = 0 ; while ( $ N ) { $ cnt ++ ; $ N >>= 1 ; } return $ cnt ; } function at_position ( $ num , $ pos ) { $ bit = $ num & ( 1 << $ pos ) ; return $ bit ; } function toggle ( & $ num , $ pos ) { $ num ^= ( 1 << $ pos ) ; } function minChangeToReachTaregetOR ( $ A , $ B , $ K , $ T ) { $ maxlen = max ( bitCount ( $ A ) , bitCount ( $ B ) , bitCount ( $ T ) ) ; for ( $ i = $ maxlen - 1 ; $ i >= 0 ; $ i -- ) { $ bitA = at_position ( $ A , $ i ) ; $ bitB = at_position ( $ B , $ i ) ; $ bitT = at_position ( $ T , $ i ) ; if ( $ bitT ) { if ( ! $ bitA && ! $ bitB ) { toggle ( $ B , $ i ) ; $ K -- ; } } else { if ( $ bitA ) { toggle ( $ A , $ i ) ; $ K -- ; } if ( $ bitB ) { toggle ( $ B , $ i ) ; $ K -- ; } } } if ( $ K < 0 ) { echo " Not ▁ possible
 " ; return ; } for ( $ i = $ maxlen - 1 ; $ K > 0 && $ i >= 0 ; -- $ i ) { $ bitA = at_position ( $ A , $ i ) ; $ bitB = at_position ( $ B , $ i ) ; $ bitT = at_position ( $ T , $ i ) ; if ( $ bitT ) { if ( $ bitA && $ bitB ) { toggle ( $ A , $ i ) ; $ K -- ; } } if ( $ bitA && ! $ bitB && $ K >= 2 ) { toggle ( $ A , $ i ) ; toggle ( $ B , $ i ) ; $ K -= 2 ; } } echo $ A , " " ▁ , ▁ $ B ▁ , ▁ " " } $ A = 175 ; $ B = 66 ; $ K = 5 ; $ T = 100 ; minChangeToReachTaregetOR ( $ A , $ B , $ K , $ T ) ; ? >


"Character replacement after removing duplicates from a string | Function to minimize string ; duplicate characters are removed ; checks if character has previously occurred or not if not then add it to the minimized string ' mstr ' ; return $mstr ; minimized string ; Utility function to print the minimized , replaced string ; Creating final string by replacing character ; index calculation ; echo " Final ▁ string : ▁ " . $finalStr ; final string ; Driver code"
Solution in php:

< ? php function minimize ( $ str ) { $ mstr = " ▁ " ; $ flagchar = array_fill ( 0 , 26 , 0 ) ; $ l = strlen ( $ str ) ; for ( $ i = 0 ; $ i < strlen ( $ str ) ; $ i ++ ) { $ ch = $ str [ $ i ] ; if ( $ flagchar [ ord ( $ ch ) - 97 ] == 0 ) { $ mstr . = $ ch ; $ flagchar [ ord ( $ ch ) - 97 ] = 1 ; } } } function replaceMinimizeUtil ( $ str ) { $ finalStr = " " ; $ l = strlen ( $ str ) ; for ( $ i = 0 ; $ i < strlen ( $ minimizedStr ) ; $ i ++ ) { $ ch = $ minimizedStr [ $ i ] ; $ index = ( ord ( $ ch ) * ord ( $ ch ) ) % $ l ; $ finalStr = $ finalStr . $ str [ $ index ] ; } } $ str = " geeks " ; replaceMinimizeUtil ( $ str ) ; ? >


"Character whose frequency is equal to the sum of frequencies of other characters of the given string | Function that returns true if some character exists in the given string whose frequency is equal to the sum frequencies of other characters of the string ; If string is of odd length ; To store the frequency of each character of the string ; Update the frequencies of the characters ; No such character exists ; Driver code"
Solution in php:

< ? php function isFrequencyEqual ( $ str , $ len ) { if ( $ len % 2 == 1 ) return false ; $ freq = array ( ) ; for ( $ i = 0 ; $ i < 26 ; $ i ++ ) $ freq [ $ i ] = 0 ; for ( $ i = 0 ; $ i < $ len ; $ i ++ ) $ freq [ ord ( $ str [ $ i ] ) - 97 ] ++ ; for ( $ i = 0 ; $ i < 26 ; $ i ++ ) if ( $ freq [ $ i ] == $ len / 2 ) return true ; return false ; } $ str = " geeksforgeeks " ; $ len = strlen ( $ str ) ; if ( isFrequencyEqual ( $ str , $ len ) ) echo " Yes " ; else echo " No " ; ? >


"Check If every group of a ' s ▁ is ▁ followed ▁ by ▁ a ▁ group ▁ of ▁ b ' s of same length | Function to match whether there are always n consecutive b ' s ▁ followed ▁ by ▁ n ▁ consecutive ▁ a ' s throughout the string ; Traverse through the string ; Count a 's in current segment ; Count b 's in current segment ; If both counts are not same . ; Driver code"
Solution in php:

< ? php function matchPattern ( $ s ) { $ count = 0 ; $ n = strlen ( $ s ) ; $ i = 0 ; while ( $ i < $ n ) { while ( $ i < $ n && $ s [ $ i ] == ' a ' ) { $ count ++ ; $ i ++ ; } while ( $ i < $ n && $ s [ $ i ] == ' b ' ) { $ count -- ; $ i ++ ; } if ( $ count != 0 ) return false ; } return true ; } $ s = " bb " ; if ( matchPattern ( $ s ) == true ) echo " Yes " ; else echo " No " ; ? >


"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"
Solution in php:


"Check a number is odd or even without modulus operator | Returns true if n is even , else odd ; Driver code"
Solution in php:

< ? php function isEven ( $ n ) { $ isEven = true ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) $ isEven = ! $ isEven ; return $ isEven ; } $ n = 101 ; $ is = isEven ( $ n ) ? " Even " : " Odd " ; echo " $ is " ? >


"Check a number is odd or even without modulus operator | Returns true if n is even , else odd ; Return true if n / 2 does not result in a float value . ; Driver code"
Solution in php:

< ? php function isEven ( $ n ) { return ( ( int ) ( $ n / 2 ) * 2 == $ n ) ; } $ n = 101 ; if ( isEven ( $ n ) ) echo ( " Even " ) ; else echo ( " Odd " ) ; ? >


"Check for Amicable Pair | Function to calculate sum of all proper divisors of a given number ; Sum of divisors ; find all divisors which divides ' num ' ; if ' i ' is divisor of ' n ' ; if both divisors are same then add it once else add both ; Add 1 and n to result as above loop considers proper divisors greater than 1. ; Returns true if x and y are Amicable else false . ; Driver Code"
Solution in php:

< ? php function divSum ( $ n ) { $ result = 0 ; for ( $ i = 2 ; $ i <= sqrt ( $ n ) ; $ i ++ ) { if ( $ n % $ i == 0 ) { if ( $ i == ( $ n / $ i ) ) $ result += $ i ; else $ result += ( $ i + $ n / $ i ) ; } } return ( $ result + 1 ) ; } function areAmicable ( $ x , $ y ) { if ( divSum ( $ x ) != $ y ) return false ; return ( divSum ( $ y ) == $ x ) ; } $ x = 220 ; $ y = 284 ; if ( areAmicable ( $ x , $ y ) ) echo " Yes " ; else echo " No " ; ? >


"Check for balanced parentheses in an expression | O ( 1 ) space | Function1 to match closing bracket ; Function1 to match opening bracket ; Function to check balanced parentheses ; helper variables ; Handling case of opening parentheses ; Handling case of closing parentheses ; If corresponding matching opening parentheses doesn 't lie in given interval return 0 ; else continue ; If corresponding closing parentheses doesn 't lie in given interval  return 0 ; if found , now check for each opening and closing parentheses in this interval ; Driver Code"
Solution in php:

< ? php function matchClosing ( $ X , $ start , $ end , $ open , $ close ) { $ c = 1 ; $ i = $ start + 1 ; while ( $ i <= $ end ) { if ( $ X [ $ i ] == $ open ) { $ c ++ ; } else if ( $ X [ $ i ] == $ close ) { $ c -- ; } if ( $ c == 0 ) { return $ i ; } $ i ++ ; } return $ i ; } function matchingOpening ( $ X , $ start , $ end , $ open , $ close ) { $ c = -1 ; $ i = $ end - 1 ; while ( $ i >= $ start ) { if ( $ X [ $ i ] == $ open ) { $ c ++ ; } else if ( $ X [ $ i ] == $ close ) { $ c -- ; } if ( $ c == 0 ) { return $ i ; } $ i -- ; } return -1 ; } function isBalanced ( $ X , $ n ) { $ i ; $ j = 0 ; $ k ; $ x ; $ start ; $ end ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ X [ $ i ] == ' ( ' ) { $ j = matchClosing ( $ X , $ i , $ n - 1 , ' ( ' , ' ) ' ) ; } else if ( $ X [ $ i ] == ' { ' ) { $ j = matchClosing ( $ X , $ i , $ n - 1 , ' { ' , ' } ' ) ; } else if ( $ X [ $ i ] == ' [ ' ) { $ j = matchClosing ( $ X , $ i , $ n - 1 , ' [ ' , ' ] ' ) ; } else { if ( $ X [ $ i ] == ' ) ' ) { $ j = matchingOpening ( $ X , 0 , $ i , ' ( ' , ' ) ' ) ; } else if ( $ X [ $ i ] == ' } ' ) { $ j = matchingOpening ( $ X , 0 , $ i , ' { ' , ' } ' ) ; } else if ( $ X [ $ i ] == ' ] ' ) { $ j = matchingOpening ( $ X , 0 , $ i , ' [ ' , ' ] ' ) ; } if ( $ j < 0 $ j >= $ i ) { return false ; } continue ; } if ( $ j >= $ n $ j < 0 ) { return false ; } $ start = $ i ; $ end = $ j ; for ( $ k = $ start + 1 ; $ k < $ end ; $ k ++ ) { if ( $ X [ $ k ] == ' ( ' ) { $ x = matchClosing ( $ X , $ k , $ end , ' ( ' , ' ) ' ) ; if ( ! ( $ k < $ x && $ x < $ end ) ) { return false ; } } else if ( $ X [ $ k ] == ' ) ' ) { $ x = matchingOpening ( $ X , $ start , $ k , ' ( ' , ' ) ' ) ; if ( ! ( $ start < $ x && $ x < $ k ) ) { return false ; } } if ( $ X [ $ k ] == ' { ' ) { $ x = matchClosing ( $ X , $ k , $ end , ' { ' , ' } ' ) ; if ( ! ( $ k < $ x && $ x < $ end ) ) { return false ; } } else if ( $ X [ $ k ] == ' } ' ) { $ x = matchingOpening ( $ X , $ start , $ k , ' { ' , ' } ' ) ; if ( ! ( $ start < $ x && $ x < $ k ) ) { return...


"Check for integer overflow on multiplication | Function to check whether there is overflow in a * b or not . It returns true if there is overflow . ; Check if either of them is zero ; Driver code"
Solution in php:

< ? php function isOverflow ( $ a , $ b ) { if ( $ a == 0 $ b == 0 ) return false ; $ result = $ a * $ b ; if ( $ a == ( int ) $ result / $ b ) return false ; else return true ; } $ a = 10000000000 ; $ b = -10000000000 ; if ( isOverflow ( $ a , $ b ) ) echo " Yes " ; else echo " No " ; ? >


"Check for possible path in 2D matrix | PHP program to find if there is path from top left to right bottom ; to find the path from top left to bottom right ; set arr [ 0 ] [ 0 ] = 1 ; Mark reachable ( from top left ) nodes in first row and first column . ; Mark reachable nodes in remaining matrix . ; return yes if right bottom index is 1 ; Given array ; path from arr [ 0 ] [ 0 ] to arr [ row ] [ col ]"
Solution in php: