"Number of subsequences of the form a ^ i b ^ j c ^ k | Returns count of subsequences of the form a ^ i b ^ j c ^ k ; Initialize counts of different subsequences caused by different combination of ' a ' ; Initialize counts of different subsequences caused by different combination of ' a ' and different combination of ' b ' ; Initialize counts of different subsequences caused by different combination of ' a ' , ' b ' and ' c ' . ; Traverse all characters of given string ; If current character is ' a ' , then there are following possibilities : a ) Current character begins a new subsequence . b ) Current character is part of aCount subsequences . c ) Current character is not part of aCount subsequences . ; If current character is ' b ' , then there are following possibilities : a ) Current character begins a new subsequence of b 's with aCount subsequences. b) Current character is part of bCount subsequences. c) Current character is not part of  bCount subsequences.  ; If current character is ' c ' , then there are following possibilities : a ) Current character begins a new subsequence of c 's with bCount subsequences. b) Current character is part of cCount subsequences. c) Current character is not part of  cCount subsequences.  ; Driver Code"
Solution in php:

< ? php function countSubsequences ( $ s ) { $ aCount = 0 ; $ bCount = 0 ; $ cCount = 0 ; for ( $ i = 0 ; $ i < strlen ( $ s ) ; $ i ++ ) { if ( $ s [ $ i ] == ' a ' ) $ aCount = ( 1 + 2 * $ aCount ) ; else if ( $ s [ $ i ] == ' b ' ) $ bCount = ( $ aCount + 2 * $ bCount ) ; else if ( $ s [ $ i ] == ' c ' ) $ cCount = ( $ bCount + 2 * $ cCount ) ; } return $ cCount ; } $ s = " abbc " ; echo countSubsequences ( $ s ) ; ? >


"Number of substrings of a string | PHP program to count number of substrings of a string ; Driver Code"
Solution in php:

< ? php function countNonEmptySubstr ( $ str ) { $ n = strlen ( $ str ) ; return $ n * ( $ n + 1 ) / 2 ; } $ s = " abcde " ; echo countNonEmptySubstr ( $ s ) ; ? >


"Number of substrings of one string present in other | PHP program to count number of substrings of s1 present in s2 . ; s3 stores all substrings of s1 ; check the presence of s3 in s2 ; Driver code"
Solution in php:

< ? php function countSubstrs ( $ s1 , $ s2 ) { $ ans = 0 ; for ( $ i = 0 ; $ i < strlen ( $ s1 ) ; $ i ++ ) { $ s3 = " " ; for ( $ j = $ i ; $ j < strlen ( $ s1 ) ; $ j ++ ) { $ s3 += $ s1 [ $ j ] ; if ( stripos ( $ s2 , $ s3 , 0 ) != -1 ) $ ans ++ ; } } return $ ans ; } $ s1 = " aab " ; $ s2 = " aaaab " ; echo countSubstrs ( $ s1 , $ s2 ) ; ? >


"Number of substrings with count of each character as k | PHP program to count number of substrings with counts of distinct characters as k . ; Returns true if all values in freq [ ] are either 0 or k . ; Returns count of substrings where frequency of every present character is k ; Pick a starting point ; Initialize all frequencies as 0 for this starting point ; One by one pick ending points ; Increment frequency of current char ; If frequency becomes more than k , we can 't have more substrings  starting with i ; If frequency becomes k , then check other frequencies as well . ; Driver code"
Solution in php:

 < ? php $ MAX_CHAR = 26 ; function check ( & $ freq , $ k ) { global $ MAX_CHAR ; for ( $ i = 0 ; $ i < $ MAX_CHAR ; $ i ++ ) if ( $ freq [ $ i ] && $ freq [ $ i ] != $ k ) return false ; return true ; } function substrings ( $ s , $ k ) { global $ MAX_CHAR ; for ( $ i = 0 ; $ i < strlen ( $ s ) ; $ i ++ ) { $ freq = array_fill ( 0 , $ MAX_CHAR , NULL ) ; for ( $ j = $ i ; $ j < strlen ( $ s ) ; $ j ++ ) { $ index = ord ( $ s [ $ j ] ) - ord ( ' a ' ) ; $ freq [ $ index ] ++ ; if ( $ freq [ $ index ] > $ k ) break ; else if ( $ freq [ $ index ] == $ k && check ( $ freq , $ k ) == true ) $ res ++ ; } } return $ res ; } $ s = " aabbcc " ; $ k = 2 ; echo substrings ( $ s , $ k ) . "
 " ; $ s = " aabbc " ; $ k = 2 ; echo substrings ( $ s , $ k ) . "
 " ; ? >


"Number of substrings with odd decimal value in a binary string | function to count number of substrings with odd decimal representation ; auxiliary array to store count of 1 's  before ith index ; store count of 1 's  before i-th index ; variable to store answer ; traverse the string reversely to calculate number of odd substrings before i - th index ; Driver code"
Solution in php:

< ? php function countSubstr ( $ s ) { $ n = strlen ( $ s ) ; $ auxArr = array ( ) ; if ( $ s [ 0 ] == '1' ) $ auxArr [ 0 ] = 1 ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { if ( $ s [ $ i ] == '1' ) $ auxArr [ $ i ] = $ auxArr [ $ i - 1 ] + 1 ; else $ auxArr [ $ i ] = $ auxArr [ $ i - 1 ] ; } $ count = 0 ; for ( $ i = $ n - 1 ; $ i >= 0 ; $ i -- ) if ( $ s [ $ i ] == '1' ) $ count += $ auxArr [ $ i ] ; return $ count ; } $ s = "1101" ; echo countSubstr ( $ s ) ; ? >


"Number of swaps to sort when only adjacent swapping allowed | This function merges two sorted arrays and returns inversion count in the arrays . ; i is index for left subarray ; j is index for right subarray ; k is index for resultant merged subarray ; this is tricky -- see above explanation / diagram for merge ( ) ; Copy the remaining elements of left subarray ( if there are any ) to temp ; Copy the remaining elements of right subarray ( if there are any ) to temp ; Copy back the merged elements to original array ; An auxiliary recursive function that sorts the input array and returns the number of inversions in the array . ; Divide the array into two parts and call _mergeSortAndCountInv ( ) for each of the parts ; Inversion count will be sum of inversions in left - part , right - part and number of inversions in merging ; Merge the two parts ; This function sorts the input array and returns the number of inversions in the array ; Driver progra to test above functions"
Solution in php:

< ? php function merge ( & $ arr , & $ temp , $ left , $ mid , $ right ) { $ inv_count = 0 ; $ i = $ left ; $ j = $ mid ; $ k = $ left ; while ( ( $ i <= $ mid - 1 ) && ( $ j <= $ right ) ) { if ( $ arr [ $ i ] <= $ arr [ $ j ] ) $ temp [ $ k ++ ] = $ arr [ $ i ++ ] ; else { $ temp [ $ k ++ ] = $ arr [ $ j ++ ] ; $ inv_count = $ inv_count + ( $ mid - $ i ) ; } } while ( $ i <= $ mid - 1 ) $ temp [ $ k ++ ] = $ arr [ $ i ++ ] ; while ( $ j <= $ right ) $ temp [ $ k ++ ] = $ arr [ $ j ++ ] ; for ( $ i = $ left ; $ i <= $ right ; $ i ++ ) $ arr [ $ i ] = $ temp [ $ i ] ; return $ inv_count ; } function _mergeSort ( & $ arr , & $ temp , $ left , $ right ) { $ inv_count = 0 ; if ( $ right > $ left ) { $ mid = intval ( ( $ right + $ left ) / 2 ) ; $ inv_count = _mergeSort ( $ arr , $ temp , $ left , $ mid ) ; $ inv_count += _mergeSort ( $ arr , $ temp , $ mid + 1 , $ right ) ; $ inv_count += merge ( $ arr , $ temp , $ left , $ mid + 1 , $ right ) ; } return $ inv_count ; } function countSwaps ( & $ arr , $ n ) { $ temp = array_fill ( 0 , $ n , NULL ) ; return _mergeSort ( $ arr , $ temp , 0 , $ n - 1 ) ; } $ arr = array ( 1 , 20 , 6 , 4 , 5 ) ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; echo " Number ▁ of ▁ swaps ▁ is ▁ " . countSwaps ( $ arr , $ n ) ; return 0 ; ? >


"Number of times a number can be replaced by the sum of its digits until it only contains one digit | PHP program to count number of times we need to add digits to get a single digit . ; Here the count variable store how many times we do sum of digits and temporary_sum always store the temporary sum we get at each iteration . ; In this loop we always compute the sum of digits in temporary_ sum variable and convert it into string str till its length become 1 and increase the count in each iteration . ; computing sum of its digits ; converting temporary_sum into string str again . ; increase the count ; Driver Code"
Solution in php:

< ? php function NumberofTimes ( $ str ) { $ temporary_sum = 0 ; $ count = 0 ; while ( strlen ( $ str ) > 1 ) { $ temporary_sum = 0 ; for ( $ i = 0 ; $ i < strlen ( $ str ) ; $ i ++ ) $ temporary_sum += ( $ str [ $ i ] - '0' ) ; $ str = ( string ) ( $ temporary_sum ) ; $ count ++ ; } return $ count ; } $ s = "991" ; echo NumberofTimes ( $ s ) ; ? >


"Number of times the largest perfect square number can be subtracted from N | Function to return the count of steps ; Variable to store the count of steps ; Iterate while N > 0 ; Get the largest perfect square and subtract it from N ; Increment steps ; Return the required count ; Driver code"
Solution in php:

< ? php function countSteps ( $ n ) { $ steps = 0 ; while ( $ n ) { $ largest = ( int ) sqrt ( $ n ) ; $ n -= ( $ largest * $ largest ) ; $ steps ++ ; } return $ steps ; } $ n = 85 ; echo countSteps ( $ n ) ; ? >


"Number of triangles after N moves | function to calculate number of triangles in Nth step ; Driver Code"
Solution in php:

< ? php function numberOfTriangles ( $ n ) { $ ans = 2 * ( pow ( 3 , $ n ) ) - 1 ; return $ ans ; } $ n = 2 ; echo numberOfTriangles ( $ n ) ; ? >


"Number of triangles formed from a set of points on three lines | Returns factorial of a number ; calculate c ( n , r ) ; Driver code"
Solution in php:

 < ? php function factorial ( $ n ) { $ fact = 1 ; for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) $ fact = $ fact * $ i ; return $ fact ; } function ncr ( $ n , $ r ) { return factorial ( $ n ) / ( factorial ( $ r ) * factorial ( $ n - $ r ) ) ; } $ m = 3 ; $ n = 4 ; $ k = 5 ; $ totalTriangles = ncr ( $ m + $ n + $ k , 3 ) - ncr ( $ m , 3 ) - ncr ( $ n , 3 ) - ncr ( $ k , 3 ) ; echo $ totalTriangles . "
 " ;


"Number of triangles in a plane if no more than two points are collinear | Function to find number of triangles in a plane . ; Formula to find number of triangles nC3 = n * ( n - 1 ) * ( n - 2 ) / 6 ; Driver code"
Solution in php:

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


"Number of triangles possible with given lengths of sticks which are powers of 2 | Function to return the number of positive area triangles ; To store the count of total triangles ; To store the count of pairs of sticks with equal lengths ; Back - traverse and count the number of triangles ; Count the number of pairs ; If we have one remaining stick and we have a pair ; Count 1 triangle ; Reduce one pair ; Count the remaining triangles that can be formed ; Driver code"
Solution in php:

< ? php Function countTriangles ( $ a , $ n ) { $ cnt = 0 ; $ pairs = 0 ; for ( $ i = $ n - 1 ; $ i >= 0 ; $ i -- ) { $ pairs += $ a [ $ i ] / 2 ; if ( $ a [ $ i ] % 2 == 1 && $ pairs > 0 ) { $ cnt += 1 ; $ pairs -= 1 ; } } $ cnt += ( int ) ( ( 2 * $ pairs ) / 3 ) ; return $ cnt ; } $ a = array ( 1 , 2 , 2 , 2 , 2 ) ; $ n = sizeof ( $ a ) ; echo ( countTriangles ( $ a , $ n ) ) ; ? >


"Number of unique rectangles formed using N unit squares | height >= length is maintained ; Driver code"
Solution in php:

< ? php function countRect ( $ n ) { $ ans = 0 ; for ( $ length = 1 ; $ length <= sqrt ( $ n ) ; $ length ++ ) for ( $ height = $ length ; $ height * $ length <= $ n ; $ height ++ ) $ ans ++ ; return $ ans ; } $ n = 5 ; echo countRect ( $ n ) ; ? >


"Number of unmarked integers in a special sieve | PHP Program to determine the number of unmarked integers in a special sieve ; Driver Code"
Solution in php:

< ? php function countUnmarked ( $ N ) { if ( $ N % 2 == 0 ) return $ N / 2 ; else return $ N / 2 + 1 ; } $ N = 4 ; echo " Number ▁ of ▁ unmarked ▁ elements : ▁ " , countUnmarked ( $ N ) ; ? >


"Number of visible boxes after putting one inside another | return the minimum number of visible boxes ; New Queue of integers . ; sorting the array ; traversing the array ; checking if current element is greater than or equal to twice of front element ; Pushing each element of array ; Driver Code"
Solution in php:

< ? php function minimumBox ( $ arr , $ n ) { $ q = array ( ) ; sort ( $ arr ) ; array_push ( $ q , $ arr [ 0 ] ) ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ now = $ q [ 0 ] ; if ( $ arr [ $ i ] >= 2 * $ now ) array_pop ( $ q ) ; array_push ( $ q , $ arr [ $ i ] ) ; } return count ( $ q ) ; } $ arr = array ( 4 , 1 , 2 , 8 ) ; $ n = count ( $ arr ) ; echo minimumBox ( $ arr , $ n ) ; ? >


"Number of ways a convex polygon of n + 2 sides can split into triangles by connecting vertices | Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver code"
Solution in php:

< ? php function binomialCoeff ( $ n , $ k ) { $ res = 1 ; if ( $ k > $ n - $ k ) $ k = $ n - $ k ; for ( $ i = 0 ; $ i < $ k ; ++ $ i ) { $ res *= ( $ n - $ i ) ; $ res /= ( $ i + 1 ) ; } return $ res ; } function catalan ( $ n ) { $ c = binomialCoeff ( 2 * $ n , $ n ) ; return $ c / ( $ n + 1 ) ; } $ n = 3 ; echo catalan ( $ n ) ; ? >


"Number of ways in which the substring in range [ L , R ] can be formed using characters out of the range | Function to return the number of ways to form the sub - string ; Initialize a hash - table with 0 ; Iterate in the string and count the frequency of characters that do not lie in the range L and R ; Out of range characters ; Stores the final number of ways ; Iterate for the sub - string in the range L and R ; If exists then multiply the number of ways and decrement the frequency ; If does not exist the sub - string cannot be formed ; Return the answer ; Driver code"
Solution in php:


"Number of ways to arrange 2 * N persons on the two sides of a table with X and Y persons on opposite sides | Function to find factorial of a number ; Function to find nCr ; Function to find the number of ways to arrange 2 * N persons ; Driver code ; Function call"
Solution in php:

< ? php function factorial ( $ n ) { if ( $ n <= 1 ) return 1 ; return $ n * factorial ( $ n - 1 ) ; } function nCr ( $ n , $ r ) { return factorial ( $ n ) / ( factorial ( $ n - $ r ) * factorial ( $ r ) ) ; } function NumberOfWays ( $ n , $ x , $ y ) { return nCr ( 2 * $ n - $ x - $ y , $ n - $ x ) * factorial ( $ n ) * factorial ( $ n ) ; } $ n = 5 ; $ x = 4 ; $ y = 2 ; echo ( NumberOfWays ( $ n , $ x , $ y ) ) ; ? >


"Number of ways to arrange K different objects taking N objects at a time | PHP implementation of the approach ; Function to return n ! % p ; $res = 1 ; Initialize result ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; $x = $x % $p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now $y = $y >> 1 ; y = y / 2 ; Returns n ^ ( - 1 ) mod p ; Returns nCr % p using Fermat 's little theorem. ; Base case ; Fill factorial array so that we can find all factorial of r , n and n - r ; Function to return the number of ways to arrange K different objects taking N objects at a time ; Driver Code ; Function call"
Solution in php:

< ? php $ mod = ( 1e9 + 7 ) ; function factorial ( $ n , $ p ) { for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) $ res = ( $ res * $ i ) % $ p ; return $ res ; } function power ( $ x , $ y , $ p ) { while ( $ y > 0 ) { if ( ( $ y & 1 ) == 1 ) $ res = ( $ res * $ x ) % $ p ; $ x = ( $ x * $ x ) % $ p ; } return $ res ; } function modInverse ( $ n , $ p ) { return power ( $ n , $ p - 2 , $ p ) ; } function nCrModP ( $ n , $ r , $ p ) { if ( $ r == 0 ) return 1 ; $ fac = array ( ( int ) $ n + 1 ) ; $ fac [ 0 ] = 1 ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) $ fac [ $ i ] = $ fac [ $ i - 1 ] * $ i % $ p ; return ( $ fac [ ( int ) $ n ] * modInverse ( $ fac [ ( int ) $ r ] , $ p ) % $ p * modInverse ( $ fac [ ( int ) $ n - ( int ) $ r ] , $ p ) % $ p ) % $ p ; } function countArrangements ( $ n , $ k , $ p ) { return ( factorial ( $ n , $ p ) * nCrModP ( $ k , $ n , $ p ) ) % $ p ; } { $ N = 5 ; $ K = 8 ; echo ( countArrangements ( $ N , $ K , $ mod ) ) ; }


"Number of ways to arrange N items under given constraints | method returns number of ways with which items can be arranged ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; declare dp array to store result up to ith colored item ; variable to keep track of count of items considered till now ; loop over all different colors ; populate next value using current value and stated relation ; return value stored at last index ; Driver code"
Solution in php:


"Number of ways to form an array with distinct adjacent elements | Returns the total ways to form arrays such that every consecutive element is different and each element except the first and last can take values from 1 to M ; define the dp [ ] [ ] array ; if the first element is 1 ; there is only one way to place a 1 at the first index ; the value at first index needs to be 1 , thus there is no way to place a non - one integer ; if the first element was 1 then at index 1 , only non one integer can be placed thus there are M - 1 ways to place a non one integer at index 2 and 0 ways to place a 1 at the 2 nd index ; Else there is one way to place a one at index 2 and if a non one needs to be placed here , there are ( M - 2 ) options , i . e neither the element at this index should be 1 , neither should it be equal to the previous element ; Build the dp array in bottom up manner ; f ( i , one ) = f ( i - 1 , non - one ) ; f ( i , non - one ) = f ( i - 1 , one ) * ( M - 1 ) + f ( i - 1 , non - one ) * ( M - 2 ) ; last element needs to be one , so return dp [ n - 1 ] [ 0 ] ; Driver Code"
Solution in php:


"Number of ways to represent a number as sum of k fibonacci numbers | To store fibonacci numbers 42 second number in fibonacci series largest possible integer ; Function to generate fibonacci series ; Recursive function to return the number of ways ; base condition ; for recursive function call ; Driver code"
Solution in php:

< ? php $ fib = array_fill ( 0 , 43 , 0 ) ; function fibonacci ( ) { global $ fib ; $ fib [ 0 ] = 1 ; $ fib [ 1 ] = 2 ; for ( $ i = 2 ; $ i < 43 ; $ i ++ ) $ fib [ $ i ] = $ fib [ $ i - 1 ] + $ fib [ $ i - 2 ] ; } function rec ( $ x , $ y , $ last ) { global $ fib ; if ( $ y == 0 ) { if ( $ x == 0 ) return 1 ; return 0 ; } $ sum = 0 ; for ( $ i = $ last ; $ i >= 0 and $ fib [ $ i ] * $ y >= $ x ; $ i -- ) { if ( $ fib [ $ i ] > $ x ) continue ; $ sum += rec ( $ x - $ fib [ $ i ] , $ y - 1 , $ i ) ; } return $ sum ; } fibonacci ( ) ; $ n = 13 ; $ k = 3 ; echo " Possible ▁ ways ▁ are : ▁ " . rec ( $ n , $ k , 42 ) ; ? >


"Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes | Function to find number of ways ; initialise result that store No . of swaps required ; Traverse both strings and check the bits as explained ; calculate result ; Driver code"
Solution in php:


"Number which has the maximum number of distinct prime factors in the range M to N | Function to return the maximum number ; array to store the number of distinct primes ; true if index ' i ' is a prime ; initializing the number of factors to 0 and ; Used in Sieve ; condition works only when ' i ' is prime , hence for factors of all prime number , the prime status is changed to false ; Number is prime ; number of factor of a prime number is 1 ; incrementing factorCount all the factors of i ; and changing prime status to false ; Initialize the max and num ; Gets the maximum number ; Gets the maximum number ; Driver code ; Calling function"
Solution in php:

< ? php function maximumNumberDistinctPrimeRange ( $ m , $ n ) { $ factorCount = array ( ) ; $ prime = array ( ) ; for ( $ i = 0 ; $ i <= $ n ; $ i ++ ) { $ factorCount [ $ i ] = 0 ; $ prime [ $ i ] = true ; } for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) { if ( $ prime [ $ i ] == true ) { $ factorCount [ $ i ] = 1 ; for ( $ j = $ i * 2 ; $ j <= $ n ; $ j += $ i ) { $ factorCount [ $ j ] ++ ; $ prime [ $ j ] = false ; } } } $ max = $ factorCount [ $ m ] ; $ num = $ m ; for ( $ i = $ m ; $ i <= $ n ; $ i ++ ) { if ( $ factorCount [ $ i ] > $ max ) { $ max = $ factorCount [ $ i ] ; $ num = $ i ; } } return $ num ; } $ m = 4 ; $ n = 6 ; echo maximumNumberDistinctPrimeRange ( $ m , $ n ) ; ? >


"Number whose XOR sum with given array is a given number k | This function returns the number to be inserted in the given array ; initialise the answer with k ; XOR of all elements in the array ; Driver Code"
Solution in php:

 < ? php function findEletobeInserted ( $ A , $ n , $ k ) { $ ans = $ k ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ ans ^= $ A [ $ i ] ; return $ ans ; } $ A = array ( 1 , 2 , 3 , 4 , 5 ) ; $ n = count ( $ A ) ; $ k = 10 ; echo findEletobeInserted ( $ A , $ n , $ k ) ; echo " ▁ has ▁ to ▁ be ▁ inserted " ; echo " ▁ in ▁ the ▁ given ▁ array ▁ to ▁ make ▁ xor ▁ sum ▁ of ▁ " ; echo $ k , "
 " ; ? >


"Number whose sum of XOR with given array range is maximum | PHP program to find smallest integer X such that sum of its XOR with range is maximum . ; Function to make prefix array which counts 1 's of each bit up to that number ; Making a prefix array which sums number of 1 's up to  that position ; If j - th bit of a number is set then add one to previously counted 1 's ; Function to find X ; Initially taking maximum value all bits 1 ; Iterating over each bit ; get 1 ' s ▁ at ▁ ith ▁ bit ▁ between ▁ the ▁ ▁ range ▁ L - R ▁ by ▁ subtracting ▁ 1' s till Rth number - 1 's till L-1th number ; If 1 ' s ▁ are ▁ more ▁ than ▁ or ▁ equal ▁ ▁ to ▁ 0' s then unset the ith bit from answer ; Set ith bit to 0 by doing Xor with 1 ; Driver Code"
Solution in php:


"Number with even sum of digits | Function to find kth good number . ; Find the last digit of n . ; If last digit is between 0 to 4 then return 2 * n . ; If last digit is between 5 to 9 then return 2 * n + 1. ; Driver code"
Solution in php:

< ? php function findKthGoodNo ( $ n ) { $ lastDig = $ n % 10 ; if ( $ lastDig >= 0 && $ lastDig <= 4 ) return $ n << 1 ; else return ( $ n << 1 ) + 1 ; } $ n = 10 ; echo ( findKthGoodNo ( $ n ) ) ; ? >


"Number with set bits only between L | Function to return the integer with all the bits set in range L - R ; Driver Code"
Solution in php:

< ? php function setbitsfromLtoR ( $ L , $ R ) { return ( 1 << ( $ R + 1 ) ) - ( 1 << $ L ) ; } $ L = 2 ; $ R = 5 ; echo setbitsfromLtoR ( $ L , $ R ) ; ? >


"Number with set bits only between L | Function to return the integer with all the bits set in range L - R ; iterate from L to R and add all powers of 2 ; Driver Code"
Solution in php:

< ? php function getInteger ( $ L , $ R ) { $ number = 0 ; for ( $ i = $ L ; $ i <= $ R ; $ i ++ ) $ number += pow ( 2 , $ i ) ; return $ number ; } $ L = 2 ; $ R = 5 ; echo getInteger ( $ L , $ R ) ; ? >


"Numbers having Unique ( or Distinct ) digits | Function to print unique digit numbers in range from l to r . ; Start traversing the numbers ; Find digits and maintain its hash ; if a digit occurs more than 1 time then break ; num will be 0 only when above loop doesn 't get break that  means the number is unique  so print it. ; Driver code"
Solution in php:

< ? php function printUnique ( $ l , $ r ) { for ( $ i = $ l ; $ i <= $ r ; $ i ++ ) { $ num = $ i ; $ visited = ( false ) ; while ( $ num ) { if ( $ visited [ $ num % 10 ] ) $ visited [ $ num % 10 ] = true ; $ num = ( int ) $ num / 10 ; } if ( $ num == 0 ) echo $ i , " ▁ " ; } } $ l = 1 ; $ r = 20 ; printUnique ( $ l , $ r ) ; ? >


"Numbers having difference with digit sum more than s | function for digit sum ; function to calculate count of integer s . t . integer - digSum > s ; if n < s no integer possible ; iterate for s range and then calculate total count of such integer if starting integer is found ; if no integer found return 0 ; Driver Code"
Solution in php:

< ? php function digitSum ( $ n ) { $ digSum = 0 ; while ( $ n ) { $ digSum += $ n % 10 ; $ n /= 10 ; } return $ digSum ; } function countInteger ( $ n , $ s ) { if ( $ n < $ s ) return 0 ; for ( $ i = $ s ; $ i <= min ( $ n , $ s + 163 ) ; $ i ++ ) if ( ( $ i - digitSum ( $ i ) ) > $ s ) return ( $ n - $ i + 1 ) ; return 0 ; } $ n = 1000 ; $ s = 100 ; echo countInteger ( $ n , $ s ) ; ? >


"Numbers less than N that are perfect cubes and the sum of their digits reduced to a single digit is 1 | Function that returns true if the eventual digit sum of number nm is 1 ; if reminder will 1 then eventual sum is 1 ; Function to print the required numbers less than n ; If it is the required perfect cube ; Driver code"
Solution in php:

< ? php function isDigitSumOne ( $ nm ) { if ( $ nm % 9 == 1 ) return true ; else return false ; } function printValidNums ( $ n ) { $ cbrt_n = ceil ( pow ( $ n , 1 / 3 ) ) ; for ( $ i = 1 ; $ i <= $ cbrt_n ; $ i ++ ) { $ cube = pow ( $ i , 3 ) ; if ( $ cube >= 1 && $ cube <= $ n && isDigitSumOne ( $ cube ) ) echo $ cube , " ▁ " ; } } $ n = 1000 ; printValidNums ( $ n ) ; ? >


"Numbers less than N which are product of exactly two distinct prime numbers | Function to check whether a number is a PerfectSquare or not ; Function to check if a number is a product of exactly two distinct primes ; Function to find numbers that are product of exactly two distinct prime numbers . ; Vector to store such numbers ; insert in the vector ; Print all numbers till n from the vector ; Driver Code"
Solution in php:

< ? php function isPerfectSquare ( $ x ) { $ sr = sqrt ( $ x ) ; return ( ( $ sr - floor ( $ sr ) ) == 0 ) ; } function isProduct ( $ num ) { $ cnt = 0 ; for ( $ i = 2 ; $ cnt < 2 && $ i * $ i <= $ num ; ++ $ i ) { while ( $ num % $ i == 0 ) { $ num /= $ i ; ++ $ cnt ; } } if ( $ num > 1 ) ++ $ cnt ; return $ cnt == 2 ; } function findNumbers ( $ N ) { $ vec = array ( ) ; for ( $ i = 1 ; $ i <= $ N ; $ i ++ ) { if ( isProduct ( $ i ) && ! isPerfectSquare ( $ i ) ) { array_push ( $ vec , $ i ) ; } } for ( $ i = 0 ; $ i < sizeof ( $ vec ) ; $ i ++ ) { echo $ vec [ $ i ] . " " ; } } $ N = 30 ; findNumbers ( $ N ) ;


"Numbers that are not divisible by any number in the range [ 2 , 10 ] | Function to return the count of numbers from 1 to N which are not divisible by any number in the range [ 2 , 10 ] ; Driver code"
Solution in php:


"Numbers whose bitwise OR and sum with N are equal | Function to find total 0 bit in a number ; Function to find Count of non - negative numbers less than or equal to N , whose bitwise OR and SUM with N are equal . ; count number of zero bit in N ; power of 2 to count ; Driver code"
Solution in php:

< ? php function CountZeroBit ( $ n ) { $ count = 0 ; while ( $ n ) { if ( ! ( $ n & 1 ) ) $ count ++ ; $ n >>= 1 ; } return $ count ; } function CountORandSumEqual ( $ N ) { $ count = CountZeroBit ( $ N ) ; return ( 1 << $ count ) ; } $ N = 10 ; echo CountORandSumEqual ( $ N ) ; ? >


"Numbers whose factorials end with n zeros | Function to calculate trailing zeros ; binary search for first number with n trailing zeros ; Print all numbers after low with n trailing zeros . ; Print result ; Driver code"
Solution in php:

< ? php function trailingZeroes ( $ n ) { $ cnt = 0 ; while ( $ n > 0 ) { $ n = intval ( $ n / 5 ) ; $ cnt += $ n ; } return $ cnt ; } function binarySearch ( $ n ) { $ low = 0 ; while ( $ low < $ high ) { $ mid = intval ( ( $ low + $ high ) / 2 ) ; $ count = trailingZeroes ( $ mid ) ; if ( $ count < $ n ) $ low = $ mid + 1 ; else $ high = $ mid ; } $ result = array ( ) ; while ( trailingZeroes ( $ low ) == $ n ) { array_push ( $ result , $ low ) ; $ low ++ ; } for ( $ i = 0 ; $ i < sizeof ( $ result ) ; $ i ++ ) echo $ result [ $ i ] . " ▁ " ; } $ n = 2 ; binarySearch ( $ n ) ; ? >


"Numbers with exactly 3 divisors | Generates all primes upto n and prints their squares ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; print squares of primes upto n . ; Driver Code"
Solution in php:

 < ? php function numbersWith3Divisors ( $ n ) { $ prime = array_fill ( 0 , $ n + 1 , true ) ; $ prime [ 0 ] = $ 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 ; } } echo " Numbers ▁ with ▁ 3 ▁ divisors ▁ :
 " ; for ( $ i = 0 ; $ i * $ i <= $ n ; $ i ++ ) if ( $ prime [ $ i ] ) echo $ i * $ i . " ▁ " ; } $ n = 96 ; numbersWith3Divisors ( $ n ) ; ? >


"Occurrences of a pattern in binary representation of a number | Function to return the count of occurrence of pat in binary representation of n ; To store decimal value of the pattern ; To store a number that has all ones in its binary representation and length of ones equal to length of the pattern ; Find values of $pattern_int and $all_ones ; If the pattern occurs in the last digits of $n ; Right shift $n by 1 bit ; Driver code"
Solution in php:

< ? php function countPattern ( $ n , $ pat ) { $ pattern_int = 0 ; $ power_two = 1 ; $ all_ones = 0 ; for ( $ i = strlen ( $ pat ) - 1 ; $ i >= 0 ; $ i -- ) { $ current_bit = $ pat [ $ i ] - '0' ; $ pattern_int += ( $ power_two * $ current_bit ) ; $ all_ones = $ all_ones + $ power_two ; $ power_two = $ power_two * 2 ; } $ count = 0 ; while ( $ n && $ n >= $ pattern_int ) { if ( ( $ n & $ all_ones ) == $ pattern_int ) { $ count ++ ; } $ n = $ n >> 1 ; } return $ count ; } $ n = 500 ; $ pat = "10" ; echo countPattern ( $ n , $ pat ) ; ? >


"Octahedral Number | Function to find octahedral number ; Formula to calculate nth octahedral number and return it into main function . ; Drivers Code ; print result"
Solution in php:

< ? php function octahedral_num ( $ n ) { return $ n * ( 2 * $ n * $ n + 1 ) / 3 ; } $ n = 5 ; echo $ n , " th ▁ Octahedral ▁ number : ▁ " ; echo octahedral_num ( $ n ) ; ? >


"Odd numbers in N | Function to get no of set bits in binary representation of positive integer n ; Count number of 1 's in binary  representation of n. ; Number of odd numbers in n - th row is 2 raised to power the count . ; Driver code"
Solution in php:

< ? php function countSetBits ( $ n ) { $ count = 0 ; while ( $ n ) { $ count += $ n & 1 ; $ n >>= 1 ; } return $ count ; } function countOfOddsPascal ( $ n ) { $ c = countSetBits ( $ n ) ; return pow ( 2 , $ c ) ; } $ n = 20 ; echo countOfOddsPascal ( $ n ) ; ? >


"Odious number | Function to get no of set bits in binary ; Check if number is odious or not ; Driver Code"
Solution in php:

< ? php function countSetBits ( $ n ) { $ count = 0 ; while ( $ n ) { $ n &= ( $ n - 1 ) ; $ count ++ ; } return $ count ; } function checkOdious ( $ n ) { return ( countSetBits ( $ n ) % 2 == 1 ) ; } $ num = 32 ; if ( checkOdious ( $ num ) ) echo " Yes " ; else echo " No " ; ? >


"Optimal Strategy for a Game | DP | Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Create a table to store solutions of subproblems ; Fill table using above recursive formula . Note that the table is filled in diagonal fashion ( similar to http : goo . gl / PQqoS ) , from diagonal elements to table [ 0 ] [ n - 1 ] which is the result . ; Here x is value of F ( i + 2 , j ) , y is F ( i + 1 , j - 1 ) and z is F ( i , j - 2 ) in above recursive formula ; Driver Code"
Solution in php:

< ? php function optimalStrategyOfGame ( $ arr , $ n ) { $ table = array_fill ( 0 , $ n , array_fill ( 0 , $ n , 0 ) ) ; for ( $ gap = 0 ; $ gap < $ n ; ++ $ gap ) { for ( $ i = 0 , $ j = $ gap ; $ j < $ n ; ++ $ i , ++ $ j ) { $ x = ( ( $ i + 2 ) <= $ j ) ? $ table [ $ i + 2 ] [ $ j ] : 0 ; $ y = ( ( $ i + 1 ) <= ( $ j - 1 ) ) ? $ table [ $ i + 1 ] [ $ j - 1 ] : 0 ; $ z = ( $ i <= ( $ j - 2 ) ) ? $ table [ $ i ] [ $ j - 2 ] : 0 ; $ table [ $ i ] [ $ j ] = max ( $ arr [ $ i ] + min ( $ x , $ y ) , $ arr [ $ j ] + min ( $ y , $ z ) ) ; } } return $ table [ 0 ] [ $ n - 1 ] ; } $ arr1 = array ( 8 , 15 , 3 , 7 ) ; $ n = count ( $ arr1 ) ; print ( optimalStrategyOfGame ( $ arr1 , $ n ) . " " ) ; $ arr2 = array ( 2 , 2 , 2 , 2 ) ; $ n = count ( $ arr2 ) ; print ( optimalStrategyOfGame ( $ arr2 , $ n ) . " " ) ; $ arr3 = array ( 20 , 30 , 2 , 2 , 2 , 10 ) ; $ n = count ( $ arr3 ) ; print ( optimalStrategyOfGame ( $ arr3 , $ n ) . " " ) ; ? >


"Optimized Euler Totient Function for Multiple Evaluations | PHP program to efficiently compute values of euler totient function for multiple inputs . ; Stores prime numbers upto MAX - 1 values ; Finds prime numbers upto MAX - 1 and stores them in vector p ; if prime [ i ] is not marked before ; fill vector for every newly encountered prime ; run this loop till square root of MAX , mark the index i * j as not prime ; function to find totient of n ; this loop runs sqrt ( n / ln ( n ) ) times ; subtract multiples of p [ i ] from r ; Remove all occurrences of p [ i ] in n ; when n has prime factor greater than sqrt ( n ) ; preprocess all prime numbers upto 10 ^ 5"
Solution in php:


"Optimized Naive Algorithm for Pattern Searching | A modified Naive Pettern Searching algorithn that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver Code"
Solution in php:

 < ? php function search ( $ pat , $ txt ) { $ M = strlen ( $ pat ) ; $ N = strlen ( $ txt ) ; $ i = 0 ; while ( $ i <= $ N - $ M ) { $ j ; for ( $ j = 0 ; $ j < $ M ; $ j ++ ) if ( $ txt [ $ i + $ j ] != $ pat [ $ j ] ) break ; if ( $ j == $ M ) { echo ( " Pattern ▁ found ▁ at ▁ index ▁ $ i " . "
 " ) ; $ i = $ i + $ M ; } else if ( $ j == 0 ) $ i = $ i + 1 ; else $ i = $ i + $ j ; } } $ txt = " ABCEABCDABCEABCD " ; $ pat = " ABCD " ; search ( $ pat , $ txt ) ; ? >


"Overall percentage change from successive changes | PHP implementation of above approach ; Calculate successive change of 1 st 2 change ; Calculate successive change for rest of the value ; Driver code ; Calling function"
Solution in php:

< ? php function successiveChange ( $ arr , $ N ) { $ result = 0 ; $ var1 = $ arr [ 0 ] ; $ var2 = $ arr [ 1 ] ; $ result = $ var1 + $ var2 + ( ( $ var1 * $ var2 ) / 100 ) ; for ( $ i = 2 ; $ i < $ N ; $ i ++ ) $ result = $ result + $ arr [ $ i ] + ( ( $ result * $ arr [ $ i ] ) / 100 ) ; return $ result ; } $ arr = array ( 10 , 20 , 30 , 10 ) ; $ N = count ( $ arr ) ; $ result = successiveChange ( $ arr , $ N ) ; echo " Percentage ▁ change ▁ is ▁ = ▁ " , $ result , " ▁ % " ; ? >


"P | function to check if number n is a P - smooth number or not ; prime factorise it by 2 ; if the number is divisible by 2 ; check for all the possible numbers that can divide it ; prime factorize it by i ; stores the maximum if maximum and i , if i divides the number ; if n at the end is a prime number , then it a divisor itself ; Driver Code"
Solution in php:

< ? php function check ( $ n , $ p ) { $ maximum = -1 ; while ( ! ( $ n % 2 ) ) { $ maximum = max ( $ maximum , 2 ) ; $ n = $ n / 2 ; } for ( $ i = 3 ; $ i <= sqrt ( $ n ) ; $ i += 2 ) { while ( $ n % $ i == 0 ) { $ maximum = max ( $ maximum , $ i ) ; $ n = $ n / $ i ; } } if ( $ n > 2 ) $ maximum = max ( $ maximum , $ n ) ; return ( $ maximum <= $ p ) ; } $ n = 24 ; $ p = 7 ; if ( check ( $ n , $ p ) ) echo ( " yes " ) ; else echo ( " no " ) ; ? >


"Padovan Sequence | Function to calculate padovan number P ( n ) ; 0 th , 1 st and 2 nd number of the series are 1 ; Driver Code"
Solution in php:

< ? php function pad ( $ n ) { $ pPrevPrev = 1 ; $ pPrev = 1 ; $ pCurr = 1 ; $ pNext = 1 ; for ( $ i = 3 ; $ i <= $ n ; $ i ++ ) { $ pNext = $ pPrevPrev + $ pPrev ; $ pPrevPrev = $ pPrev ; $ pPrev = $ pCurr ; $ pCurr = $ pNext ; } return $ pNext ; } $ n = 12 ; echo ( pad ( $ n ) ) ; ? >


"Painting Fence Algorithm | Returns count of ways to color k posts using k colors ; There are k ways to color first post ; There are 0 ways for single post to violate ( same color_ and k ways to not violate ( different color ) ; Fill for 2 posts onwards ; Current same is same as previous diff ; We always have k - 1 choices for next post ; Total choices till i . ; Driver code"
Solution in php:

 < ? php function countWays ( $ n , $ k ) { $ total = $ k ; $ mod = 1000000007 ; $ same = 0 ; $ diff = $ k ; for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) { $ same = $ diff ; $ diff = $ total * ( $ k - 1 ) ; $ diff = $ diff % $ mod ; $ total = ( $ same + $ diff ) % $ mod ; } return $ total ; } $ n = 3 ; $ k = 2 ; echo countWays ( $ n , $ k ) . "
 " ; ? >


"Pair with given product | Set 1 ( Find if any pair exists ) | Returns true if there is a pair in arr [ 0. . n - 1 ] with product equal to x . ; Consider all possible pairs and check for every pair . ; Driver code"
Solution in php:

 < ? php function isProduct ( $ arr , $ n , $ x ) { for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) for ( $ j = $ i + 1 ; $ i < $ n ; $ i ++ ) if ( $ arr [ $ i ] * $ arr [ $ j ] == $ x ) return true ; return false ; } $ arr = array ( 10 , 20 , 9 , 40 ) ; $ x = 400 ; $ n = count ( $ arr ) ; if ( isProduct ( $ arr , $ n , $ x ) ) echo " Yes
 " ; else echo " No
 " ; $ x = 190 ; if ( isProduct ( $ arr , $ n , $ x ) ) echo " Yes
 " ; else echo " No
 " ; ? >


"Pair with maximum GCD from two arrays | Find the maximum GCD pair with maximum sum ; array to keep a count of existing elements ; first [ i ] and second [ i ] are going to store maximum multiples of i in a [ ] and b [ ] respectively . ; traverse through the first array to mark the elements in cnt ; Find maximum multiple of every number in first array ; Find maximum multiple of every number in second array We re - initialise cnt [ ] and traverse through the second array to mark the elements in cnt ; if the multiple is present in the second array then store the max of number or the pre - existing element ; traverse for every elements and checks the maximum N that is present in both the arrays ; Driver code ; Maximum possible value of elements in both arrays ."
Solution in php:


"Pairs from an array that satisfy the given condition | Function to return the number of set bits in n ; Function to return the count of required pairs ; Set bits for first element of the pair ; Set bits for second element of the pair ; Set bits of the resultant number which is the XOR of both the elements of the pair ; If the condition is satisfied ; Increment the count ; Return the total count ; Driver code"
Solution in php:

< ? php function setBits ( $ n ) { $ count = 0 ; while ( $ n ) { $ n = $ n & ( $ n - 1 ) ; $ count ++ ; } return $ count ; } function countPairs ( & $ a , $ n ) { $ count = 0 ; for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) { $ setbits_x = setBits ( $ a [ $ i ] ) ; for ( $ j = $ i + 1 ; $ j < $ n ; $ j ++ ) { $ setbits_y = setBits ( $ a [ $ j ] ) ; $ setbits_xor_xy = setBits ( $ a [ $ i ] ^ $ a [ $ j ] ) ; if ( $ setbits_x + $ setbits_y == $ setbits_xor_xy ) $ count ++ ; } } return $ count ; } $ a = array ( 2 , 3 , 4 , 5 , 6 ) ; $ n = sizeof ( $ a ) / sizeof ( $ a [ 0 ] ) ; echo countPairs ( $ a , $ n ) ; ? >


"Pairs of strings which on concatenating contains each character of " string " | PHP implementation of the approach ; Function to return the bitmask for the string ; Function to return the count of pairs ; bitMask [ i ] will store the count of strings from the array whose bitmask is i ; To store the count of pairs ; MAX - 1 = 63 i . e . 111111 in binary ; arr [ i ] cannot make s pair with itself i . e . ( arr [ i ] , arr [ i ] ) ; Driver code"
Solution in php:

< ? php $ MAX = 64 ; function getBitmask ( $ s ) { $ temp = 0 ; for ( $ j = 0 ; $ j < strlen ( $ s ) ; $ j ++ ) { if ( $ s [ $ j ] == ' s ' ) { $ temp = $ temp | ( 1 ) ; } else if ( $ s [ $ j ] == ' t ' ) { $ temp = $ temp | ( 2 ) ; } else if ( $ s [ $ j ] == ' r ' ) { $ temp = $ temp | ( 4 ) ; } else if ( $ s [ $ j ] == ' i ' ) { $ temp = $ temp | ( 8 ) ; } else if ( $ s [ $ j ] == ' n ' ) { $ temp = $ temp | ( 16 ) ; } else if ( $ s [ $ j ] == ' g ' ) { $ temp = $ temp | ( 32 ) ; } } return $ temp ; } function countPairs ( $ arr , $ n ) { $ bitMask = array_fill ( 0 , $ GLOBALS [ ' MAX ' ] , 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ bitMask [ getBitmask ( $ arr [ $ i ] ) ] ++ ; $ cnt = 0 ; for ( $ i = 0 ; $ i < $ GLOBALS [ ' MAX ' ] ; $ i ++ ) { for ( $ j = $ i ; $ j < $ GLOBALS [ ' MAX ' ] ; $ j ++ ) { if ( ( $ i $ j ) == ( $ GLOBALS [ ' MAX ' ] - 1 ) ) { if ( $ i == $ j ) $ cnt += floor ( ( $ bitMask [ $ i ] * $ bitMask [ $ i ] - 1 ) / 2 ) ; else $ cnt += ( $ bitMask [ $ i ] * $ bitMask [ $ j ] ) ; } } } return $ cnt ; } $ arr = array ( " strrr " , " string " , " gstrin " ) ; $ n = count ( $ arr ) ; echo countPairs ( $ arr , $ n ) ; ? >


"Pairs such that one is a power multiple of other | function to count the required pairs ; sort the given array ; for each A [ i ] traverse rest array ; count Aj such that Ai * k ^ x = Aj ; increase x till Ai * k ^ x <= largest element ; Driver Code"
Solution in php:


"Pairs with Difference less than K | Function to count pairs ; Driver code"
Solution in php:


"Pairs with Difference less than K | PHP code to find count of Pairs with difference less than K . ; to sort the array . ; Keep incrementing result while subsequent elements are within limits . ; Driver code"
Solution in php:


"Pairs with GCD equal to one in the given range | Function to print all pairs ; check if even ; We can print all adjacent pairs for ( int i = l ; i < r ; i += 2 ) { cout << " { " << i << " , ▁ " << i + 1 << " } , ▁ " ; } ; Driver Code"
Solution in php:

< ? php function checkPairs ( $ l , $ r ) { if ( ( $ l - $ r ) % 2 == 0 ) return false ; return true ; } $ l = 1 ; $ r = 8 ; if ( checkPairs ( $ l , $ r ) ) echo ( " Yes " ) ; else echo ( " No " ) ; ? >


"Palindrome Partitioning | DP | Returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; Get the length of the string ; Create two arrays to build the solution in bottom up manner C [ i ] [ j ] = Minimum number of cuts needed for palindrome partitioning of substring str [ i . . j ] P [ i ] [ j ] = true if substring str [ i . . j ] is palindrome , else false Note that C [ i ] [ j ] is 0 if P [ i ] [ j ] is true ; Every substring of length 1 is a palindrome ; L is substring length . Build the solution in a bottom - up manner by considering all substrings of length starting from 2 to n . The loop structure is same as Matrix Chain Multiplication problem ( See https : www . geeksforgeeks . org / matrix - chain - multiplication - dp - 8 / ) ; For substring of length L , set different possible starting indexes ; Set ending index ; If L is 2 , then we just need to compare two characters . Else need to check two corner characters and value of P [ i + 1 ] [ j - 1 ] ; IF str [ i . . j ] is palindrome , then C [ i ] [ j ] is 0 ; Make a cut at every possible location starting from i to j , and get the minimum cost cut . ; Return the min cut value for complete string . i . e . , str [ 0. . n - 1 ] ; Driver program to test the above function"
Solution in php:

< ? php function minPalPartion ( $ str ) { $ n = strlen ( $ str ) ; $ C = array_fill ( 0 , $ n , array_fill ( 0 , $ n , NULL ) ) ; $ P = array_fill ( false , $ n , array_fill ( false , $ n , NULL ) ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ P [ $ i ] [ $ i ] = true ; $ C [ $ i ] [ $ i ] = 0 ; } for ( $ L = 2 ; $ L <= $ n ; $ L ++ ) { for ( $ i = 0 ; $ i < $ n - $ L + 1 ; $ i ++ ) { $ j = $ i + $ L - 1 ; if ( $ L == 2 ) $ P [ $ i ] [ $ j ] = ( $ str [ $ i ] == $ str [ $ j ] ) ; else $ P [ $ i ] [ $ j ] = ( $ str [ $ i ] == $ str [ $ j ] ) && $ P [ $ i + 1 ] [ $ j - 1 ] ; if ( $ P [ $ i ] [ $ j ] == true ) $ C [ $ i ] [ $ j ] = 0 ; else { $ C [ $ i ] [ $ j ] = PHP_INT_MAX ; for ( $ k = $ i ; $ k <= $ j - 1 ; $ k ++ ) $ C [ $ i ] [ $ j ] = min ( $ C [ $ i ] [ $ j ] , $ C [ $ i ] [ $ k ] + $ C [ $ k + 1 ] [ $ j ] + 1 ) ; } } } return $ C [ 0 ] [ $ n - 1 ] ; } $ str = " ababbbabbababa " ; echo " Min ▁ cuts ▁ needed ▁ for ▁ Palindrome ▁ Partitioning ▁ is ▁ " . minPalPartion ( $ str ) ; return 0 ; ? >


"Palindromic Primes | A function that returns true only if num contains one digit ; comparison operation is faster than division operation . So using following instead of " return ▁ num ▁ / ▁ 10 ▁ = = ▁ 0 ; " ; A recursive function to find out whether num is palindrome or not . Initially , dupNum contains address of a copy of num . ; Base case ( needed for recursion termination ) : This statement / mainly compares the first digit with the last digit ; This is the key line in this method . Note that all recursive / calls have a separate copy of num , but they all share same copy of dupNum . We divide num while moving up the recursion tree ; The following statements are executed when we move up the recursion call tree ; At this point , if num % 10 contains ith digit from beginning , then ( dupNum ) % 10 contains ith digit from end ; The main function that uses recursive function isPalUtil ( ) to find out whether num is palindrome or not ; If num is negative , make it positive ; Create a separate copy of num , so that modifications made to address dupNum don 't change the input number.  $dupNum = $num; dupNum = num ; Function to generate all primes and checking whether number is palindromic or not ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Print all palindromic prime numbers ; checking whether the given number is prime palindromic or not ; Driver Code"
Solution in php:

 < ? php function oneDigit ( $ num ) { return ( $ num >= 0 && $ num < 10 ) ; } function isPalUtil ( $ num , $ dupNum ) { if ( oneDigit ( $ num ) ) return ( $ num == ( $ dupNum ) % 10 ) ; if ( ! isPalUtil ( ( int ) ( $ num / 10 ) , $ dupNum ) ) return false ; $ dupNum = ( int ) ( $ dupNum / 10 ) ; return ( $ num % 10 == ( $ dupNum ) % 10 ) ; } function isPal ( $ num ) { if ( $ num < 0 ) $ num = - $ num ; return isPalUtil ( $ num , $ dupNum ) ; } function printPalPrimesLessThanN ( $ n ) { $ prime = array_fill ( 0 , $ n + 1 , true ) ; for ( $ p = 2 ; $ p * $ p <= $ n ; $ p ++ ) { if ( $ prime [ $ p ] ) { for ( $ i = $ p * 2 ; $ i <= $ n ; $ i += $ p ) { $ prime [ $ i ] = false ; } } } for ( $ p = 2 ; $ p <= $ n ; $ p ++ ) { if ( $ prime [ $ p ] && isPal ( $ p ) ) { print ( $ p . " " ) ; } } } $ n = 100 ; print ( " Palindromic ▁ primes ▁ smaller ▁ " . " than ▁ or ▁ equal ▁ to ▁ " . $ n . " ▁ are ▁ :
 " ) ; printPalPrimesLessThanN ( $ n ) ; ? >


"Panalphabetic window in a string | Return if given string contain panalphabetic window . ; traversing the string ; if character of string is equal to ch , increment ch . ; if all characters are found , return true . ; Driver Code"
Solution in php:

< ? php function isPanalphabeticWindow ( $ s , $ n ) { $ ch = ' a ' ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ s [ $ i ] == $ ch ) $ ch ++ ; if ( $ ch == ' z ' ) return true ; } return false ; } $ s = " abujm ▁ zvcd ▁ acefc ▁ deghf ▁ gijkle " . " ▁ m ▁ n ▁ o ▁ p ▁ pafqrstuvwxyzfap " ; $ n = strlen ( $ s ) ; if ( isPanalphabeticWindow ( $ s , $ n ) ) echo ( " YES " ) ; else echo ( " NO " ) ; ? >


"Pancake sorting | Reverses arr [ 0. . i ] ; Returns index of the maximum element in arr [ 0. . n - 1 ] ; The main function that sorts given array using flip operations ; Start from the complete array and one by one reduce current size by one ; Find index of the maximum element in arr [ 0. . curr_size - 1 ] ; Move the maximum element to end of current array if it 's not already  at the end ; To move at the end , first move maximum number to beginning ; Now move the maximum number to end by reversing current array ; A utility function to print n array of size n ; Driver code"
Solution in php:

 < ? php function flip ( & $ arr , $ i ) { $ start = 0 ; while ( $ start < $ i ) { $ temp = $ arr [ $ start ] ; $ arr [ $ start ] = $ arr [ $ i ] ; $ arr [ $ i ] = $ temp ; $ start ++ ; $ i -- ; } } function findMax ( $ arr , $ n ) { $ mi = 0 ; for ( $ i = 0 ; $ i < $ n ; ++ $ i ) if ( $ arr [ $ i ] > $ arr [ $ mi ] ) $ mi = $ i ; return $ mi ; } function pancakeSort ( & $ arr , $ n ) { for ( $ curr_size = $ n ; $ curr_size > 1 ; -- $ curr_size ) { $ mi = findMax ( $ arr , $ curr_size ) ; if ( $ mi != $ curr_size - 1 ) { flip ( $ arr , $ mi ) ; flip ( $ arr , $ curr_size -1 ) ; } } } function printArray ( $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n ; ++ $ i ) print ( $ arr [ $ i ] . " ▁ " ) ; } $ arr = array ( 23 , 10 , 20 , 11 , 12 , 6 , 7 ) ; $ n = count ( $ arr ) ; pancakeSort ( $ arr , $ n ) ; echo ( " Sorted ▁ Array ▁
 " ) ; printArray ( $ arr , $ n ) ; return 0 ; ? >


"Pandigital Product | To check the string formed from multiplicand , multiplier and product is pandigital ; calculate the multiplicand , multiplier , and product eligible for pandigital ; Driver Code"
Solution in php:

< ? php function isPandigital ( $ str ) { if ( strlen ( $ str ) != 9 ) return false ; $ x = str_split ( $ str ) ; sort ( $ x ) ; $ x = implode ( $ x ) ; return strcmp ( $ x , "123456789" ) ; } function PandigitalProduct_1_9 ( $ n ) { for ( $ i = 1 ; $ i * $ i <= $ n ; $ i ++ ) if ( $ n % $ i == 0 && isPandigital ( strval ( $ n ) . strval ( $ i ) . strval ( ( int ) ( $ n / $ i ) ) ) ) return true ; return false ; } $ n = 6050 ; if ( PandigitalProduct_1_9 ( $ n ) ) echo " yes " ; else echo " no " ; ? >


"Partition an array such into maximum increasing segments | Returns the maximum number of sorted subarrays in a valid partition ; Find minimum value from right for every index ; Finding the shortest prefix such that all the elements in the prefix are less than or equal to the elements in the rest of the array . ; if current max is less than the right prefix min , we increase number of partitions . ; Driver code ; Find minimum value from right for every index"
Solution in php:

 < ? php function sorted_partitions ( $ arr , $ n ) { $ right_min [ $ n + 1 ] = array ( ) ; $ right_min [ $ n ] = PHP_INT_MAX ; for ( $ i = $ n - 1 ; $ i >= 0 ; $ i -- ) { $ right_min [ $ i ] = min ( $ right_min [ $ i + 1 ] , $ arr [ $ i ] ) ; } $ partitions = 0 ; for ( $ current_max = $ arr [ 0 ] , $ i = 0 ; $ i < $ n ; $ i ++ ) { $ current_max = max ( $ current_max , $ arr [ $ i ] ) ; if ( $ current_max <= $ right_min [ $ i + 1 ] ) $ partitions ++ ; } return $ partitions ; } $ arr = array ( 3 , 1 , 2 , 4 , 100 , 7 , 9 ) ; $ n = sizeof ( $ arr ) ; $ ans = sorted_partitions ( $ arr , $ n ) ; echo $ ans , "
 " ; ? >


"Partition into two subarrays of lengths k and ( N | Function to calculate max_difference ; Sum of the array ; Sort the array in descending order ; Calculating max_difference ; Driver Code"
Solution in php:

< ? php function maxDifference ( $ arr , $ N , $ k ) { $ M ; $ S = 0 ; $ S1 = 0 ; $ max_difference = 0 ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) $ S += $ arr [ $ i ] ; rsort ( $ arr ) ; $ M = max ( $ k , $ N - $ k ) ; for ( $ i = 0 ; $ i < $ M ; $ i ++ ) $ S1 += $ arr [ $ i ] ; $ max_difference = $ S1 - ( $ S - $ S1 ) ; return $ max_difference ; } $ arr = array ( 8 , 4 , 5 , 2 , 10 ) ; $ N = count ( $ arr ) ; $ k = 2 ; echo maxDifference ( $ arr , $ N , $ k ) ; ? >


"Partition the array into three equal sum segments | First segment 's end index ; Third segment 's start index ; This function returns true if the array can be divided into three equal sum segments ; Prefix Sum Array ; Suffix Sum Array ; Stores the total sum of the array ; We can also take pre [ pos2 - 1 ] - pre [ pos1 ] == total_sum / 3 here . ; Driver Code"
Solution in php:

 < ? php $ pos1 = -1 ; $ pos2 = -1 ; function equiSumUtil ( $ arr ) { global $ pos2 , $ pos1 ; $ n = count ( $ arr ) ; $ pre = array_fill ( 0 , $ n , 0 ) ; $ sum = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ sum += $ arr [ $ i ] ; $ pre [ $ i ] = $ sum ; } $ suf = array_fill ( 0 , $ n , 0 ) ; $ sum = 0 ; for ( $ i = $ n - 1 ; $ i >= 0 ; $ i -- ) { $ sum += $ arr [ $ i ] ; $ suf [ $ i ] = $ sum ; } $ total_sum = $ sum ; $ i = 0 ; $ j = $ n - 1 ; while ( $ i < $ j - 1 ) { if ( $ pre [ $ i ] == $ total_sum / 3 ) { $ pos1 = $ i ; } if ( $ suf [ $ j ] == $ total_sum / 3 ) { $ pos2 = $ j ; } if ( $ pos1 != -1 && $ pos2 != -1 ) { if ( $ suf [ $ pos1 + 1 ] - $ suf [ $ pos2 ] == $ total_sum / 3 ) { return true ; } else { return false ; } } if ( $ pre [ $ i ] < $ suf [ $ j ] ) { $ i ++ ; } else { $ j -- ; } } return false ; } function equiSum ( $ arr ) { global $ pos2 , $ pos1 ; $ ans = equiSumUtil ( $ arr ) ; if ( $ ans ) { print ( " First ▁ Segment ▁ : ▁ " ) ; for ( $ i = 0 ; $ i <= $ pos1 ; $ i ++ ) { print ( $ arr [ $ i ] . " " ) ; } print ( "
 " ) ; print ( " Second ▁ Segment ▁ : ▁ " ) ; for ( $ i = $ pos1 + 1 ; $ i < $ pos2 ; $ i ++ ) { print ( $ arr [ $ i ] . " " ) ; } print ( "
 " ) ; print ( " Third ▁ Segment ▁ : ▁ " ) ; for ( $ i = $ pos2 ; $ i < count ( $ arr ) ; $ i ++ ) { print ( $ arr [ $ i ] . " " ) ; } print ( "
 " ) ; } else { println ( " Array ▁ cannot ▁ be ▁ divided ▁ into ▁ " , " three ▁ equal ▁ sum ▁ segments " ) ; } } $ arr = array ( 1 , 3 , 6 , 2 , 7 , 1 , 2 , 8 ) ; equiSum ( $ arr ) ; ? >


"Path with maximum average value | method returns maximum average of all path of cost matrix ; Initialize first column of total cost ( dp ) array ; Initialize first row of dp array ; Construct rest of the dp array ; divide maximum sum by constant path length : ( 2 N - 1 ) for getting average ; Driver code"
Solution in php:


"Pentagonal Pyramidal Number | function to get nth Pentagonal pyramidal number . ; Driver Code"
Solution in php:

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


"Pentagonal Pyramidal Number | function to get nth Pentagonal pyramidal number . ; Running loop from 1 to n ; get nth pentagonal number ; add to sum ; Driver Code"
Solution in php:

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


"Pentatope number | Function that returns nth pentatope number ; For 5 th PentaTope Number ; For 11 th PentaTope Number"
Solution in php:

 < ? php function pentatopeNum ( $ n ) { return ( $ n * ( $ n + 1 ) * ( $ n + 2 ) * ( $ n + 3 ) ) / 24 ; } $ n = 5 ; echo pentatopeNum ( $ n ) , "
 " ; $ n = 11 ; echo pentatopeNum ( $ n ) , "
 " ; ? >


"Pentatope number | function for Pentatope number ; formula for find Pentatope nth term ; Driver Code"
Solution in php:

 < ? php function Pentatope_number ( $ n ) { return $ n * ( $ n + 1 ) * ( $ n + 2 ) * ( $ n + 3 ) / 24 ; } $ n = 7 ; echo $ n , " th ▁ Pentatope ▁ number ▁ : " , Pentatope_number ( $ n ) , "
 " ; $ n = 12 ; echo $ n , " th ▁ Pentatope ▁ number ▁ : " , Pentatope_number ( $ n ) ; ? >


"Perfect Number | Returns true if n is perfect ; To store sum of divisors ; Find all divisors and add them ; If sum of divisors is equal to n , then n is a perfect number ; Driver Code"
Solution in php:

 < ? php function isPerfect ( $ n ) { $ sum = 1 ; for ( $ i = 2 ; $ i * $ i <= $ n ; $ i ++ ) { if ( $ n % $ i == 0 ) { if ( $ i * $ i != $ n ) $ sum = $ sum + $ i + ( int ) ( $ n / $ i ) ; else $ sum = $ sum + $ i ; } } if ( $ sum == $ n && $ n != 1 ) return true ; return false ; } echo " Below ▁ are ▁ all ▁ perfect ▁ numbers ▁ till ▁ 10000
 " ; for ( $ n = 2 ; $ n < 10000 ; $ n ++ ) if ( isPerfect ( $ n ) ) echo " $ n ▁ is ▁ a ▁ perfect ▁ number
 " ; ? >


"Perfect Square String | PHP program to find if string is a perfect square or not . ; calculating the length of the string ; calculating the ASCII value of the string ; Find floating point value of square root of x . ; If square root is an integer ; Driver code"
Solution in php:

< ? php function isPerfectSquareString ( $ str ) { $ sum = 0 ; $ len = strlen ( $ str ) ; for ( $ i = 0 ; $ i < $ len ; $ i ++ ) $ sum += ( int ) $ str [ $ i ] ; $ squareRoot = sqrt ( $ sum ) ; return ( ( $ squareRoot - floor ( $ squareRoot ) ) == 0 ) ; } $ str = " d " ; if ( isPerfectSquareString ( $ str ) ) echo " Yes " ; else echo " No " ; ? >


"Perfect cubes in a range | A Simple Method to count cubes between a and b ; Traverse through all numbers in given range and one by one check if number is prime ; Check if current number ' i ' is perfect cube ; Driver Code"
Solution in php:

 < ? php function printCubes ( $ a , $ b ) { for ( $ i = $ a ; $ i <= $ b ; $ i ++ ) { for ( $ j = 1 ; $ j * $ j * $ j <= $ i ; $ j ++ ) { if ( $ j * $ j * $ j == $ i ) { echo $ j * $ j * $ j , " " ; break ; } } } } $ a = 1 ; $ b = 100 ; echo " Perfect ▁ cubes ▁ in ▁ given ▁ range :
 ▁ " ; printCubes ( $ a , $ b ) ; ? >


"Perfect cubes in a range | An efficient solution to print perfect cubes between a and b ; Find cube root of both a and b ; Print cubes between acrt and bcrt ; Driver code"
Solution in php:

 < ? php function printCubes ( $ a , $ b ) { $ acrt = ( int ) pow ( $ a , 1 / 3 ) ; $ bcrt = ( int ) pow ( $ b , 1 / 3 ) ; for ( $ i = $ acrt ; $ i <= $ bcrt ; $ i ++ ) if ( $ i * $ i * $ i >= $ a && $ i * $ i * $ i <= $ b ) echo $ i * $ i * $ i , " ▁ " ; } $ a = 24 ; $ b = 576 ; echo " Perfect ▁ cubes ▁ in ▁ given ▁ range :
 " , printCubes ( $ a , $ b ) ; ? >


"Perfect power ( 1 , 4 , 8 , 9 , 16 , 25 , 27 , ... ) | Function that keeps all the odd power numbers upto n ; We need exclude perfect squares . ; sort the vector ; Return sum of odd and even powers . ; Driver Code"
Solution in php:

< ? php function powerNumbers ( $ n ) { $ v = array ( ) ; for ( $ i = 2 ; $ i * $ i * $ i <= $ n ; $ i ++ ) { $ j = $ i * $ i ; while ( $ j * $ i <= $ n ) { $ j *= $ i ; $ s = sqrt ( $ j ) ; if ( $ s * $ s != $ j ) array_push ( $ v , $ j ) ; } } sort ( $ v ) ; $ uni = array_unique ( $ v ) ; for ( $ i = 0 ; $ i < count ( $ uni ) ; $ i ++ ) { $ key = array_search ( $ uni [ $ i ] , $ v ) ; unset ( $ v [ $ key ] ) ; } return count ( $ v ) + 3 + intval ( sqrt ( $ n ) ) ; } echo ( powerNumbers ( 50 ) ) ; ? >


"Perimeter and Area of Varignon 's Parallelogram | Function to find the perimeter ; Function to find the area ; Driver code"
Solution in php:

 < ? php function per ( $ a , $ b ) { return ( $ a + $ b ) ; } function area ( $ s ) { return ( $ s / 2 ) ; } $ a = 7 ; $ b = 8 ; $ s = 10 ; echo ( per ( $ a , $ b ) " " ) ; echo "
 " ; echo ( area ( $ s ) ) ; ? >


"Permutations of n things taken r at a time with k things together | Function to find factorial of a number ; Function to calculate p ( n , r ) ; Function to find the number of permutations of n different things taken r at a time with k things grouped together ; Driver code"
Solution in php:

< ? php function factorial ( $ n ) { $ fact = 1 ; for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) $ fact = $ fact * $ i ; return $ fact ; } function npr ( $ n , $ r ) { $ pnr = factorial ( $ n ) / factorial ( $ n - $ r ) ; return $ pnr ; } function countPermutations ( $ n , $ r , $ k ) { return factorial ( $ k ) * ( $ r - $ k + 1 ) * npr ( $ n - $ k , $ r - $ k ) ; } $ n = 8 ; $ r = 5 ; $ k = 2 ; echo countPermutations ( $ n , $ r , $ k ) ; ? >


"Permutations of string such that no two vowels are adjacent | Factorial of a number ; Function to find c ( n , r ) ; Function to count permutations of string such that no two vowels are adjacent ; Finding the frequencies of the characters ; finding the no . of vowels and consonants in given word ; finding places for the vowels ; ways to fill consonants 6 ! / 2 ! ; ways to put vowels 7 C5 x 5 ! ; Driver code"
Solution in php:

 < ? php function factorial ( $ n ) { $ fact = 1 ; for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) $ fact = $ fact * $ i ; return $ fact ; } function ncr ( $ n , $ r ) { return factorial ( $ n ) / ( factorial ( $ r ) * factorial ( $ n - $ r ) ) ; } function countWays ( $ str ) { $ freq = array_fill ( 0 , 26 , NULL ) ; $ nvowels = 0 ; $ nconsonants = 0 ; for ( $ i = 0 ; $ i < strlen ( $ str ) ; $ i ++ ) ++ $ freq [ ord ( $ str [ $ i ] ) - ord ( ' a ' ) ] ; for ( $ i = 0 ; $ i < 26 ; $ i ++ ) { if ( $ i == 0 $ i == 4 $ i == 8 $ i == 14 $ i == 20 ) $ nvowels += $ freq [ $ i ] ; else $ nconsonants += $ freq [ $ i ] ; } $ vplaces = $ nconsonants + 1 ; $ cways = factorial ( $ nconsonants ) ; for ( $ i = 0 ; $ i < 26 ; $ i ++ ) { if ( $ i != 0 && $ i != 4 && $ i != 8 && $ i != 14 && $ i != 20 && $ freq [ $ i ] > 1 ) { $ cways = $ cways / factorial ( $ freq [ $ i ] ) ; } } $ vways = ncr ( $ vplaces , $ nvowels ) * factorial ( $ nvowels ) ; for ( $ i = 0 ; $ i < 26 ; $ i ++ ) { if ( $ i == 0 $ i == 4 $ i == 8 $ i == 14 $ i == 20 && $ freq [ $ i ] > 1 ) { $ vways = $ vways / factorial ( $ freq [ $ i ] ) ; } } return $ cways * $ vways ; } $ str = " permutation " ; echo countWays ( $ str ) . "
 " ; return 0 ; ? >


"Permutations to arrange N persons around a circular table | Function to find no . of permutations ; Driver Code"
Solution in php:

< ? php function Circular ( $ n ) { $ Result = 1 ; while ( $ n > 0 ) { $ Result = $ Result * $ n ; $ n -- ; } return $ Result ; } $ n = 4 ; echo Circular ( $ n - 1 ) ; ? >


"Perpendicular distance between a point and a Line in 2 D | Function to find distance ; Driver Code"
Solution in php:

< ? php function shortest_distance ( $ x1 , $ y1 , $ a , $ b , $ c ) { $ d = abs ( ( $ a * $ x1 + $ b * $ y1 + $ c ) ) / ( sqrt ( $ a * $ a + $ b * $ b ) ) ; echo " Perpendicular ▁ distance ▁ is ▁ " , $ d ; } $ x1 = 5 ; $ y1 = 6 ; $ a = -2 ; $ b = 3 ; $ c = 4 ; shortest_distance ( $ x1 , $ y1 , $ a , $ b , $ c ) ; ? >


"Pierpont Prime | PHP program to print Pierpont prime numbers smaller than n . ; Finding all numbers having factor power of 2 and 3 Using sieve ; Storing number of the form 2 ^ i . 3 ^ k + 1. ; Finding prime number using sieve of Eratosthenes . Reusing same array as result of above computations in v . ; Printing n pierpont primes smaller than n ; Driver Code"
Solution in php:

< ? php function printPierpont ( $ n ) { $ arr = array_fill ( 0 , $ n + 1 , false ) ; $ two = 1 ; $ three = 1 ; while ( $ two + 1 < $ n ) { $ arr [ $ two ] = true ; while ( $ two * $ three + 1 < $ n ) { $ arr [ $ three ] = true ; $ arr [ $ two * $ three ] = true ; $ three *= 3 ; } $ three = 1 ; $ two *= 2 ; } $ v ; $ x = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) if ( $ arr [ $ i ] ) $ v [ $ x ++ ] = $ i + 1 ; $ arr1 = array_fill ( 0 , count ( $ arr ) , false ) ; for ( $ p = 2 ; $ p * $ p < $ n ; $ p ++ ) { if ( $ arr1 [ $ p ] == false ) for ( $ i = $ p * 2 ; $ i < $ n ; $ i += $ p ) $ arr1 [ $ i ] = true ; } for ( $ i = 0 ; $ i < $ x ; $ i ++ ) if ( ! $ arr1 [ $ v [ $ i ] ] ) echo $ v [ $ i ] . " ▁ " ; } $ n = 200 ; printPierpont ( $ n ) ; ? >


"Pizza cut problem ( Or Circle Division by Lines ) | Function for finding maximum pieces with n cuts . ; Driver code"
Solution in php:

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


"Place k elements such that minimum distance is maximized | Returns true if it is possible to arrange k elements of arr [ 0. . n - 1 ] with minimum distance given as mid . ; Place first element at arr [ 0 ] position ; Initialize count of elements placed . ; Try placing k elements with minimum distance mid . ; Place next element if its distance from the previously placed element is greater than current mid ; Return if all elements are placed successfully ; Returns largest minimum distance for k elements in arr [ 0. . n - 1 ] . If elements can 't be placed, returns -1. ; Sort the positions ; Initialize result . ; Consider the maximum possible distance ; Do binary search for largest minimum distance ; If it is possible to place k elements with minimum distance mid , search for higher distance . ; Change value of variable max to mid iff all elements can be successfully placed ; If not possible to place k elements , search for lower distance ; Driver Code"
Solution in php:

< ? php function isFeasible ( $ mid , $ arr , $ n , $ k ) { $ pos = $ arr [ 0 ] ; $ elements = 1 ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] - $ pos >= $ mid ) { $ pos = $ arr [ $ i ] ; $ elements ++ ; if ( $ elements == $ k ) return true ; } } return 0 ; } function largestMinDist ( $ arr , $ n , $ k ) { sort ( $ arr ) ; $ res = -1 ; $ left = 1 ; $ right = $ arr [ $ n - 1 ] ; while ( $ left < $ right ) { $ mid = ( $ left + $ right ) / 2 ; if ( isFeasible ( $ mid , $ arr , $ n , $ k ) ) { $ res = max ( $ res , $ mid ) ; $ left = $ mid + 1 ; } else $ right = $ mid ; } return $ res ; } $ arr = array ( 1 , 2 , 8 , 4 , 9 ) ; $ n = sizeof ( $ arr ) ; $ k = 3 ; echo largestMinDist ( $ arr , $ n , $ k ) ; ? >


"Polybius Square Cipher | function to display polybius cipher text ; convert each character to its encrypted code ; finding row of the table ; finding column of the table ; if character is ' k ' ; if character is greater than ' j ' ; Driver Code ; print the cipher of "geeksforgeeks"
Solution in php:

 < ? php function polybiusCipher ( $ s ) { $ row = 0 ; $ col = 0 ; for ( $ i = 0 ; $ i < strlen ( $ s ) ; $ i ++ ) { $ row = floor ( ( ord ( $ s [ $ i ] ) - ord ( ' a ' ) ) / 5 ) + 1 ; $ col = ( ( ord ( $ s [ $ i ] ) - ord ( ' a ' ) ) % 5 ) + 1 ; if ( $ s [ $ i ] == ' k ' ) { $ row = $ row - 1 ; $ col = 5 - $ col + 1 ; } else if ( $ s [ $ i ] >= ' j ' ) { if ( $ col == 1 ) { $ col = 6 ; $ row = $ row - 1 ; } $ col = $ col - 1 ; } echo ( $ row . $ col ) ; } echo ( "
 " ) ; } $ s = " geeksforgeeks " ; polybiusCipher ( $ s ) ; ? >


"Position after taking N steps to the right and left in an alternate manner | Function to return the last destination ; Driver Code"
Solution in php:

< ? php function lastCoordinate ( $ n , $ a , $ b ) { return ( ( $ n + 1 ) / 2 ) * $ a - ( int ) ( $ n / 2 ) * $ b ; } $ n = 3 ; $ a = 5 ; $ b = 2 ; echo lastCoordinate ( $ n , $ a , $ b ) ; ? >


"Position of a person diametrically opposite on a circle | Function to return the required position ; Driver code"
Solution in php:

< ? php function getPosition ( $ n , $ m ) { if ( $ m > ( $ n / 2 ) ) return ( $ m - ( $ n / 2 ) ) ; return ( $ m + ( $ n / 2 ) ) ; } $ n = 8 ; $ m = 5 ; echo getPosition ( $ n , $ m ) ; ? >


"Position of an element after stable sort | Method returns the position of arr [ idx ] after performing stable - sort on array ; Count of elements smaller than current element plus the equal element occurring before given index ; If element is smaller then increase the smaller count ; If element is equal then increase count only if it occurs before ; Driver Code"
Solution in php:

< ? php function getIndexInSortedArray ( $ arr , $ n , $ idx ) { $ result = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] < $ arr [ $ idx ] ) $ result ++ ; if ( $ arr [ $ i ] == $ arr [ $ idx ] and $ i < $ idx ) $ result ++ ; } return $ result ; } $ arr = array ( 3 , 4 , 3 , 5 , 2 , 3 , 4 , 3 , 1 , 5 ) ; $ n = count ( $ arr ) ; $ idxOfEle = 5 ; echo getIndexInSortedArray ( $ arr , $ n , $ idxOfEle ) ; ? >


"Position of rightmost common bit in two numbers | Function to find the position of rightmost set bit in ' n ' ; Function to find the position of rightmost same bit in the binary representations of ' m ' and ' n ' ; position of rightmost same bit ; Driver Code"
Solution in php:

< ? php function getRightMostSetBit ( $ n ) { return log ( $ n & - $ n ) + 1 ; } function posOfRightMostSameBit ( $ m , $ n ) { return getRightMostSetBit ( ~ ( $ m ^ $ n ) ) ; } $ m = 16 ; $ n = 7 ; echo " Position ▁ = ▁ " , ceil ( posOfRightMostSameBit ( $ m , $ n ) ) ; ? >


"Position of rightmost different bit | Function to find the position of rightmost set bit in ' n ' ; to handle edge case when n = 0. ; Function to find the position of rightmost different bit in the binary representations of ' m ' and ' n ' ; position of rightmost different bit ; Driver Code"
Solution in php:

< ? php function getRightMostSetBit ( $ n ) { if ( $ n == 0 ) return 0 ; return log ( $ n & - $ n , ( 2 ) ) + 1 ; } function posOfRightMostDiffBit ( $ m , $ n ) { return getRightMostSetBit ( $ m ^ $ n ) ; } $ m = 52 ; $ n = 4 ; echo posOfRightMostDiffBit ( $ m , $ n ) ; ? >


"Position of rightmost different bit | function to find rightmost different bit in two numbers . ; Driver code"
Solution in php:

< ? php function posOfRightMostDiffBit ( $ m , $ n ) { $ t = floor ( log ( $ m ^ $ n , 2 ) ) ; return $ t ; } $ m = 52 ; $ n = 4 ; echo " Position ▁ = ▁ " , posOfRightMostDiffBit ( $ m , $ n ) ; ? >


"Position of rightmost set bit | PHP Code for Position of rightmost set bit ; Driver Code"
Solution in php:

< ? php function getFirstSetBitPos ( $ n ) { return ceil ( log ( ( $ n & - $ n ) + 1 , 2 ) ) ; } $ n = 12 ; echo getFirstSetBitPos ( $ n ) ; ? >


"Position of rightmost set bit | PHP implementation of above approach ; counting the position of first set bit ; Driver code"
Solution in php:

 < ? php function Right_most_setbit ( $ num ) { $ pos = 1 ; $ INT_SIZE = 32 ; for ( $ i = 0 ; $ i < $ INT_SIZE ; $ i ++ ) { if ( ! ( $ num & ( 1 << $ i ) ) ) $ pos ++ ; else break ; } return $ pos ; } $ num = 18 ; $ pos = Right_most_setbit ( $ num ) ; echo $ pos ; echo ( "
 " ) ? >


"Position of rightmost set bit | function to find the rightmost set bit ; Position variable initialize with 1 m variable is used to check the set bit ; left shift ; Driver Code ; function call"
Solution in php:

< ? php function PositionRightmostSetbit ( $ n ) { $ position = 1 ; $ m = 1 ; while ( ! ( $ n & $ m ) ) { $ m = $ m << 1 ; $ position ++ ; } return $ position ; } $ n = 16 ; echo PositionRightmostSetbit ( $ n ) ; ? >


"Position of robot after given movements | function to find final position of robot after the complete movement ; traverse the instruction string ' move ' ; for each movement increment its respective counter ; required final position of robot ; Driver Code"
Solution in php:

< ? php function finalPosition ( $ move ) { $ l = strlen ( $ move ) ; $ countUp = 0 ; $ countDown = 0 ; $ countLeft = 0 ; $ countRight = 0 ; for ( $ i = 0 ; $ i < $ l ; $ i ++ ) { if ( $ move [ $ i ] == ' U ' ) $ countUp ++ ; else if ( $ move [ $ i ] == ' D ' ) $ countDown ++ ; else if ( $ move [ $ i ] == ' L ' ) $ countLeft ++ ; else if ( $ move [ $ i ] == ' R ' ) $ countRight ++ ; } echo " Final ▁ Position : ▁ ( " . ( $ countRight - $ countLeft ) . " , " ▁ , ▁ ( $ countUp ▁ - ▁ $ countDown ) ▁ . ▁ " ) " ▁ . " " } $ move = " UDDLLRUUUDUURUDDUULLDRRRR " ; finalPosition ( $ move ) ; ? >


"Position of the K | Function that returns the Kth set bit ; Traverse in the binary ; Check if the last bit is set or not ; Check if count is equal to k then return the index ; Increase the index as we move right ; Right shift the number by 1 ; Driver Code"
Solution in php:

< ? php function FindIndexKthBit ( $ n , $ k ) { $ cnt = 0 ; $ ind = 0 ; while ( $ n ) { if ( $ n & 1 ) $ cnt ++ ; if ( $ cnt == $ k ) return $ ind ; $ ind ++ ; $ n = $ n >> 1 ; } return -1 ; } $ n = 15 ; $ k = 3 ; $ ans = FindIndexKthBit ( $ n , $ k ) ; if ( $ ans != -1 ) echo $ ans ; else echo " No ▁ k - th ▁ set ▁ bit " ; ? >


"Positive elements at even and negative at odd positions ( Relative order not maintained ) | PHP program to rearrange positive and negative numbers ; Move forward the positive pointer till negative number number not encountered ; Move forward the negative pointer till positive number number not encountered ; Swap array elements to fix their position . ; Break from the while loop when any index exceeds the size of the array ; Driver code"
Solution in php:

< ? php function rearrange ( & $ a , $ size ) { $ positive = 0 ; $ negative = 1 ; while ( true ) { while ( $ positive < $ size && $ a [ $ positive ] >= 0 ) $ positive += 2 ; while ( $ negative < $ size && $ a [ $ negative ] <= 0 ) $ negative += 2 ; if ( $ positive < $ size && $ negative < $ size ) { $ temp = $ a [ $ positive ] ; $ a [ $ positive ] = $ a [ $ negative ] ; $ a [ $ negative ] = $ temp ; } else break ; } } $ arr = array ( 1 , -3 , 5 , 6 , -3 , 6 , 7 , -4 , 9 , 10 ) ; $ n = sizeof ( $ arr ) ; rearrange ( $ arr , $ n ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; ? >


"Possibility of a word from a given set of characters | PHP program to check if a query string is present is given set . ; Count occurrences of all characters in s . ; Check if number of occurrences of every character in q is less than or equal to that in s . ; Driver Code"
Solution in php:

< ? php function isPresent ( $ s , $ q ) { $ freq = array ( 256 ) ; for ( $ i = 0 ; $ i < 256 ; $ i ++ ) $ freq [ $ i ] = 0 ; for ( $ i = 0 ; $ i < strlen ( $ s ) ; $ i ++ ) $ freq [ ord ( $ s [ $ i ] ) - ord ( ' a ' ) ] ++ ; for ( $ i = 0 ; $ i < strlen ( $ q ) ; $ i ++ ) { $ freq [ ord ( $ q [ $ i ] ) - ord ( ' a ' ) ] -- ; if ( $ freq [ ord ( $ q [ $ i ] ) - ord ( ' a ' ) ] < 0 ) return false ; } return true ; } $ s = " abctd " ; $ q = " cat " ; if ( isPresent ( $ s , $ q ) ) echo " Yes " ; else echo " No " ; ? >


"Possible cuts of a number such that maximum parts are divisible by 3 | Function to find the maximum number of numbers divisible by 3 in a large number ; store size of the string ; Stores last index of a remainder ; last visited place of remainder zero is at 0. ; To store result from 0 to i ; get the remainder ; Get maximum res [ i ] value ; Driver Code"
Solution in php:

 < ? php function MaximumNumbers ( $ s ) { $ n = strlen ( $ s ) ; $ remIndex = array_fill ( 0 , 3 , -1 ) ; $ remIndex [ 0 ] = 0 ; $ res = array ( ) ; $ r = 0 ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) { $ r = ( $ r + $ s [ $ i - 1 ] - '0' ) % 3 ; $ res [ $ i ] = $ res [ $ i - 1 ] ; if ( $ remIndex [ $ r ] != -1 ) $ res [ $ i ] = max ( $ res [ $ i ] , $ res [ $ remIndex [ $ r ] ] + 1 ) ; $ remIndex [ $ r ] = $ i + 1 ; } return $ res [ $ n ] ; } $ s = "12345" ; print ( MaximumNumbers ( $ s ) ) # This  code is contributed by Ryuga
? >


"Possible cuts of a number such that maximum parts are divisible by 3 | PHP program to find the maximum number of numbers divisible by 3 in a large number ; This will contain the count of the splits ; This will keep sum of all successive integers , when they are indivisible by 3 ; This is the condition of finding a split ; Driver Code"
Solution in php:

< ? php function get_max_splits ( $ num_string ) { $ count = 0 ; $ running_sum = 0 ; for ( $ i = 0 ; $ i < strlen ( $ num_string ) ; $ i ++ ) { $ current_num = intval ( $ num_string [ $ i ] ) ; $ running_sum += $ current_num ; if ( $ current_num % 3 == 0 or ( $ running_sum != 0 and $ running_sum % 3 == 0 ) ) { $ count += 1 ; $ running_sum = 0 ; } } return $ count ; } print ( get_max_splits ( "12345" ) ) ; ? >


"Possible moves of knight | PHP program to find number of possible moves of knight ; To calculate possible moves ; All possible moves of a knight ; Check if each possible move is valid or not ; Position of knight after move ; count valid moves ; Return number of possible moves ; Driver Code"
Solution in php:


"Possible to form a triangle from array values | Method prints possible triangle when array values are taken as sides ; If number of elements are less than 3 , then no triangle is possible ; first sort the array ; loop for all 3 consecutive triplets ; If triplet satisfies triangle condition , break ; Driver Code"
Solution in php:

< ? php function isPossibleTriangle ( $ arr , $ N ) { if ( $ N < 3 ) return false ; sort ( $ arr ) ; for ( $ i = 0 ; $ i < $ N - 2 ; $ i ++ ) if ( $ arr [ $ i ] + $ arr [ $ i + 1 ] > $ arr [ $ i + 2 ] ) return true ; } $ arr = array ( 5 , 4 , 3 , 1 , 2 ) ; $ N = count ( $ arr ) ; if ( isPossibleTriangle ( $ arr , $ N ) ) echo " Yes " ; else echo " No " ; ? >


"Possible two sets from first N natural numbers difference of sums as D | Function returns true if it is possible to split into two sets otherwise returns false ; Driver code"
Solution in php:

< ? php function check ( $ N , $ D ) { $ temp = ( $ N * ( $ N + 1 ) ) / 2 + $ D ; return ( $ temp % 2 == 0 ) ; } $ N = 5 ; $ M = 7 ; if ( check ( $ N , $ M ) ) echo ( " yes " ) ; else echo ( " no " ) ;


"Powerful Number | function to check if the number is powerful ; First divide the number repeatedly by 2 ; If only 2 ^ 1 divides n ( not higher powers ) , then return false ; if n is not a power of 2 then this loop will execute repeat above process ; Find highest power of " factor " that divides n ; If only factor ^ 1 divides n ( not higher powers ) , then return false ; n must be 1 now if it is not a prime number . Since prime numbers are not powerful , we return false if n is not 1. ; Driver Code"
Solution in php:

 < ? php function isPowerful ( $ n ) { while ( $ n % 2 == 0 ) { $ power = 0 ; while ( $ n % 2 == 0 ) { $ n /= 2 ; $ power ++ ; } if ( $ power == 1 ) return false ; } for ( $ factor = 3 ; $ factor <= sqrt ( $ n ) ; $ factor += 2 ) { $ power = 0 ; while ( $ n % $ factor == 0 ) { $ n = $ n / $ factor ; $ power ++ ; } if ( $ power == 1 ) return false ; } return ( $ n == 1 ) ; } $ d = isPowerful ( 20 ) ? " YES
 " : " NO
 " ; echo $ d ; $ d = isPowerful ( 27 ) ? " YES
 " : " NO
 " ; echo $ d ; ? >


"Powers of 2 to required sum | PHP program to find the blocks for given number . ; Convert decimal number to its binary equivalent ; Displaying the output when the bit is '1' in binary equivalent of number . ; Driver Code"
Solution in php:

 < ? php function block ( $ x ) { $ v = array ( ) ; echo ' locks for ' . $ x . ' ▁ : ▁ ' ; while ( $ x > 0 ) { array_push ( $ v , intval ( $ x % 2 ) ) ; $ x = intval ( $ x / 2 ) ; } for ( $ i = 0 ; $ i < sizeof ( $ v ) ; $ i ++ ) { if ( $ v [ $ i ] == 1 ) { print $ i ; if ( $ i != sizeof ( $ v ) - 1 ) echo ' , ▁ ' ; } } echo "
 " ; } block ( 71307 ) ; block ( 1213 ) ; block ( 29 ) ; block ( 100 ) ; ? >


"Predict the winner of the game on the basis of absolute difference of sum by selecting numbers | Function to decide the winner ; Iterate for all numbers in the array ; If mod gives 0 ; If mod gives 1 ; If mod gives 2 ; If mod gives 3 ; Check the winning condition for X ; Driver code"
Solution in php:

< ? php function decideWinner ( $ a , $ n ) { $ count0 = 0 ; $ count1 = 0 ; $ count2 = 0 ; $ count3 = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ a [ $ i ] % 4 == 0 ) $ count0 ++ ; else if ( $ a [ $ i ] % 4 == 1 ) $ count1 ++ ; else if ( $ a [ $ i ] % 4 == 2 ) $ count2 ++ ; else if ( $ a [ $ i ] % 4 == 3 ) $ count3 ++ ; } if ( $ count0 % 2 == 0 && $ count1 % 2 == 0 && $ count2 % 2 == 0 && $ count3 == 0 ) return 1 ; else return 2 ; } $ a = array ( 4 , 8 , 5 , 9 ) ; $ n = count ( $ a ) ; if ( decideWinner ( $ a , $ n ) == 1 ) echo " X ▁ wins " ; else echo " Y ▁ wins " ; ? >


"Prefixes with more a than b | Function to count prefixes ; calculating for string S ; count == 0 or when N == 1 ; when all characters are a or a - b == 0 ; checking for saturation of string after repetitive addition ; Driver Code"
Solution in php:


"Previous greater element | php program previous greater element A naive solution to print previous greater element for every element in an array . ; Previous greater for first element never exists , so we print - 1. ; Let us process remaining elements . ; Find first element on left side that is greater than arr [ i ] . ; If all elements on left are smaller . ; Driver code"
Solution in php:


"Previous smaller integer having one less number of set bits | function to find the position of rightmost set bit . ; function to find the previous smaller integer ; position of rightmost set bit of n ; turn off or unset the bit at position ' pos ' ; Driver Code"
Solution in php:

< ? php function getFirstSetBitPos ( $ n ) { return log ( $ n & - $ n ) + 1 ; } function previousSmallerInteger ( $ n ) { $ pos = getFirstSetBitPos ( $ n ) ; return ( $ n & ~ ( 1 << ( $ pos - 1 ) ) ) ; } $ n = 25 ; echo " Previous ▁ smaller ▁ Integer ▁ = ▁ " , previousSmallerInteger ( $ n ) ; ? >


"Primality Test | Set 1 ( Introduction and School Method ) | A school method based PHP program to check if a number is prime ; Corner case ; Check from 2 to n - 1 ; Driver Code"
Solution in php:

 < ? php function isPrime ( $ n ) { if ( $ n <= 1 ) return false ; for ( $ i = 2 ; $ i < $ n ; $ i ++ ) if ( $ n % $ i == 0 ) return false ; return true ; } $ tet = isPrime ( 11 ) ? " ▁ true
 " : " ▁ false
 " ; echo $ tet ; $ tet = isPrime ( 15 ) ? " ▁ true
 " : " ▁ false
 " ; echo $ tet ; ? >


"Primality test for the sum of digits at odd places of a number | Function that return sum of the digits at odd places ; Function that returns true if the number is prime else false ; Corner cases ; This condition is checked so that we can skip middle five numbers in the below loop ; Driver code ; Get the sum of the digits at odd places"
Solution in php:

< ? php function sum_odd ( $ n ) { $ sum = 0 ; $ pos = 1 ; while ( $ n ) { if ( $ pos % 2 == 1 ) $ sum += $ n % 10 ; $ n = ( int ) ( $ n / 10 ) ; $ pos ++ ; } return $ sum ; } function check_prime ( $ n ) { if ( $ n <= 1 ) return false ; if ( $ n <= 3 ) return true ; if ( $ n % 2 == 0 $ n % 3 == 0 ) return false ; for ( $ i = 5 ; $ i * $ i <= $ n ; $ i = ( $ i + 6 ) ) if ( $ n % $ i == 0 || $ n % ( $ i + 2 ) == 0 ) return false ; return true ; } $ n = 223 ; $ sum = sum_odd ( $ n ) ; if ( check_prime ( $ sum ) ) echo " YES " ; else echo " NO " ; ? >


"Prime Factor | function to print all prime factors of a given number n ; Print 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 , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Driver Code"
Solution in php:


"Prime Factorization using Sieve O ( log n ) for multiple queries | PHP program to find prime factorization of a number n in O ( Log n ) time with precomputation allowed . ; stores smallest prime factor for every number ; Calculating SPF ( Smallest Prime Factor ) for every number till MAXN . Time Complexity : O ( nloglogn ) ; marking smallest prime factor for every number to be itself . ; separately marking spf for every even number as 2 ; checking if i is prime ; marking SPF for all numbers divisible by i ; marking spf [ j ] if it is not previously marked ; A O ( log n ) function returning primefactorization by dividing by smallest prime factor at every step ; precalculating Smallest Prime Factor ; calling getFactorization function"
Solution in php:

< ? php $ MAXN = 19999 ; $ spf = array_fill ( 0 , $ MAXN , 0 ) ; function sieve ( ) { global $ MAXN , $ spf ; $ spf [ 1 ] = 1 ; for ( $ i = 2 ; $ i < $ MAXN ; $ i ++ ) $ spf [ $ i ] = $ i ; for ( $ i = 4 ; $ i < $ MAXN ; $ i += 2 ) $ spf [ $ i ] = 2 ; for ( $ i = 3 ; $ i * $ i < $ MAXN ; $ i ++ ) { if ( $ spf [ $ i ] == $ i ) { for ( $ j = $ i * $ i ; $ j < $ MAXN ; $ j += $ i ) if ( $ spf [ $ j ] == $ j ) $ spf [ $ j ] = $ i ; } } } function getFactorization ( $ x ) { global $ spf ; $ ret = array ( ) ; while ( $ x != 1 ) { array_push ( $ ret , $ spf [ $ x ] ) ; if ( $ spf [ $ x ] ) $ x = ( int ) ( $ x / $ spf [ $ x ] ) ; } return $ ret ; } sieve ( ) ; $ x = 12246 ; echo " prime ▁ factorization ▁ for ▁ " . $ x . " ▁ : ▁ " ; $ p = getFactorization ( $ x ) ; for ( $ i = 0 ; $ i < count ( $ p ) ; $ i ++ ) echo $ p [ $ i ] . " ▁ " ; ? >


"Prime Number of Set Bits in Binary Representation | Set 2 | Function to create an array of prime numbers upto number ' n ' ; 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 ; Append all the prime numbers to the list ; Utility function to count the number of set bits ; Driver program ; Here prime numbers are checked till the maximum number of bits possible because that the maximum bit sum possible is the number of bits itself ."
Solution in php:

< ? php function SieveOfEratosthenes ( $ n ) { $ prime = array_fill ( 0 , $ n + 1 , true ) ; for ( $ p = 2 ; $ p * $ p <= $ n ; $ p ++ ) { if ( $ prime [ $ p ] == true ) for ( $ i = $ p * 2 ; $ i < $ n + 1 ; $ i += $ p ) $ prime [ $ i ] = false ; } $ lis = array ( ) ; for ( $ p = 2 ; $ p <= $ n ; $ p ++ ) if ( $ prime [ $ p ] ) array_push ( $ lis , $ p ) ; return $ lis ; } function setBits ( $ n ) { $ cnt = 0 ; while ( $ n ) { if ( $ n & 1 ) $ cnt ++ ; $ n >>= 1 ; } ; return $ cnt ; } $ x = 4 ; $ y = 8 ; $ count = 0 ; $ primeArr = SieveOfEratosthenes ( ceil ( log ( $ y , 2 ) ) ) ; for ( $ i = $ x ; $ i < $ y + 1 ; $ i ++ ) { $ temp = setBits ( $ i ) ; if ( in_array ( $ temp , $ primeArr ) ) $ count += 1 ; } print ( $ count ) ; ? >


"Prime String | Function that checks if sum is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Driver code"
Solution in php:

 < ? php function isPrimeString ( $ str ) { $ len = strlen ( $ str ) ; $ n = 0 ; for ( $ i = 0 ; $ i < $ len ; $ i ++ ) $ n += ( int ) $ str [ $ i ] ; if ( $ n <= 1 ) return false ; if ( $ n <= 3 ) return true ; if ( $ n % 2 == 0 $ n % 3 == 0 ) return false ; for ( $ i = 5 ; $ i * $ i <= $ n ; $ i = $ i + 6 ) if ( $ n % $ i == 0 || $ n % ( $ i + 2 ) == 0 ) return false ; return true ; } $ str = " geekRam " ; if ( isPrimeString ( $ str ) ) echo " Yes " , "
 " ; else echo " No " , "
 " ; ? >


"Prime factors of a big number | function to calculate all the prime factors and count of every prime factor ; count the number of times 2 divides ; equivalent to n = n / 2 ; ; if 2 divides it ; check for all the possible numbers that can divide it ; if n at the end is a prime number . ; Driver Code"
Solution in php:


"Prime numbers after prime P with sum S | vector to store prime and N primes whose sum equals given S ; function to check prime number ; square root of x ; since 1 is not prime number ; if any factor is found return false ; no factor found ; function to display N primes whose sum equals S ; function to evaluate all possible N primes whose sum equals S ; if total equals S And total is reached using N primes ; display the N primes ; if total is greater than S or if index has reached last element ; add prime [ index ] to set vector ; include the ( index ) th prime to total ; remove element from set vector ; exclude ( index ) th prime ; function to generate all primes ; all primes less than S itself ; if i is prime add it to prime vector ; if primes are less than N ; Driver Code"
Solution in php:

 < ? php $ set = array ( ) ; $ prime = array ( ) ; function isPrime ( $ x ) { $ sqroot = sqrt ( $ x ) ; $ flag = true ; if ( $ x == 1 ) return false ; for ( $ i = 2 ; $ i <= $ sqroot ; $ i ++ ) if ( $ x % $ i == 0 ) return false ; return true ; } function display ( ) { global $ set , $ prime ; $ length = count ( $ set ) ; for ( $ i = 0 ; $ i < $ length ; $ i ++ ) echo ( $ set [ $ i ] . " ▁ " ) ; echo ( "
 " ) ; } function primeSum ( $ total , $ N , $ S , $ index ) { global $ set , $ prime ; if ( $ total == $ S && count ( $ set ) == $ N ) { display ( ) ; return ; } if ( $ total > $ S || $ index == count ( $ prime ) ) return ; array_push ( $ set , $ prime [ $ index ] ) ; primeSum ( $ total + $ prime [ $ index ] , $ N , $ S , $ index + 1 ) ; array_pop ( $ set ) ; primeSum ( $ total , $ N , $ S , $ index + 1 ) ; } function allPrime ( $ N , $ S , $ P ) { global $ set , $ prime ; for ( $ i = $ P + 1 ; $ i <= $ S ; $ i ++ ) { if ( isPrime ( $ i ) ) array_push ( $ prime , $ i ) ; } if ( count ( $ prime ) < $ N ) return ; primeSum ( 0 , $ N , $ S , 0 ) ; } $ S = 54 ; $ N = 2 ; $ P = 3 ; allPrime ( $ N , $ S , $ P ) ; ? >


"Prime points ( Points that split a number into two primes ) | Function to count number of digits ; Function to check whether a number is prime or not . Returns 0 if prime else - 1 ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to print prime points ; counting digits ; As single and double digit numbers do not have left and right number pairs ; Finding all left and right pairs . Printing the prime points accordingly . Discarding first and last index point ; Calculating left number ; Calculating right number ; Prime point condition ; No prime point found ; Driver Code"
Solution in php:

< ? php function countDigits ( $ n ) { $ count = 0 ; while ( $ n > 0 ) { $ count ++ ; $ n = ( int ) ( $ n / 10 ) ; } return $ count ; } function checkPrime ( $ n ) { if ( $ n <= 1 ) return -1 ; if ( $ n <= 3 ) return 0 ; if ( $ n % 2 == 0 $ n % 3 == 0 ) return -1 ; for ( $ i = 5 ; $ i * $ i <= $ n ; $ i = $ i + 6 ) if ( $ n % $ i == 0 || $ n % ( $ i + 2 ) == 0 ) return -1 ; return 0 ; } function printPrimePoints ( $ n ) { $ count = countDigits ( $ n ) ; if ( $ count == 1 $ count == 2 ) { echo " - 1" ; return ; } $ found = false ; for ( $ i = 1 ; $ i < ( $ count - 1 ) ; $ i ++ ) { $ left = ( int ) ( $ n / ( ( int ) pow ( 10 , $ count - $ i ) ) ) ; $ right = $ n % ( ( int ) pow ( 10 , $ count - $ i - 1 ) ) ; if ( checkPrime ( $ left ) == 0 && checkPrime ( $ right ) == 0 ) { echo $ i , " " ; $ found = true ; } } if ( $ found == false ) echo " - 1" ; } $ n = 2317 ; printPrimePoints ( $ n ) ; ? >


"Print ' K ' th least significant bit of a number | Function returns 1 if set , 0 if not ; Driver code ; Function call"
Solution in php:

< ? php function LSB ( $ num , $ K ) { return ( $ num & ( 1 << ( $ K - 1 ) ) ) ; } $ num = 10 ; $ K = 4 ; $ r = LSB ( $ num , $ K ) ; if ( $ r ) echo '1' ; else echo '0' ; ? >


"Print Bracket Number | function to print the bracket number ; used to print the bracket number for the left bracket ; used to obtain the bracket number for the right bracket ; traverse the given expression ' exp ' ; if current character is a left bracket ; print ' left _ bnum ' , ; push ' left _ bum ' on to the stack ' right _ bnum ' ; increment ' left _ bnum ' by 1 ; else if current character is a right bracket ; print the top element of stack ' right _ bnum ' it will be the right bracket number ; pop the top element from the stack ; Driver Code"
Solution in php:

< ? php function printBracketNumber ( $ exp , $ n ) { $ left_bnum = 1 ; $ right_bnum = array ( ) ; $ t = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ exp [ $ i ] == ' ( ' ) { echo $ left_bnum . " " ; $ right_bnum [ $ t ++ ] = $ left_bnum ; $ left_bnum ++ ; } else if ( $ exp [ $ i ] == ' ) ' ) { echo $ right_bnum [ $ t - 1 ] . " " ; $ right_bnum [ $ t - 1 ] = 1 ; $ t -- ; } } } $ exp = " ( a + ( b * c ) ) + ( d / e ) " ; $ n = strlen ( $ exp ) ; printBracketNumber ( $ exp , $ n ) ; ? >


"Print Fibonacci Series in reverse order | PHP Program to print Fibonacci series in reverse order ; assigning first and second elements ; storing sum in the preceding location ; printing array in reverse order ; Driver COde"
Solution in php:


"Print Fibonacci sequence using 2 variables | Simple php Program to print Fibonacci sequence ; Driver code"
Solution in php:


"Print N | function to generate n digit numbers ; if number generated ; Append 1 at the current number and reduce the remaining places by one ; If more ones than zeros , append 0 to the current number and reduce the remaining places by one ; Driver Code ; Function call"
Solution in php:

< ? php function printRec ( $ number , $ extraOnes , $ remainingPlaces ) { if ( 0 == $ remainingPlaces ) { echo ( $ number . " " ) ; return ; } printRec ( $ number . "1" , $ extraOnes + 1 , $ remainingPlaces - 1 ) ; if ( 0 < $ extraOnes ) printRec ( $ number . "0" , $ extraOnes - 1 , $ remainingPlaces - 1 ) ; } function printNums ( $ n ) { $ str = " " ; printRec ( $ str , 0 , $ n ) ; } $ n = 4 ; printNums ( $ n ) ;


"Print a case where the given sorting algorithm fails | Function to print a case where the given sorting algorithm fails ; only case where it fails ; Driver Code"
Solution in php:

< ? php function printCase ( $ n ) { if ( $ n <= 2 ) { echo ( -1 ) ; return ; } for ( $ i = $ n ; $ i >= 1 ; $ i -- ) { echo ( $ i ) ; echo ( " ▁ " ) ; } } $ n = 3 ; printCase ( $ n ) ; ? >


"Print a closest string that does not contain adjacent duplicates | Function to print simple string ; If any two adjacent characters are equal ; Initialize it to ' a ' ; Traverse the loop until it is different from the left and right letter . ; Driver Code"
Solution in php:


"Print a matrix in a spiral form starting from a point | PHP program to print a matrix in spiral form . ; Driver code ; Function calling"
Solution in php:

 < ? php $ MAX = 100 ; function printSpiral ( $ mat , $ r , $ c ) { global $ MAX ; $ i ; $ a = 0 ; $ b = 2 ; $ low_row = ( 0 > $ a ) ? 0 : $ a ; $ low_column = ( 0 > $ b ) ? 0 : $ b - 1 ; $ high_row = ( ( $ a + 1 ) >= $ r ) ? $ r - 1 : $ a + 1 ; $ high_column = ( ( $ b + 1 ) >= $ c ) ? $ c - 1 : $ b + 1 ; while ( ( $ low_row > 0 - $ r && $ low_column > 0 - $ c ) ) { for ( $ i = $ low_column + 1 ; $ i <= $ high_column && $ i < $ c && $ low_row >= 0 ; ++ $ i ) echo $ mat [ $ low_row ] [ $ i ] , " ▁ " ; $ low_row -= 1 ; for ( $ i = $ low_row + 2 ; $ i <= $ high_row && $ i < $ r && $ high_column < $ c ; ++ $ i ) echo $ mat [ $ i ] [ $ high_column ] , " ▁ " ; $ high_column += 1 ; for ( $ i = $ high_column - 2 ; $ i >= $ low_column && $ i >= 0 && $ high_row < $ r ; -- $ i ) echo $ mat [ $ high_row ] [ $ i ] , " ▁ " ; $ high_row += 1 ; for ( $ i = $ high_row - 2 ; $ i > $ low_row && $ i >= 0 && $ low_column >= 0 ; -- $ i ) echo $ mat [ $ i ] [ $ low_column ] , " ▁ " ; $ low_column -= 1 ; } echo "
 " ; } $ mat = array ( array ( 1 , 2 , 3 ) , array ( 4 , 5 , 6 ) , array ( 7 , 8 , 9 ) ) ; $ r = 3 ; $ c = 3 ; printSpiral ( $ mat , $ r , $ c ) ; ? >


"Print a number as string of ' A ' and ' B ' in lexicographic order | Function to calculate number of characters in corresponding string of ' A ' and ' B ' ; Since the minimum number of characters will be 1 ; Calculating number of characters ; Since k length string can represent at most pow ( 2 , k + 1 ) - 2 that is if k = 4 , it can represent at most pow ( 2 , 4 + 1 ) - 2 = 30 so we have to calculate the length of the corresponding string ; return the length of the corresponding string ; Function to print corresponding string of ' A ' and ' B ' ; Find length of string ; Since the first number that can be represented by k length string will be ( pow ( 2 , k ) - 2 ) + 1 and it will be AAA ... A , k times , therefore , N will store that how much we have to print ; At a particular time , we have to decide whether we have to print ' A ' or ' B ' , this can be check by calculating the value of pow ( 2 , k - 1 ) ; Print new line ; Driver code"
Solution in php:

 < ? php function no_of_characters ( $ M ) { $ k = 1 ; while ( true ) { if ( pow ( 2 , $ k + 1 ) - 2 < $ M ) $ k ++ ; else break ; } return $ k ; } function print_string ( $ M ) { $ k ; $ num ; $ N ; $ k = no_of_characters ( $ M ) ; $ N = $ M - ( pow ( 2 , $ k ) - 2 ) ; while ( $ k > 0 ) { $ num = pow ( 2 , $ k - 1 ) ; if ( $ num >= $ N ) echo " A " ; else { echo " B " ; $ N -= $ num ; } $ k -- ; } echo "
 " ; } $ M ; $ M = 30 ; print_string ( $ M ) ; $ M = 55 ; print_string ( $ M ) ; $ M = 100 ; print_string ( $ M ) ; ? >


"Print a number containing K digits with digital root D | Function to find a number ; If d is 0 k has to be 1 ; Print k - 1 zeroes ; Driver code"
Solution in php:

< ? php function printNumberWithDR ( $ k , $ d ) { if ( $ d == 0 && $ k != 1 ) echo " - 1" ; else { echo $ d ; $ k -- ; while ( $ k -- ) echo "0" ; } } $ k = 4 ; $ d = 4 ; printNumberWithDR ( $ k , $ d ) ; ? >


"Print a number strictly less than a given number such that all its digits are distinct . | Function to find a number less than n such that all its digits are distinct ; looping through numbers less than n ; initializing a hash array ; creating a copy of i ; initializing variables to compare lengths of digits ; counting frequency of the digits ; checking if each digit is present once ; Driver code"
Solution in php:


"Print all Good numbers in given range | To check whether n is a good number and doesn ' t ▁ contain ▁ digit ▁ ' d '. ; Get last digit and initialize sum from right side ; If last digit is d , return ; Traverse remaining digits ; Current digit ; If digit is d or digit is less than or equal to sum of digits on right side ; Update sum and n ; Print Good numbers in range [ L , R ] ; Traverse all numbers in given range ; If current numbers is good , print it . ; Driver Code ; Print good numbers in [ L , R ]"
Solution in php:

< ? php function isValid ( $ n , $ d ) { $ digit = $ n % 10 ; $ sum = $ digit ; if ( $ digit == $ d ) return false ; $ n = ( int ) ( $ n / 10 ) ; while ( $ n ) { $ digit = $ n % 10 ; if ( $ digit == $ d $ digit <= $ sum ) return false ; else { $ sum += $ digit ; $ n = ( int ) ( $ n / 10 ) ; } } return 1 ; } function printGoodNumbers ( $ L , $ R , $ d ) { for ( $ i = $ L ; $ i <= $ R ; $ i ++ ) { if ( isValid ( $ i , $ d ) ) echo $ i . " " ; } } $ L = 410 ; $ R = 520 ; $ d = 3 ; printGoodNumbers ( $ L , $ R , $ d ) ; ? >


"Print all increasing sequences of length k from first n natural numbers | A utility function to print contents of arr [ 0. . k - 1 ] ; A recursive function to print all increasing sequences of first n natural numbers . Every sequence should be length k . The array arr [ ] is used to store current sequence . ; If length of current increasing sequence becomes k , print it ; Decide the starting number to put at current position : If length is 0 , then there are no previous elements in arr [ ] . So start putting new numbers with 1. If length is not 0 , then start from value of previous element plus 1. ; Increase length ; Put all numbers ( which are greater than the previous element ) at new position . ; This is important . The variable ' len ' is shared among all function calls in recursion tree . Its value must be brought back before next iteration of while loop ; This function prints all increasing sequences of first n natural numbers . The length of every sequence must be k . This function mainly uses printSeqUtil ( ) ; An array to store individual sequences Initial length of ; current sequence ; Driver Code"
Solution in php:

 < ? php function printArr ( $ arr , $ k ) { for ( $ i = 0 ; $ i < $ k ; $ i ++ ) echo $ arr [ $ i ] , " ▁ " ; echo "
 " ; } function printSeqUtil ( $ n , $ k , $ len , $ arr ) { if ( $ len == $ k ) { printArr ( $ arr , $ k ) ; return ; } $ i = ( $ len == 0 ) ? 1 : $ arr [ $ len - 1 ] + 1 ; $ len ++ ; while ( $ i <= $ n ) { $ arr [ $ len - 1 ] = $ i ; printSeqUtil ( $ n , $ k , $ len , $ arr ) ; $ i ++ ; } $ len -- ; } function printSeq ( $ n , $ k ) { $ arr = array ( ) ; $ len = 0 ; printSeqUtil ( $ n , $ k , $ len , $ arr ) ; } $ k = 3 ; $ n = 7 ; printSeq ( $ n , $ k ) ; ? >


"Print all integers that are sum of powers of two given numbers | Function to print powerful integers ; Set is used to store distinct numbers in sorted order ; Store all the powers of y < bound in a vector to avoid calculating them again and again ; x ^ i ; If num is within limits insert it into the set ; Break out of the inner loop ; Adding any number to it will be out of bounds ; Increment i ; Print the contents of the set ; Driver code ; Print powerful integers"
Solution in php:

< ? php function powerfulIntegers ( $ x , $ y , $ bound ) { $ s = array ( ) ; $ powersOfY = array ( ) ; array_push ( $ powersOfY , 1 ) ; $ i = $ y ; while ( $ i < $ bound && $ y != 1 ) { array_push ( $ powersOfY , $ i ) ; $ i *= $ y ; } $ i = 0 ; while ( true ) { $ xPowI = pow ( $ x , $ i ) ; for ( $ j = 0 ; $ j < count ( $ powersOfY ) ; $ j ++ ) { $ num = $ xPowI + $ powersOfY [ $ j ] ; if ( $ num <= $ bound ) array_push ( $ s , $ num ) ; else break ; } if ( $ xPowI >= $ bound $ x == 1 ) break ; $ i += 1 ; } $ s = array_unique ( $ s ) ; sort ( $ s ) ; foreach ( $ s as & $ itr ) print ( $ itr . " " ) ; } $ x = 2 ; $ y = 3 ; $ bound = 10 ; powerfulIntegers ( $ x , $ y , $ bound ) ; ? >