"Numbers with sum of digits equal to the sum of digits of its all prime factor | Java program to Find the count of the numbers in the given range such that the sum of its digit is equal to the sum of all its prime factors digits sum . ; maximum size of number ; array to store smallest prime factor of number ; array to store sum of digits of a number ; boolean array to check given number is countable for required answer or not . ; prefix array to store answer ; Calculating SPF ( SmallestPrime Factor ) for every number till MAXN . ; 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 ; Function to find sum of digits in a number ; find sum of digits of all numbers up to MAXN ; add sum of digits of least prime factor and n / spf [ n ] ; if it is valid make isValid true ; prefix sum to compute answer ; Driver code ; declaration ; print answer for required range ; print answer for required range"
How can the above be solved in Java?

import java . io . * ; class GFG { static int MAXN = 100005 ; static int spf [ ] = new int [ MAXN ] ; static int sum_digits [ ] = new int [ MAXN ] ; static boolean isValid [ ] = new boolean [ MAXN ] ; static int ans [ ] = new int [ MAXN ] ; static void Smallest_prime_factor ( ) { for ( int i = 1 ; i < MAXN ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < MAXN ; i += 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i <= MAXN ; i += 2 ) if ( spf [ i ] == i ) for ( int j = i * i ; j < MAXN ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } static int Digit_Sum ( int copy ) { int d = 0 ; while ( copy > 0 ) { d += copy % 10 ; copy /= 10 ; } return d ; } static void Sum_Of_All_Digits ( ) { for ( int n = 2 ; n < MAXN ; n ++ ) { sum_digits [ n ] = sum_digits [ n / spf [ n ] ] + Digit_Sum ( spf [ n ] ) ; if ( Digit_Sum ( n ) == sum_digits [ n ] ) isValid [ n ] = true ; } for ( int n = 2 ; n < MAXN ; n ++ ) { if ( isValid [ n ] ) ans [ n ] = 1 ; ans [ n ] += ans [ n - 1 ] ; } } public static void main ( String [ ] args ) { Smallest_prime_factor ( ) ; Sum_Of_All_Digits ( ) ; int l , r ; l = 2 ; r = 3 ; System . out . println ( " Valid ▁ numbers ▁ in ▁ the ▁ range ▁ " + l + " ▁ " + r + " ▁ are ▁ " + ( ans [ r ] - ans [ l - 1 ] ) ) ; l = 2 ; r = 10 ; System . out . println ( " Valid ▁ numbers ▁ in ▁ the ▁ range ▁ " + l + " ▁ " + r + " ▁ are ▁ " + ( ans [ r ] - ans [ l - 1 ] ) ) ; } }


"Occurrences of a pattern in binary representation of a number | Java program to find the number of times pattern p occurred in binary representation on n . ; 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"
How can the above be solved in Java?

import java . util . * ; class solution { static int countPattern ( int n , String pat ) { int pattern_int = 0 ; int power_two = 1 ; int all_ones = 0 ; for ( int i = pat . length ( ) - 1 ; i >= 0 ; i -- ) { int current_bit = pat . charAt ( i ) - '0' ; pattern_int += ( power_two * current_bit ) ; all_ones = all_ones + power_two ; power_two = power_two * 2 ; } int count = 0 ; while ( n != 0 && n >= pattern_int ) { if ( ( n & all_ones ) == pattern_int ) { count ++ ; } n = n >> 1 ; } return count ; } public static void main ( String args [ ] ) { int n = 500 ; String pat = "10" ; System . out . println ( countPattern ( n , pat ) ) ; } }


"Octacontagon Number | Java program for above approach ; Finding the nth octacontagon Number ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int octacontagonNum ( int n ) { return ( 78 * n * n - 76 * n ) / 2 ; } public static void main ( String args [ ] ) { int n = 3 ; System . out . print ( "3rd ▁ octacontagon ▁ Number ▁ is ▁ = ▁ " + octacontagonNum ( n ) ) ; } }


"Octadecagonal Number | Java program to find Nth octadecagonal number ; Function to find N - th octadecagonal number ; Formula to calculate nth octadecagonal number ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int Octadecagonal_num ( int n ) { return ( 16 * n * n - 14 * n ) / 2 ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( Octadecagonal_num ( n ) ) ; n = 10 ; System . out . println ( Octadecagonal_num ( n ) ) ; } }


"Octahedral Number | Java program to find nth octahedral number ; Function to find octahedral number ; Formula to calculate nth octahedral number and return it into main function . ; Driver Code ; print result"
How can the above be solved in Java?

import java . io . * ; class GFG { static int octahedral_num ( int n ) { return n * ( 2 * n * n + 1 ) / 3 ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . print ( n + " th ▁ Octahedral " + " ▁ number : ▁ " ) ; System . out . println ( octahedral_num ( n ) ) ; } }


"Octal equivalents of connected components in Binary valued graph | Java implementation to find octal equivalents of all connected components ; Function to traverse the undirected graph using the Depth first traversal ; Marking the visited vertex as true ; Store the connected chain ; Recursive call to the DFS algorithm ; Function to create map between binary number and its equivalent hexadecimal ; Function to return octal equivalent of each connected component ; Length of string before ' . ' ; Add min 0 's in the beginning to make  left substring length divisible by 3 ; If decimal point exists ; Length of string after ' . ' ; Add min 0 's in the end to make right  substring length divisible by 3 ; Create map between binary and its equivalent octal code ; One by one extract from left , substring of size 3 and add its octal code ; If ' . ' is encountered add it to result ; Required octal number ; Function to find the octal equivalents of all connected components ; Initializing boolean array to mark visited vertices ; Following loop invokes DFS algorithm ; Variable to hold temporary length ; Container to store each chain ; DFS algorithm ; Variable to hold each chain size ; Container to store values of vertices of individual chains ; Storing the values of each chain ; Printing binary chain ; Converting the array with vertex values to a binary string ; Printing the octal values ; Driver code ; Initializing graph in the form of adjacency list ; Defining the number of edges and vertices ; Assigning the values for each vertex of the undirected graph ; Constructing the undirected graph"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void depthFirst ( int v , List < List < Integer > > graph , boolean [ ] visited , List < Integer > storeChain ) { visited [ v ] = true ; storeChain . add ( v ) ; for ( int i : graph . get ( v ) ) { if ( visited [ i ] == false ) { depthFirst ( i , graph , visited , storeChain ) ; } } } static void createMap ( Map < String , Character > um ) { um . put ( "000" , '0' ) ; um . put ( "001" , '1' ) ; um . put ( "010" , '2' ) ; um . put ( "011" , '3' ) ; um . put ( "100" , '4' ) ; um . put ( "101" , '5' ) ; um . put ( "110" , '6' ) ; um . put ( "111" , '7' ) ; } static String octal ( String bin ) { int l = bin . length ( ) ; int t = bin . indexOf ( ' . ' ) ; int len_left = t != - 1 ? t : l ; for ( int i = 1 ; i <= ( 3 - len_left % 3 ) % 3 ; i ++ ) bin = '0' + bin ; if ( t != - 1 ) { int len_right = l - len_left - 1 ; for ( int i = 1 ; i <= ( 3 - len_right % 3 ) % 3 ; i ++ ) bin = bin + '0' ; } Map < String , Character > bin_oct_map = new HashMap < String , Character > ( ) ; createMap ( bin_oct_map ) ; int i = 0 ; String octal = " " ; while ( true ) { octal += bin_oct_map . get ( bin . substring ( i , i + 3 ) ) ; i += 3 ; if ( i == bin . length ( ) ) break ; if ( bin . charAt ( i ) == ' . ' ) { octal += ' . ' ; i ++ ; } } return octal ; } static void octalValue ( List < List < Integer > > graph , int vertices , List < Integer > values ) { boolean [ ] visited = new boolean [ 1001 ] ; for ( int i = 1 ; i <= vertices ; i ++ ) { if ( visited [ i ] == false ) { int sizeChain ; List < Integer > storeChain = new ArrayList < Integer > ( ) ; depthFirst ( i , graph , visited , storeChain ) ; sizeChain = storeChain . size ( ) ; int [ ] chainValues = new int [ sizeChain + 1 ] ; for ( int j = 0 ; j < sizeChain ; j ++ ) { int temp = values . get ( storeChain . get ( j ) - 1 ) ; chainValues [ j ] = temp ; } System . out . print ( " Chain ▁ = ▁ " ) ; for ( int j = 0 ; j < sizeChain ; j ++ ) { System . out . print ( chainValues [ j ] + " ▁ " ) ; } System . out . print...


"Odd numbers in N | Java code to find the count of odd numbers in n - th row of Pascal 's Triangle ; 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"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countSetBits ( int n ) { long count = 0 ; while ( n > 0 ) { count += n & 1 ; n >>= 1 ; } return ( int ) count ; } static int countOfOddsPascal ( int n ) { int c = countSetBits ( n ) ; return ( int ) Math . pow ( 2 , c ) ; } public static void main ( String [ ] args ) { int n = 20 ; System . out . println ( countOfOddsPascal ( n ) ) ; } }


"Odious number | Java program to check if a number is Odious Number or not ; Function to get no of set bits in binary representation of passed binary no . Please refer below for details of this function : https : www . geeksforgeeks . org / count - set - bits - in - an - integer / ; Check if number is odious or not ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . math . * ; class GFG { static int countSetBits ( int n ) { int count = 0 ; while ( n != 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } static boolean checkOdious ( int n ) { return ( countSetBits ( n ) % 2 == 1 ) ; } public static void main ( String args [ ] ) { int num = 32 ; if ( checkOdious ( num ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Online algorithm for checking palindrome in a stream | Java program for online algorithm for palindrome checking ; d is the number of characters in input alphabet ; q is a prime number used for evaluating Rabin Karp 's Rolling hash ; Length of input string ; A single character is always a palindrome ; Return if string has only one character ; Initialize first half reverse and second half for as firstr and second characters ; Now check for palindromes from second character onward ; If the hash values of ' firstr ' and ' second ' match , then only check individual characters ; Check if str [ 0. . i ] is palindrome using simple character by character match ; Calculate hash values for next iteration . Don 't calculate hash for next characters  if this is the last character of string ; If i is even ( next i is odd ) ; Add next character after first half at beginning of ' firstr ' ; Add next character after second half at the end of second half . ; If next i is odd ( next i is even ) then we need not to change firstr , we need to remove first character of second and append a character to it . ; Driver program to test above function"
How can the above be solved in Java?

public class GFG { static final int d = 256 ; static final int q = 103 ; static void checkPalindromes ( String str ) { int N = str . length ( ) ; System . out . println ( str . charAt ( 0 ) + " ▁ Yes " ) ; if ( N == 1 ) return ; int firstr = str . charAt ( 0 ) % q ; int second = str . charAt ( 1 ) % q ; int h = 1 , i , j ; for ( i = 1 ; i < N ; i ++ ) { if ( firstr == second ) { for ( j = 0 ; j < i / 2 ; j ++ ) { if ( str . charAt ( j ) != str . charAt ( i - j ) ) break ; } System . out . println ( ( j == i / 2 ) ? str . charAt ( i ) + " ▁ Yes " : str . charAt ( i ) + " ▁ No " ) ; } else System . out . println ( str . charAt ( i ) + " ▁ No " ) ; if ( i != N - 1 ) { if ( i % 2 == 0 ) { h = ( h * d ) % q ; firstr = ( firstr + h * str . charAt ( i / 2 ) ) % q ; second = ( second * d + str . charAt ( i + 1 ) ) % q ; } else { second = ( d * ( second + q - str . charAt ( ( i + 1 ) / 2 ) * h ) % q + str . charAt ( i + 1 ) ) % q ; } } } } public static void main ( String args [ ] ) { String txt = " aabaacaabaa " ; checkPalindromes ( txt ) ; } }


"Optimal Binary Search Tree | DP | A naive recursive implementation of optimal binary search tree problem ; A recursive function to calculate cost of optimal binary search tree ; Base cases if ( j < i ) no elements in this subarray ; one element in this subarray ; Get sum of freq [ i ] , freq [ i + 1 ] , ... freq [ j ] ; Initialize minimum value ; One by one consider all elements as root and recursively find cost of the BST , compare the cost with min and update min if needed ; Return minimum value ; The main function that calculates minimum cost of a Binary Search Tree . It mainly uses optCost ( ) to find the optimal cost . ; Here array keys [ ] is assumed to be sorted in increasing order . If keys [ ] is not sorted , then add code to sort keys , and rearrange freq [ ] accordingly . ; A utility function to get sum of array elements freq [ i ] to freq [ j ] ; Driver code"
How can the above be solved in Java?

public class GFG { static int optCost ( int freq [ ] , int i , int j ) { return 0 ; if ( j == i ) return freq [ i ] ; int fsum = sum ( freq , i , j ) ; int min = Integer . MAX_VALUE ; for ( int r = i ; r <= j ; ++ r ) { int cost = optCost ( freq , i , r - 1 ) + optCost ( freq , r + 1 , j ) ; if ( cost < min ) min = cost ; } return min + fsum ; } static int optimalSearchTree ( int keys [ ] , int freq [ ] , int n ) { return optCost ( freq , 0 , n - 1 ) ; } static int sum ( int freq [ ] , int i , int j ) { int s = 0 ; for ( int k = i ; k <= j ; k ++ ) s += freq [ k ] ; return s ; } public static void main ( String [ ] args ) { int keys [ ] = { 10 , 12 , 20 } ; int freq [ ] = { 34 , 8 , 50 } ; int n = keys . length ; System . out . println ( " Cost ▁ of ▁ Optimal ▁ BST ▁ is ▁ " + optimalSearchTree ( keys , freq , n ) ) ; } }


"Optimal Binary Search Tree | DP | A naive recursive implementation of optimal binary search tree problem ; A utility function to get sum of array elements freq [ i ] to freq [ j ] ; A recursive function to calculate cost of optimal binary search tree ; Base cases no elements in this subarray ; one element in this subarray ; Get sum of freq [ i ] , freq [ i + 1 ] , ... freq [ j ] ; Initialize minimum value ; One by one consider all elements as root and recursively find cost of the BST , compare the cost with min and update min if needed ; Return minimum value ; The main function that calculates minimum cost of a Binary Search Tree . It mainly uses optCost ( ) to find the optimal cost . ; Here array keys [ ] is assumed to be sorted in increasing order . If keys [ ] is not sorted , then add code to sort keys , and rearrange freq [ ] accordingly . ; Driver code"
How can the above be solved in Java?

public class GFG { static int sum ( int freq [ ] , int i , int j ) { int s = 0 ; for ( int k = i ; k <= j ; k ++ ) s += freq [ k ] ; return s ; } static int optCost ( int freq [ ] , int i , int j ) { if ( j < i ) return 0 ; if ( j == i ) return freq [ i ] ; int fsum = sum ( freq , i , j ) ; int min = Integer . MAX_VALUE ; for ( int r = i ; r <= j ; ++ r ) { int cost = optCost ( freq , i , r - 1 ) + optCost ( freq , r + 1 , j ) ; if ( cost < min ) min = cost ; } return min + fsum ; } static int optimalSearchTree ( int keys [ ] , int freq [ ] , int n ) { return optCost ( freq , 0 , n - 1 ) ; } public static void main ( String [ ] args ) { int keys [ ] = { 10 , 12 , 20 } ; int freq [ ] = { 34 , 8 , 50 } ; int n = keys . length ; System . out . println ( " Cost ▁ of ▁ Optimal ▁ BST ▁ is ▁ " + optimalSearchTree ( keys , freq , n ) ) ; } }


"Optimal Binary Search Tree | DP | Dynamic Programming Java code for Optimal Binary Search Tree Problem ; A utility function to get sum of array elements freq [ i ] to freq [ j ] ; A Dynamic Programming based function that calculates minimum cost of a Binary Search Tree . ; Create an auxiliary 2D matrix to store results of subproblems ; For a single key , cost is equal to frequency of the key ; Now we need to consider chains of length 2 , 3 , ... . L is chain length . ; i is row number in cost [ ] [ ] ; Get column number j from row number i and chain length L ; Try making all keys in interval keys [ i . . j ] as root ; c = cost when keys [ r ] becomes root of this subtree ; Driver program to test above functions"
How can the above be solved in Java?

public class Optimal_BST2 { static int sum ( int freq [ ] , int i , int j ) { int s = 0 ; for ( int k = i ; k <= j ; k ++ ) { if ( k >= freq . length ) continue ; s += freq [ k ] ; } return s ; } static int optimalSearchTree ( int keys [ ] , int freq [ ] , int n ) { int cost [ ] [ ] = new int [ n + 1 ] [ n + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) cost [ i ] [ i ] = freq [ i ] ; for ( int L = 2 ; L <= n ; L ++ ) { for ( int i = 0 ; i <= n - L + 1 ; i ++ ) { int j = i + L - 1 ; cost [ i ] [ j ] = Integer . MAX_VALUE ; for ( int r = i ; r <= j ; r ++ ) { int c = ( ( r > i ) ? cost [ i ] [ r - 1 ] : 0 ) + ( ( r < j ) ? cost [ r + 1 ] [ j ] : 0 ) + sum ( freq , i , j ) ; if ( c < cost [ i ] [ j ] ) cost [ i ] [ j ] = c ; } } } return cost [ 0 ] [ n - 1 ] ; } public static void main ( String [ ] args ) { int keys [ ] = { 10 , 12 , 20 } ; int freq [ ] = { 34 , 8 , 50 } ; int n = keys . length ; System . out . println ( " Cost ▁ of ▁ Optimal ▁ BST ▁ is ▁ " + optimalSearchTree ( keys , freq , n ) ) ; } }


"Optimal Storage on Tapes | Java Program to find the order of programs for which MRT is minimized ; This functions outputs the required order and Minimum Retrieval Time ; Here length of i 'th program is L[i] ; Lengths of programs sorted according to increasing lengths . This is the order in which the programs have to be stored on tape for minimum MRT ; MRT - Minimum Retrieval Time ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void findOrderMRT ( int [ ] L , int n ) { Arrays . sort ( L ) ; System . out . print ( " Optimal ▁ order ▁ in ▁ which ▁ " + " programs ▁ are ▁ to ▁ be ▁ stored ▁ is : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( L [ i ] + " ▁ " ) ; System . out . println ( ) ; double MRT = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j <= i ; j ++ ) sum += L [ j ] ; MRT += sum ; } MRT /= n ; System . out . print ( " Minimum ▁ Retrieval ▁ Time " + " ▁ of ▁ this ▁ order ▁ is ▁ " + MRT ) ; } public static void main ( String [ ] args ) { int [ ] L = { 2 , 5 , 4 } ; int n = L . length ; findOrderMRT ( L , n ) ; } }


"Optimal Strategy for a Game | DP | Java program to find out maximum value from a given sequence of coins ; 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 tableis 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 program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int optimalStrategyOfGame ( int arr [ ] , int n ) { int table [ ] [ ] = new int [ n ] [ n ] ; int gap , i , j , x , y , z ; 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 ] = Math . max ( arr [ i ] + Math . min ( x , y ) , arr [ j ] + Math . min ( y , z ) ) ; } } return table [ 0 ] [ n - 1 ] ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 8 , 15 , 3 , 7 } ; int n = arr1 . length ; System . out . println ( " " + optimalStrategyOfGame ( arr1 , n ) ) ; int arr2 [ ] = { 2 , 2 , 2 , 2 } ; n = arr2 . length ; System . out . println ( " " + optimalStrategyOfGame ( arr2 , n ) ) ; int arr3 [ ] = { 20 , 30 , 2 , 2 , 2 , 10 } ; n = arr3 . length ; System . out . println ( " " + optimalStrategyOfGame ( arr3 , n ) ) ; } }


"Optimal Strategy for a Game | Set 2 | Java program to find out maximum value from a given sequence of coins ; For both of your choices , the opponent gives you total sum minus maximum of his value ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Compute sum of elements ; Initialize memoization table ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int MAX = 100 ; static int [ ] [ ] memo = new int [ MAX ] [ MAX ] ; static int oSRec ( int arr [ ] , int i , int j , int sum ) { if ( j == i + 1 ) return Math . max ( arr [ i ] , arr [ j ] ) ; if ( memo [ i ] [ j ] != - 1 ) return memo [ i ] [ j ] ; memo [ i ] [ j ] = Math . max ( ( sum - oSRec ( arr , i + 1 , j , sum - arr [ i ] ) ) , ( sum - oSRec ( arr , i , j - 1 , sum - arr [ j ] ) ) ) ; return memo [ i ] [ j ] ; } static int accumulate ( int [ ] arr , int start , int end ) { int sum = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) sum += arr [ i ] ; return sum ; } static int optimalStrategyOfGame ( int [ ] arr , int n ) { int sum = 0 ; sum = accumulate ( arr , 0 , n ) ; for ( int j = 0 ; j < MAX ; j ++ ) { for ( int k = 0 ; k < MAX ; k ++ ) memo [ j ] [ k ] = - 1 ; } return oSRec ( arr , 0 , n - 1 , sum ) ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 8 , 15 , 3 , 7 } ; int n = arr1 . length ; System . out . printf ( "%d
", optimalStrategyOfGame ( arr1 , n ) ) ; int arr2 [ ] = { 2 , 2 , 2 , 2 } ; n = arr2 . length ; System . out . printf ( "%d
", optimalStrategyOfGame ( arr2 , n ) ) ; int arr3 [ ] = { 20 , 30 , 2 , 2 , 2 , 10 } ; n = arr3 . length ; System . out . printf ( "%d
", optimalStrategyOfGame ( arr3 , n ) ) ; } }


"Optimal Strategy for a Game | Set 2 | Java program to find out maximum value from a given sequence of coins ; For both of your choices , the opponent gives you total sum minus maximum of his value ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int oSRec ( int [ ] arr , int i , int j , int sum ) { if ( j == i + 1 ) return Math . max ( arr [ i ] , arr [ j ] ) ; return Math . max ( ( sum - oSRec ( arr , i + 1 , j , sum - arr [ i ] ) ) , ( sum - oSRec ( arr , i , j - 1 , sum - arr [ j ] ) ) ) ; } static int optimalStrategyOfGame ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } return oSRec ( arr , 0 , n - 1 , sum ) ; } static public void main ( String [ ] args ) { int [ ] arr1 = { 8 , 15 , 3 , 7 } ; int n = arr1 . length ; System . out . println ( optimalStrategyOfGame ( arr1 , n ) ) ; int [ ] arr2 = { 2 , 2 , 2 , 2 } ; n = arr2 . length ; System . out . println ( optimalStrategyOfGame ( arr2 , n ) ) ; int [ ] arr3 = { 20 , 30 , 2 , 2 , 2 , 10 } ; n = arr3 . length ; System . out . println ( optimalStrategyOfGame ( arr3 , n ) ) ; } }


"Optimal Strategy for a Game | Special Gold Coin | Java implementation of the approach ; Function to return the winner of the game ; To store the count of silver coins ; Update the position of the gold coin ; First player will win the game ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String getWinner ( String str , int len ) { int total = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( str . charAt ( i ) == ' S ' ) { total ++ ; } } if ( ( total % 2 ) == 1 ) return " First " ; return " Second " ; } public static void main ( String [ ] args ) { String str = " GSSS " ; int len = str . length ( ) ; System . out . println ( getWinner ( str , len ) ) ; } }


"Optimal Strategy for the Divisor game using Dynamic Programming | Java program for implementation of optimal strategy for the divisor game using dynamic programming ; Recursive function to find the winner ; Check if N = 1 or N = 3 then player B wins ; Check if N = 2 then player A wins ; Check if current state already visited then return the previously obtained ans ; Check if currently it is player A 's turn  then initialise the ans to 0 ; Traversing across all the divisors of N which are less than N ; Check if current value of i is a divisor of N ; Check if it is player A 's turn  then we need at least one true ; Else if it is player B 's turn  then we need at least one false ; Return the current ans ; Driver code ; Initialise N"
How can the above be solved in Java?

import java . util . * ; class GFG { static int divisorGame ( int N , int A , int dp [ ] [ ] ) { if ( N == 1 N == 3 ) return 0 ; if ( N == 2 ) return 1 ; if ( dp [ N ] [ A ] != - 1 ) return dp [ N ] [ A ] ; int ans = ( A == 1 ) ? 0 : 1 ; for ( int i = 1 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { if ( A == 1 ) ans |= divisorGame ( N - i , 0 , dp ) ; else ans &= divisorGame ( N - i , 1 , dp ) ; } } return dp [ N ] [ A ] = ans ; } public static void main ( String [ ] args ) { int N = 3 ; int [ ] [ ] dp = new int [ N + 1 ] [ 2 ] ; for ( int i = 0 ; i < N + 1 ; i ++ ) { for ( int j = 0 ; j < 2 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } if ( divisorGame ( N , 1 , dp ) == 1 ) System . out . print ( " Player ▁ A ▁ wins " ) ; else System . out . print ( " Player ▁ B ▁ wins " ) ; } }


"Optimal strategy for a Game with modifications | Java implementation of the above approach ; Function to return sum of subarray from l to r ; calculate sum by a loop from l to r ; dp to store the values of sub problems ; if length of the array is less than k return the sum ; if the value is previously calculated ; else calculate the value ; select all the sub array of length len_r ; get the sum of that sub array ; check if it is the maximum or not ; store it in the table ; Driver code"
How can the above be solved in Java?

class GFG { static int sum ( int arr [ ] , int l , int r ) { int s = 0 ; for ( int i = l ; i <= r ; i ++ ) { s += arr [ i ] ; } return s ; } static int dp [ ] [ ] [ ] = new int [ 101 ] [ 101 ] [ 101 ] ; static int solve ( int arr [ ] , int l , int r , int k ) { if ( r - l + 1 <= k ) return sum ( arr , l , r ) ; if ( dp [ l ] [ r ] [ k ] != 0 ) return dp [ l ] [ r ] [ k ] ; int sum_ = sum ( arr , l , r ) ; int len_r = ( r - l + 1 ) - k ; int len = ( r - l + 1 ) ; int ans = 0 ; for ( int i = 0 ; i < len - len_r + 1 ; i ++ ) { int sum_sub = sum ( arr , i + l , i + l + len_r - 1 ) ; ans = Math . max ( ans , ( sum_ - sum_sub ) + ( sum_sub - solve ( arr , i + l , i + l + len_r - 1 , k ) ) ) ; } dp [ l ] [ r ] [ k ] = ans ; return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 15 , 20 , 9 , 2 , 5 } , k = 2 ; int n = arr . length ; System . out . println ( solve ( arr , 0 , n - 1 , k ) ) ; } }


"Optimally accommodate 0 s and 1 s from a Binary String into K buckets | Java implementation of the approach ; 2 - D dp array saving different states dp [ i ] [ j ] = minimum value of accommodation till i 'th index of the string using j+1 number of buckets. ; Function to find the minimum required sum using dynamic programming ; If both start and bucket reached end then return 0 else that arrangement is not possible so return INT_MAX ; Corner case ; If state if already calculated then return its answer ; Start filling zeroes and ones which to be accommodated in jth bucket then ans for current arrangement will be ones * zeroes + recur ( i + 1 , bucket + 1 ) ; If this arrangement is not possible then don 't calculate further ; Function to initialize the dp and call solveUtil ( ) method to get the answer ; Start with 0 - th index and 1 bucket ; Driver code ; K buckets"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int [ ] [ ] dp ; static int solveUtil ( int start , int bucket , String str , int K ) { int N = str . length ( ) ; if ( start == N ) { if ( bucket == K ) { return 0 ; } return Integer . MAX_VALUE ; } if ( bucket == K ) { return Integer . MAX_VALUE ; } if ( dp [ start ] [ bucket ] != - 1 ) { return dp [ start ] [ bucket ] ; } int zeroes = 0 ; int ones = 0 ; int ans = Integer . MAX_VALUE ; for ( int i = start ; i < N ; ++ i ) { if ( str . charAt ( i ) == '1' ) { ones ++ ; } else { zeroes ++ ; } if ( ones * zeroes > ans ) { break ; } int temp = solveUtil ( i + 1 , bucket + 1 , str , K ) ; if ( temp != Integer . MAX_VALUE ) { ans = Math . min ( ans , temp + ( ones * zeroes ) ) ; } } return dp [ start ] [ bucket ] = ans ; } static int solve ( String str , int K ) { int N = str . length ( ) ; dp = new int [ N ] [ K ] ; for ( int [ ] row : dp ) { Arrays . fill ( row , - 1 ) ; } int ans = solveUtil ( 0 , 0 , str , K ) ; return ans == Integer . MAX_VALUE ? - 1 : ans ; } public static void main ( String [ ] args ) { String S = "0101" ; int K = 2 ; System . out . println ( solve ( S , K ) ) ; } }


"Optimally accommodate 0 s and 1 s from a Binary String into K buckets | Java implementation of the approach ; Function to find the minimum required sum using dynamic programming ; dp [ i ] [ j ] = minimum val of accommodation till j 'th index of the string  using i+1 number of buckets.  Final ans will be in dp[n-1][K-1] ; Corner cases ; Filling first row , if only 1 bucket then simple count number of zeros and ones and do the multiplication ; If k = 0 then this arrangement is not possible ; If no arrangement is possible then our answer will remain INT_MAX so return - 1 ; Driver code ; K buckets"
How can the above be solved in Java?

class GFG { static long solve ( String str , int K ) { int n = str . length ( ) ; long dp [ ] [ ] = new long [ K ] [ n ] ; if ( n < K ) return - 1 ; else if ( n == K ) return 0 ; long zeroes = 0 , ones = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == '0' ) zeroes ++ ; else ones ++ ; dp [ 0 ] [ i ] = ones * zeroes ; } for ( int s = 1 ; s < K ; s ++ ) { for ( int i = 0 ; i < n ; i ++ ) { dp [ s ] [ i ] = Integer . MAX_VALUE ; ones = 0 ; zeroes = 0 ; for ( int k = i ; k >= 0 ; k -- ) { if ( str . charAt ( k ) == '0' ) zeroes ++ ; else ones ++ ; dp [ s ] [ i ] = Math . min ( dp [ s ] [ i ] , + ( ( k - 1 >= 0 ) ? ones * zeroes + dp [ s - 1 ] [ k - 1 ] : Integer . MAX_VALUE ) ) ; } } } return ( dp [ K - 1 ] [ n - 1 ] == Integer . MAX_VALUE ) ? - 1 : dp [ K - 1 ] [ n - 1 ] ; } public static void main ( String [ ] args ) { String S = "0101" ; int K = 2 ; System . out . println ( solve ( S , K ) ) ; } }


"Optimized Euler Totient Function for Multiple Evaluations | Java 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 ) ; Driver code ; preprocess all prime numbers upto 10 ^ 5"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 100001 ; static ArrayList < Integer > p = new ArrayList < Integer > ( ) ; static void sieve ( ) { int [ ] isPrime = new int [ MAX + 1 ] ; for ( int i = 2 ; i <= MAX ; i ++ ) { if ( isPrime [ i ] == 0 ) { p . add ( i ) ; for ( int j = 2 ; i * j <= MAX ; j ++ ) isPrime [ i * j ] = 1 ; } } } static int phi ( int n ) { int res = n ; for ( int i = 0 ; p . get ( i ) * p . get ( i ) <= n ; i ++ ) { if ( n % p . get ( i ) == 0 ) { res -= ( res / p . get ( i ) ) ; while ( n % p . get ( i ) == 0 ) n /= p . get ( i ) ; } } if ( n > 1 ) res -= ( res / n ) ; return res ; } public static void main ( String [ ] args ) { sieve ( ) ; System . out . println ( phi ( 11 ) ) ; System . out . println ( phi ( 21 ) ) ; System . out . println ( phi ( 31 ) ) ; System . out . println ( phi ( 41 ) ) ; System . out . println ( phi ( 51 ) ) ; System . out . println ( phi ( 61 ) ) ; System . out . println ( phi ( 91 ) ) ; System . out . println ( phi ( 101 ) ) ; } }


"Optimized Naive Algorithm for Pattern Searching | Java program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if ( j == M ) if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver code"
How can the above be solved in Java?

class GFG { static void search ( String pat , String txt ) { int M = pat . length ( ) ; int N = txt . length ( ) ; int i = 0 ; while ( i <= N - M ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt . charAt ( i + j ) != pat . charAt ( j ) ) break ; { System . out . println ( " Pattern ▁ found ▁ at ▁ index ▁ " + i ) ; i = i + M ; } else if ( j == 0 ) i = i + 1 ; else i = i + j ; } } public static void main ( String [ ] args ) { String txt = " ABCEABCDABCEABCD " ; String pat = " ABCD " ; search ( pat , txt ) ; } }


"Optimized Naive Algorithm for Pattern Searching | Java program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; 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"
How can the above be solved in Java?

class GFG { static void search ( String pat , String txt ) { int M = pat . length ( ) ; int N = txt . length ( ) ; int i = 0 ; while ( i <= N - M ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt . charAt ( i + j ) != pat . charAt ( j ) ) break ; if ( j == M ) { System . out . println ( " Pattern ▁ found ▁ at ▁ index ▁ " + i ) ; i = i + M ; } else if ( j == 0 ) i = i + 1 ; else i = i + j ; } } public static void main ( String [ ] args ) { String txt = " ABCEABCDABCEABCD " ; String pat = " ABCD " ; search ( pat , txt ) ; } }


"Optimum location of point to minimize total distance | A Java program to find optimum location and total cost ; structure defining a point ; structure defining a line of ax + by + c = 0 form ; method to get distance of point ( x , y ) from point p ; Utility method to compute total distance all points when choose point on given line has x - coordinate value as X ; calculating Y of chosen point by line equation ; Utility method to find minimum total distance ; loop until difference between low and high become less than EPS ; mid1 and mid2 are representative x co - ordiantes of search space ; if mid2 point gives more total distance , skip third part ; if mid1 point gives more total distance , skip first part ; compute optimum distance cost by sending average of low and high as X ; method to find optimum cost ; converting 2D array input to point array ; Driver Code"
How can the above be solved in Java?

class GFG { static double sq ( double x ) { return ( ( x ) * ( x ) ) ; } static int EPS = ( int ) ( 1e-6 ) + 1 ; static int N = 5 ; static class point { int x , y ; point ( ) { } public point ( int x , int y ) { this . x = x ; this . y = y ; } } ; static class line { int a , b , c ; public line ( int a , int b , int c ) { this . a = a ; this . b = b ; this . c = c ; } } ; static double dist ( double x , double y , point p ) { return Math . sqrt ( sq ( x - p . x ) + sq ( y - p . y ) ) ; } static double compute ( point p [ ] , int n , line l , double X ) { double res = 0 ; double Y = - 1 * ( l . c + l . a * X ) / l . b ; for ( int i = 0 ; i < n ; i ++ ) res += dist ( X , Y , p [ i ] ) ; return res ; } static double findOptimumCostUtil ( point p [ ] , int n , line l ) { double low = - 1e6 ; double high = 1e6 ; while ( ( high - low ) > EPS ) { double mid1 = low + ( high - low ) / 3 ; double mid2 = high - ( high - low ) / 3 ; double dist1 = compute ( p , n , l , mid1 ) ; double dist2 = compute ( p , n , l , mid2 ) ; if ( dist1 < dist2 ) high = mid2 ; else low = mid1 ; } return compute ( p , n , l , ( low + high ) / 2 ) ; } static double findOptimumCost ( int points [ ] [ ] , line l ) { point [ ] p = new point [ N ] ; for ( int i = 0 ; i < N ; i ++ ) p [ i ] = new point ( points [ i ] [ 0 ] , points [ i ] [ 1 ] ) ; return findOptimumCostUtil ( p , N , l ) ; } public static void main ( String [ ] args ) { line l = new line ( 1 , - 1 , - 3 ) ; int points [ ] [ ] = { { - 3 , - 2 } , { - 1 , 0 } , { - 1 , 2 } , { 1 , 2 } , { 3 , 4 } } ; System . out . println ( findOptimumCost ( points , l ) ) ; } }


"Orbit counting theorem or Burnside 's Lemma | Java program for implementing the Orbit counting theorem or Burnside 's Lemma ; Function to find result using Orbit counting theorem or Burnside 's Lemma ; According to Burnside 's Lemma  calculate distinct ways for each  rotation ; Find GCD ; Divide By N ; Print the distinct ways ; Driver Code ; N stones and M colors ; Function call"
How can the above be solved in Java?

class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static void countDistinctWays ( int N , int M ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int K = gcd ( i , N ) ; ans += Math . pow ( M , K ) ; } ans /= N ; System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int N = 4 , M = 3 ; countDistinctWays ( N , M ) ; } }


"Order of indices which is lexicographically smallest and sum of elements is <= X | Java implementation of the approach ; Function to return the chosen indices ; Maximum indices chosen ; Try to replace the first element in ans by i , making the order lexicographically smaller ; If no further replacement possible return ; If found an index smaller than ind and sum not exceeding X then remove index of smallest value from ans and then add index i to ans ; Driver code ; Print the chosen indices"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Integer > solve ( int X , Vector < Integer > A ) { int min = Integer . MAX_VALUE ; int ind = - 1 ; for ( int i = 0 ; i < A . size ( ) ; i ++ ) { if ( A . get ( i ) < min ) { min = A . get ( i ) ; ind = i ; } } int maxIndChosen = X / min ; Vector < Integer > ans = new Vector < > ( ) ; if ( maxIndChosen == 0 ) { return ans ; } for ( int i = 0 ; i < maxIndChosen ; i ++ ) { ans . add ( ind ) ; } int temp = maxIndChosen ; int sum = maxIndChosen * A . get ( ind ) ; for ( int i = 0 ; i < ind ; i ++ ) { if ( sum - X == 0 temp == 0 ) break ; while ( ( sum - A . get ( ind ) + A . get ( i ) ) <= X && temp != 0 ) { ans . remove ( 0 ) ; ans . add ( i ) ; temp -- ; sum += ( A . get ( i ) - A . get ( ind ) ) ; } } Collections . sort ( ans ) ; return ans ; } public static void main ( String args [ ] ) { Integer arr [ ] = { 5 , 6 , 4 , 8 } ; Vector < Integer > A = new Vector < Integer > ( Arrays . asList ( arr ) ) ; int X = 18 ; Vector < Integer > ans = solve ( X , A ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) System . out . print ( ans . get ( i ) + " ▁ " ) ; } }


"Ordered Prime Signature | JAVA to find total number of divisors of a number , using ordered prime signature ; Finding primes upto entered number ; Finding primes by Sieve of Eratosthenes method ; If prime [ i ] is not changed , then it is prime ; Update all multiples of p ; Forming array of the prime numbers found ; Finding ordered prime signature of the number ; Map to store prime factors and the related exponents ; Declaring an iterator for map ; Finding prime factorization of the number ; Storing the prime factor and its exponent in map ; Storing the exponent in a vector ; Sorting the stored exponents ; Printing the prime signature ; Finding total number of divisors of the number ; Adding one to each element present ; Multiplying the elements ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static Vector < Integer > primes ( int n ) { boolean [ ] prime = new boolean [ n + 1 ] ; Arrays . fill ( prime , true ) ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( prime [ i ] == true ) { for ( int j = i * 2 ; j <= n ; j += i ) prime [ j ] = false ; } } Vector < Integer > arr = new Vector < > ( ) ; for ( int i = 2 ; i <= n ; i ++ ) { if ( prime [ i ] ) arr . add ( i ) ; } return arr ; } static Vector < Integer > signature ( int n ) { Vector < Integer > r = primes ( n ) ; HashMap < Integer , Integer > factor = new HashMap < > ( ) ; HashMap < Integer , Integer > :: iterator it ; Vector < Integer > sort_exp = new Vector < > ( ) ; int k , t = n ; int it = 0 ; for ( int i = 0 ; i < r . size ( ) ; i ++ ) { if ( n % r . get ( i ) == 0 ) { k = 0 ; while ( n % r . get ( i ) == 0 ) { n = n / r . get ( i ) ; k ++ ; } factor . put ( r . get ( i ) , k ) ; sort_exp . add ( k ) ; } } Collections . sort ( sort_exp ) ; System . out . print ( " ▁ The ▁ Ordered ▁ Prime ▁ Signature ▁ of ▁ " + t + " is :  { "); for ( int i = 0 ; i < sort_exp . size ( ) ; i ++ ) { if ( i != sort_exp . size ( ) - 1 ) System . out . print ( sort_exp . get ( i ) + " , ▁ " ) ; else System . out . print ( sort_exp . get ( i ) + " }
"); } return sort_exp ; } static void divisors ( int n ) { int f = 1 , l ; Vector < Integer > div = signature ( n ) ; l = div . size ( ) ; for ( int i = 0 ; i < l ; i ++ ) { f *= ( div . get ( i ) + 1 ) ; } System . out . print ( " The ▁ total ▁ number ▁ of ▁ divisors ▁ of ▁ " + n + " ▁ is ▁ " + f + "
"); } public static void main ( String [ ] args ) { int n = 13 ; divisors ( n ) ; } }


"Ormiston prime Pairs | Java implementation to check Ormiston prime ; Function to check if the number is a prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to update the frequency array such that freq [ i ] stores the frequency of digit i in n ; While there are digits left to process ; Update the frequency of the current digit ; Remove the last digit ; Function that returns true if a and b are anagrams of each other ; To store the frequencies of the digits in a and b ; Update the frequency of the digits in a ; Update the frequency of the digits in b ; Match the frequencies of the common digits ; If frequency differs for any digit then the numbers are not anagrams of each other ; Returns true if n1 and n2 are Ormiston primes ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } static int TEN = 10 ; static void updateFreq ( int n , int freq [ ] ) { while ( n > 0 ) { int digit = n % TEN ; freq [ digit ] ++ ; n /= TEN ; } } static boolean areAnagrams ( int a , int b ) { int freqA [ ] = new int [ TEN ] ; int freqB [ ] = new int [ TEN ] ; updateFreq ( a , freqA ) ; updateFreq ( b , freqB ) ; for ( int i = 0 ; i < TEN ; i ++ ) { if ( freqA [ i ] != freqB [ i ] ) return false ; } return true ; } static boolean OrmistonPrime ( int n1 , int n2 ) { return ( isPrime ( n1 ) && isPrime ( n2 ) && areAnagrams ( n1 , n2 ) ) ; } public static void main ( String [ ] args ) { int n1 = 1913 , n2 = 1931 ; if ( OrmistonPrime ( n1 , n2 ) ) System . out . print ( " YES " + "
"); else System . out . print ( " NO " + "
"); } }


"Overall percentage change from successive changes | Java implementation of above approach ; Calculate successive change of 1 st 2 change ; Calculate successive change for rest of the value ; Driver code ; Calling function"
How can the above be solved in Java?

import java . io . * ; class GFG { static float successiveChange ( int arr [ ] , int N ) { float var1 , var2 , result = 0 ; var1 = arr [ 0 ] ; var2 = arr [ 1 ] ; result = var1 + var2 + ( ( var1 * var2 ) / 100 ) ; for ( int i = 2 ; i < N ; i ++ ) result = result + arr [ i ] + ( ( result * arr [ i ] ) / 100 ) ; return result ; } public static void main ( String [ ] args ) { int [ ] arr = { 10 , 20 , 30 , 10 } ; int N = arr . length ; float result = successiveChange ( arr , N ) ; System . out . println ( " Percentage ▁ change ▁ is ▁ = ▁ " + result + " ▁ % " ) ; } }


"P | Java program to check if a number is a p - smooth number or not ; 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 program to test above function"
How can the above be solved in Java?

import java . lang . * ; class GFG { static boolean check ( int n , int p ) { int maximum = - 1 ; while ( ( n % 2 ) == 0 ) { maximum = Math . max ( maximum , 2 ) ; n = n / 2 ; } for ( int i = 3 ; i <= Math . sqrt ( n ) ; i += 2 ) { while ( n % i == 0 ) { maximum = Math . max ( maximum , i ) ; n = n / i ; } } if ( n > 2 ) maximum = Math . max ( maximum , n ) ; return ( maximum <= p ) ; } public static void main ( String [ ] args ) { int n = 24 , p = 7 ; if ( check ( n , p ) ) System . out . println ( " yes " ) ; else System . out . println ( " no " ) ; } }


"Padovan Sequence | Java program to find n 'th term in Padovan Sequence using Dynamic Programming ; Function to calculate padovan number P ( n ) ; int [ ] padv = new int [ n ] ; create array to store padovan values ; Driver Program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int pad ( int n ) { padv [ 0 ] = padv [ 1 ] = padv [ 2 ] = 1 ; for ( int i = 3 ; i <= n ; i ++ ) { padv [ i ] = padv [ i - 2 ] + padv [ i - 3 ] ; } return padv [ n - 1 ] ; } public static void main ( String args [ ] ) { int n = 12 ; System . out . println ( pad ( n ) ) ; } }


"Painting Fence Algorithm | Java program for 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"
How can the above be solved in Java?

class GFG { static long countWays ( int n , int k ) { long total = k ; int mod = 1000000007 ; int same = 0 , diff = k ; for ( int i = 2 ; i <= n ; i ++ ) { same = diff ; diff = ( int ) total * ( k - 1 ) ; diff = diff % mod ; total = ( same + diff ) % mod ; } return total ; } public static void main ( String [ ] args ) { int n = 3 , k = 2 ; System . out . println ( countWays ( n , k ) ) ; } }


"Pair of fibonacci numbers with a given sum and minimum absolute difference | Java program to find the pair of Fibonacci numbers with a given sum and minimum absolute difference ; Hash to store all the Fibonacci numbers ; Function to generate fibonacci Series and create hash table to check Fibonacci numbers ; Adding the first two Fibonacci numbers into the Hash set ; Computing the remaining Fibonacci numbers based on the previous two numbers ; Function to find the pair of Fibonacci numbers with the given sum and minimum absolute difference ; Start from N / 2 such that the difference between i and N - i will be minimum ; If both ' i ' and ' sum ▁ - ▁ i ' are fibonacci numbers then print them and break the loop ; If there is no Fibonacci pair possible ; Driver code ; Generate the Fibonacci numbers ; Find the Fibonacci pair"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 1000005 ; static Set < Integer > fib = new HashSet < Integer > ( ) ; static void fibonacci ( ) { int prev = 0 , curr = 1 , len = 2 ; fib . add ( prev ) ; fib . add ( curr ) ; while ( len <= MAX ) { int temp = curr + prev ; fib . add ( temp ) ; prev = curr ; curr = temp ; len ++ ; } } static void findFibonacci ( int N ) { for ( int i = N / 2 ; i > 1 ; i -- ) { if ( fib . contains ( i ) && fib . contains ( N - i ) ) { System . out . println ( i + " ▁ " + ( N - i ) ) ; return ; } } System . out . println ( " - 1" ) ; } public static void main ( String args [ ] ) { fibonacci ( ) ; int sum = 199 ; findFibonacci ( sum ) ; } }


"Pair of integers ( a , b ) which satisfy the given equations | Java program to count the pair of integers ( a , b ) which satisfy the equation a ^ 2 + b = n and a + b ^ 2 = m ; Function to count valid pairs ; Driver code"
How can the above be solved in Java?

 class GFG { static int pairCount ( int n , int m ) { int cnt = 0 , b , a ; for ( b = 0 ; b <= Math . sqrt ( m ) ; b ++ ) { a = m - b * b ; if ( a * a + b == n ) { cnt ++ ; } } return cnt ; } public static void main ( String [ ] args ) { int n = 9 , m = 3 ; System . out . print ( pairCount ( n , m ) + "
"); } }


"Pair of integers having difference of their fifth power as X | Java implementation to find a pair of integers A & B such that difference of fifth power is equal to the given number X ; Function to find a pair of integers A & B such that difference of fifth power is equal to the given number X ; Loop to choose every possible pair with in the range ; Check if equation holds ; Driver Code ; Function Call"
How can the above be solved in Java?

 class GFG { static void findPair ( int x ) { int lim = 120 ; for ( int i = - lim ; i <= lim ; i ++ ) { for ( int j = - lim ; j <= lim ; j ++ ) { if ( Math . pow ( i , 5 ) - Math . pow ( j , 5 ) == x ) { System . out . print ( i + " ▁ " + j + "
"); return ; } } } System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int X = 33 ; findPair ( X ) ; } }


"Pair of integers having least GCD among all given pairs having GCD exceeding K | Java program for the above approach ; Function to calculate the GCD of two numbers ; Function to print the pair having a gcd value just greater than the given integer ; Initialize variables ; Iterate until low less than equal to high ; Calculate mid ; Reducing the search space ; Print the answer ; Driver Code ; Given array and K ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int GCD ( int a , int b ) { if ( b == 0 ) { return a ; } return GCD ( b , a % b ) ; } static void GcdPair ( int [ ] [ ] arr , int k ) { int lo = 0 , hi = arr . length - 1 , mid ; int [ ] ans = { - 1 , 0 } ; while ( lo <= hi ) { mid = lo + ( hi - lo ) / 2 ; if ( GCD ( arr [ mid ] [ 0 ] , arr [ mid ] [ 1 ] ) > k ) { ans = arr [ mid ] ; hi = mid - 1 ; } else lo = mid + 1 ; } if ( ans [ 0 ] == - 1 ) System . out . print ( " - 1" ) ; else System . out . print ( " ( ▁ " + ans [ 0 ] + " , ▁ " + ans [ 1 ] + " ▁ ) " ) ; return ; } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 3 , 6 } , { 15 , 30 } , { 25 , 75 } , { 30 , 120 } } ; int K = 16 ; GcdPair ( arr , K ) ; } }


"Pair of integers with difference K having an element as the K | Java program to implement the above problem ; Function to find the required pair ; No pair possible ; Driver Code"
How can the above be solved in Java?

 class GFG { static void computePair ( double K ) { if ( K == 1 ) { System . out . print ( " No " ) ; return ; } else { System . out . print ( K * K / ( K - 1 ) + " ▁ " ) ; System . out . print ( K / ( K - 1 ) + "
"); } } public static void main ( String [ ] args ) { double K = 6 ; computePair ( K ) ; } }


"Pair of strings having longest common prefix of maximum length in given array | Java program for the above approach ; class of Trie ; Function to insert a string into Trie ; Stores length of the string ; Traverse the string str ; If str [ i ] is not present in current path of Trie ; Create a new node of Trie ; Update root ; Function to find the maximum length of longest common prefix in Trie with str ; Stores length of str ; Stores length of longest common prefix in Trie with str ; Traverse the string str ; If str [ i ] is present in the current path of Trie ; Update len ; Update root ; Function to print the pair having maximum length of the longest common prefix ; Stores index of the string having maximum length of longest common prefix ; Stores maximum length of longest common prefix . ; Create root node of Trie ; Insert arr [ 0 ] into Trie ; Traverse the array . ; Stores maximum length of longest common prefix in Trie with arr [ i ] ; If temp is greater than len ; Update len ; Update idx ; Traverse array arr [ ] ; Stores length of arr [ i ] ; Check if maximum length of longest common prefix > M ; Traverse string arr [ i ] and arr [ j ] ; If current character of both string does not match . ; Print pairs having maximum length of the longest common prefix ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class TrieNode { TrieNode [ ] child = new TrieNode [ 256 ] ; TrieNode ( ) { } } class GFG { private static void insertTrie ( TrieNode root , String str ) { int M = str . length ( ) ; for ( int i = 0 ; i < M ; i ++ ) { if ( root . child [ str . charAt ( i ) ] == null ) { root . child [ str . charAt ( i ) ] = new TrieNode ( ) ; } root = root . child [ str . charAt ( i ) ] ; } } private static int findStrLen ( TrieNode root , String str ) { int M = str . length ( ) ; int len = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( root . child [ str . charAt ( i ) ] != null ) { len ++ ; root = root . child [ str . charAt ( i ) ] ; } else { return len ; } } return len ; } private static void findMaxLenPair ( List < String > arr , int N ) { int idx = - 1 ; int len = 0 ; TrieNode root = new TrieNode ( ) ; insertTrie ( root , arr . get ( 0 ) ) ; for ( int i = 1 ; i < N ; i ++ ) { int temp = findStrLen ( root , arr . get ( i ) ) ; if ( temp > len ) { len = temp ; idx = i ; } insertTrie ( root , arr . get ( i ) ) ; } for ( int i = 0 ; i < N ; i ++ ) { int M = arr . get ( i ) . length ( ) ; if ( i != idx && M >= len ) { boolean found = true ; for ( int j = 0 ; j < len ; j ++ ) { if ( arr . get ( i ) . charAt ( j ) != arr . get ( idx ) . charAt ( j ) ) { found = false ; break ; } } if ( found ) { System . out . println ( " ( " + arr . get ( i ) + " , ▁ " + arr . get ( idx ) + " ) " ) ; return ; } } } } public static void main ( String [ ] args ) { List < String > arr = Arrays . asList ( new String [ ] { " geeksforgeeks " , " geeks " , " geeksforcse " } ) ; int N = arr . size ( ) ; findMaxLenPair ( arr , N ) ; } }


"Pair with given product | Set 1 ( Find if any pair exists ) | Java program if there exists a pair for given product ; Returns true if there is a pair in arr [ 0. . n - 1 ] with product equal to x . ; Create an empty set and insert first element into it ; Traverse remaining elements ; 0 case must be handles explicitly as x % 0 is undefined ; x / arr [ i ] exists in hash , then we found a pair ; Insert arr [ i ] ; driver code"
How can the above be solved in Java?

import java . util . HashSet ; class GFG { static boolean isProduct ( int arr [ ] , int n , int x ) { HashSet < Integer > hset = new HashSet < > ( ) ; if ( n < 2 ) return false ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) { if ( x == 0 ) return true ; else continue ; } if ( x % arr [ i ] == 0 ) { if ( hset . contains ( x / arr [ i ] ) ) return true ; hset . add ( arr [ i ] ) ; } } return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 20 , 9 , 40 } ; int x = 400 ; int n = arr . length ; if ( isProduct ( arr , arr . length , x ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; x = 190 ; if ( isProduct ( arr , arr . length , x ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Pair with given product | Set 1 ( Find if any pair exists ) | Java program to find if there is a pair with given product . ; 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"
How can the above be solved in Java?

class GFG { boolean isProduct ( int arr [ ] , int n , int x ) { for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] * arr [ j ] == x ) return true ; return false ; } public static void main ( String [ ] args ) { GFG g = new GFG ( ) ; int arr [ ] = { 10 , 20 , 9 , 40 } ; int x = 400 ; int n = arr . length ; if ( g . isProduct ( arr , n , x ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; x = 190 ; if ( g . isProduct ( arr , n , x ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Pair with given sum and maximum shortest distance from end | Java code to find maximum shortest distance from endpoints ; Store counts of all elements . ; function to find maximum shortest distance ; stores the shortest distance of every element in original array . ; shortest distance from ends ; if duplicates are found , b [ x ] is replaced with minimum of the previous and current position 's  shortest distance ; similar elements ignore them cause we need distinct elements ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void makePermutation ( int [ ] a , int n ) { HashMap < Integer , Integer > count = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( count . containsKey ( a [ i ] ) ) { count . put ( a [ i ] , count . get ( a [ i ] ) + 1 ) ; } else { count . put ( a [ i ] , 1 ) ; } } } static int find_maximum ( int a [ ] , int n , int k ) { HashMap < Integer , Integer > b = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int x = a [ i ] ; int d = Math . min ( 1 + i , n - i ) ; if ( ! b . containsKey ( x ) ) b . put ( x , d ) ; else { b . put ( x , Math . min ( d , b . get ( x ) ) ) ; } } int ans = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { int x = a [ i ] ; if ( x != k - x && b . containsKey ( k - x ) ) ans = Math . min ( Math . max ( b . get ( x ) , b . get ( k - x ) ) , ans ) ; } return ans ; } public static void main ( String [ ] args ) { int a [ ] = { 3 , 5 , 8 , 6 , 7 } ; int K = 11 ; int n = a . length ; System . out . println ( find_maximum ( a , n , K ) ) ; } }


"Pair with largest sum which is less than K in the array | Java program to find pair with largest sum which is less than K in the array ; Function to find pair with largest sum which is less than K in the array ; To store the break point ; Sort the given array ; Find the break point ; No need to look beyond i 'th index ; Find the required pair ; Print the required answer ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void Max_Sum ( int arr [ ] , int n , int k ) { int p = n ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] >= k ) { p = i ; break ; } } int maxsum = 0 , a = 0 , b = 0 ; for ( int i = 0 ; i < p ; i ++ ) { for ( int j = i + 1 ; j < p ; j ++ ) { if ( arr [ i ] + arr [ j ] < k && arr [ i ] + arr [ j ] > maxsum ) { maxsum = arr [ i ] + arr [ j ] ; a = arr [ i ] ; b = arr [ j ] ; } } } System . out . print ( a + " ▁ " + b ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 20 , 110 , 100 , 10 } ; int k = 85 ; int n = arr . length ; Max_Sum ( arr , n , k ) ; } }


"Pair with maximum GCD from two arrays | Java program to find maximum GCD pair 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 ."
How can the above be solved in Java?

class GFG { static void gcdMax ( int [ ] a , int [ ] b , int n , int N ) { int [ ] cnt = new int [ N ] ; int [ ] first = new int [ N ] ; int [ ] second = new int [ N ] ; for ( int i = 0 ; i < n ; ++ i ) cnt [ a [ i ] ] = 1 ; for ( int i = 1 ; i < N ; ++ i ) for ( int j = i ; j < N ; j += i ) if ( cnt [ j ] > 0 ) first [ i ] = Math . max ( first [ i ] , j ) ; cnt = new int [ N ] ; for ( int i = 0 ; i < n ; ++ i ) cnt [ b [ i ] ] = 1 ; for ( int i = 1 ; i < N ; ++ i ) for ( int j = i ; j < N ; j += i ) if ( cnt [ j ] > 0 ) second [ i ] = Math . max ( second [ i ] , j ) ; int x ; for ( x = N - 1 ; x >= 0 ; x -- ) if ( first [ x ] > 0 && second [ x ] > 0 ) break ; System . out . println ( first [ x ] + " ▁ " + second [ x ] ) ; } public static void main ( String [ ] args ) { int [ ] a = { 3 , 1 , 4 , 2 , 8 } ; int [ ] b = { 5 , 2 , 12 , 8 , 3 } ; int n = a . length ; int N = 20 ; gcdMax ( a , b , n , N ) ; } }


"Pair with min absolute difference and whose product is N + 1 or N + 2 | Java program for the above approach ; Function to print pair ( a , b ) such that a * b = N + 1 or N + 2 ; Loop to iterate over the desired possible values ; Check for condition 1 ; Check for condition 2 ; Driver Code ; Given Number ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void closestDivisors ( int n ) { for ( int i = ( int ) Math . sqrt ( n + 2 ) ; i > 0 ; i -- ) { if ( ( n + 1 ) % i == 0 ) { System . out . print ( i + " , ▁ " + ( n + 1 ) / i ) ; break ; } if ( ( n + 2 ) % i == 0 ) { System . out . print ( i + " , ▁ " + ( n + 2 ) / i ) ; break ; } } } public static void main ( String [ ] args ) { int N = 123 ; closestDivisors ( N ) ; } }


"Pairs from an array that satisfy the given condition | Java implementation of the approach ; 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"
How can the above be solved in Java?

import java . io . * ; class GFG { static int setBits ( int n ) { int count = 0 ; while ( n > 0 ) { n = n & ( n - 1 ) ; count ++ ; } return count ; } static int countPairs ( int a [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int setbits_x = setBits ( a [ i ] ) ; for ( int j = i + 1 ; j < n ; j ++ ) { int setbits_y = setBits ( a [ j ] ) ; int setbits_xor_xy = setBits ( a [ i ] ^ a [ j ] ) ; if ( setbits_x + setbits_y == setbits_xor_xy ) count ++ ; } } return count ; } public static void main ( String [ ] args ) { int [ ] a = { 2 , 3 , 4 , 5 , 6 } ; int n = a . length ; System . out . println ( countPairs ( a , n ) ) ; } }


"Pairs of Amicable Numbers | Efficient Java program to count Amicable pairs in an array . ; Calculate the sum of proper divisors ; 1 is a proper divisor ; To handle perfect squares ; Check if pair is amicable ; This function prints count of amicable pairs present in the input array ; Map to store the numbers ; Iterate through each number , and find the sum of proper divisors and check if it 's  also present in the array ; It 's sum of proper divisors ; As the pairs are counted twice , thus divide by 2 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int sumOfDiv ( int x ) { int sum = 1 ; for ( int i = 2 ; i <= Math . sqrt ( x ) ; i ++ ) { if ( x % i == 0 ) { sum += i ; if ( x / i != i ) sum += x / i ; } } return sum ; } static boolean isAmicable ( int a , int b ) { return ( sumOfDiv ( a ) == b && sumOfDiv ( b ) == a ) ; } static int countPairs ( int arr [ ] , int n ) { HashSet < Integer > s = new HashSet < Integer > ( ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) s . add ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . contains ( sumOfDiv ( arr [ i ] ) ) ) { int sum = sumOfDiv ( arr [ i ] ) ; if ( isAmicable ( arr [ i ] , sum ) ) count ++ ; } } return count / 2 ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 220 , 284 , 1184 , 1210 , 2 , 5 } ; int n1 = arr1 . length ; System . out . println ( countPairs ( arr1 , n1 ) ) ; int arr2 [ ] = { 2620 , 2924 , 5020 , 5564 , 6232 , 6368 } ; int n2 = arr2 . length ; System . out . println ( countPairs ( arr2 , n2 ) ) ; } }


"Pairs of Positive Negative values in an array | Java program to find pairs of positive and negative values present in an array . ; Print pair with negative and positive value ; For each element of array . ; Try to find the negative value of arr [ i ] from i + 1 to n ; If absolute values are equal print pair . ; If size of vector is 0 , therefore there is no element with positive negative value , print "0" ; Sort the vector ; Print the pair with negative positive value . ; Driven Program"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { public static void printPairs ( int arr [ ] , int n ) { Vector < Integer > v = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( Math . abs ( arr [ i ] ) == Math . abs ( arr [ j ] ) ) v . add ( Math . abs ( arr [ i ] ) ) ; if ( v . size ( ) == 0 ) return ; Collections . sort ( v ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) System . out . print ( - v . get ( i ) + " ▁ " + v . get ( i ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 } ; int n = arr . length ; printPairs ( arr , n ) ; } }


"Pairs of strings which on concatenating contains each character of " string " | Java implementation of the above 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"
How can the above be solved in Java?

class GFG { static int MAX = 64 ; static int getBitmask ( char [ ] s ) { int temp = 0 ; for ( int j = 0 ; j < s . length ; j ++ ) { switch ( s [ j ] ) { case ' s ' : temp = temp | ( 1 ) ; break ; case ' t ' : temp = temp | ( 2 ) ; break ; case ' r ' : temp = temp | ( 4 ) ; break ; case ' i ' : temp = temp | ( 8 ) ; break ; case ' n ' : temp = temp | ( 16 ) ; break ; case ' g ' : temp = temp | ( 32 ) ; break ; default : break ; } } return temp ; } static int countPairs ( String arr [ ] , int n ) { int [ ] bitMask = new int [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) bitMask [ getBitmask ( arr [ i ] . toCharArray ( ) ) ] ++ ; int cnt = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = i ; j < MAX ; j ++ ) { if ( ( i j ) == ( MAX - 1 ) ) { if ( i == j ) cnt += ( ( bitMask [ i ] * bitMask [ i ] - 1 ) / 2 ) ; else cnt += ( bitMask [ i ] * bitMask [ j ] ) ; } } } return cnt ; } public static void main ( String [ ] args ) { String arr [ ] = { " strrr " , " string " , " gstrin " } ; int n = arr . length ; System . out . println ( countPairs ( arr , n ) ) ; } }


"Pairs such that one is a power multiple of other | Java program to find pairs count ; 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 program"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int countPairs ( int A [ ] , int n , int k ) { int ans = 0 ; Arrays . sort ( A ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int x = 0 ; while ( ( A [ i ] * Math . pow ( k , x ) ) <= A [ j ] ) { if ( ( A [ i ] * Math . pow ( k , x ) ) == A [ j ] ) { ans ++ ; break ; } x ++ ; } } } return ans ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 8 , 9 , 12 , 18 , 4 , 24 , 2 , 6 } ; int n = A . length ; int k = 3 ; System . out . println ( countPairs ( A , n , k ) ) ; } }


"Pairs whose concatenation contain all digits | Java Program to find number of pairs whose concatenation contains all digits from 0 to 9. ; Function to return number of pairs whose concatenation contain all digits from 0 to 9 ; making the mask for each of the number . ; for each of the possible pair which can make OR value equal to 1023 ; finding the count of pair from the given numbers . ; Driver Code"
How can the above be solved in Java?

 class GFG { static final int N = 20 ; static int countPair ( char str [ ] [ ] , int n ) { int [ ] cnt = new int [ 1 << 10 ] ; for ( int i = 0 ; i < n ; i ++ ) { int mask = 0 ; for ( int j = 0 ; j < str [ i ] . length ; ++ j ) mask |= ( 1 << ( str [ i ] [ j ] - '0' ) ) ; cnt [ mask ] ++ ; } int ans = 0 ; for ( int m1 = 0 ; m1 <= 1023 ; m1 ++ ) for ( int m2 = 0 ; m2 <= 1023 ; m2 ++ ) if ( ( m1 m2 ) == 1023 ) { ans += ( ( m1 == m2 ) ? ( cnt [ m1 ] * ( cnt [ m1 ] - 1 ) ) : ( cnt [ m1 ] * cnt [ m2 ] ) ) ; } return ans / 2 ; } public static void main ( String [ ] args ) { int n = 5 ; char str [ ] [ ] = { "129300455" . toCharArray ( ) , "5559948277" . toCharArray ( ) , "012334556" . toCharArray ( ) , "56789" . toCharArray ( ) , "123456879" . toCharArray ( ) } ; System . out . print ( countPair ( str , n ) + "
"); } }


"Pairs with Difference less than K | Java 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"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static int countPairs ( int a [ ] , int n , int k ) { Arrays . sort ( a ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int j = i + 1 ; while ( j < n && a [ j ] - a [ i ] < k ) { res ++ ; j ++ ; } } return res ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 10 , 4 , 2 } ; int k = 3 ; int n = a . length ; System . out . println ( countPairs ( a , n , k ) ) ; } }


"Pairs with Difference less than K | java code to find count of Pairs with difference less than K . ; Function to count pairs ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countPairs ( int a [ ] , int n , int k ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( Math . abs ( a [ j ] - a [ i ] ) < k ) res ++ ; return res ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 10 , 4 , 2 } ; int k = 3 ; int n = a . length ; System . out . println ( countPairs ( a , n , k ) ) ; } }


"Pairs with GCD equal to one in the given range | Java program to print all pairs ; Function to print all pairs ; check if even ; We can print all adjacent pairs for ( int i = l ; i < r ; i += 2 ) { System . out . print ( " { " + i + " , ▁ " + i + 1 + " } , ▁ " ) ; } ; Driver Code"
How can the above be solved in Java?

class GFG { static boolean checkPairs ( int l , int r ) { if ( ( l - r ) % 2 == 0 ) return false ; return true ; } public static void main ( String [ ] args ) { int l = 1 , r = 8 ; if ( checkPairs ( l , r ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Pairwise swap elements of a given linked list | Recursive function to pairwise swap elements of a linked list ; There must be at - least two nodes in the list ; Swap the node 's data with data of next node  ; Call pairWiseSwap ( ) for rest of the list"
How can the above be solved in Java?

static void pairWiseSwap ( node head ) { if ( head != null && head . next != null ) { swap ( head . data , head . next . data ) ; pairWiseSwap ( head . next . next ) ; } }


"Palindrome Partitioning | DP |  ; minCut function ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int minCut ( String a ) { int [ ] cut = new int [ a . length ( ) ] ; boolean [ ] [ ] palindrome = new boolean [ a . length ( ) ] [ a . length ( ) ] ; for ( int i = 0 ; i < a . length ( ) ; i ++ ) { int minCut = i ; for ( int j = 0 ; j <= i ; j ++ ) { if ( a . charAt ( i ) == a . charAt ( j ) && ( i - j < 2 palindrome [ j + 1 ] [ i - 1 ] ) ) { palindrome [ j ] [ i ] = true ; minCut = Math . min ( minCut , j == 0 ? 0 : ( cut [ j - 1 ] + 1 ) ) ; } } cut [ i ] = minCut ; } return cut [ a . length ( ) - 1 ] ; } public static void main ( String [ ] args ) { System . out . println ( minCut ( " aab " ) ) ; System . out . println ( minCut ( " aabababaxx " ) ) ; } }


"Palindrome Partitioning | DP | Driver code"
How can the above be solved in Java?


"Palindrome Partitioning | DP | Java Code for Palindrome Partitioning Problem ; Driver code"
How can the above be solved in Java?

public class GFG { static boolean isPalindrome ( String string , int i , int j ) { while ( i < j ) { if ( string . charAt ( i ) != string . charAt ( j ) ) return false ; i ++ ; j -- ; } return true ; } static int minPalPartion ( String string , int i , int j ) { if ( i >= j || isPalindrome ( string , i , j ) ) return 0 ; int ans = Integer . MAX_VALUE , count ; for ( int k = i ; k < j ; k ++ ) { count = minPalPartion ( string , i , k ) + minPalPartion ( string , k + 1 , j ) + 1 ; ans = Math . min ( ans , count ) ; } return ans ; } public static void main ( String args [ ] ) { String str = " ababbbabbababa " ; System . out . println ( " Min ▁ cuts ▁ needed ▁ for ▁ " + " Palindrome ▁ Partitioning ▁ is ▁ " + minPalPartion ( str , 0 , str . length ( ) - 1 ) ) ; } }


"Palindrome Partitioning | DP | Java Code for Palindrome Partitioning Problem ; 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 ; different looping variables ; Every substring of length 1 is a palindrome ; L is substring length . Build the solution in 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 localtion 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 above function"
How can the above be solved in Java?

public class GFG { static int minPalPartion ( String str ) { int n = str . length ( ) ; int [ ] [ ] C = new int [ n ] [ n ] ; boolean [ ] [ ] P = new boolean [ n ] [ n ] ; int i , j , k , L ; 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 . charAt ( i ) == str . charAt ( j ) ) ; else P [ i ] [ j ] = ( str . charAt ( i ) == str . charAt ( j ) ) && P [ i + 1 ] [ j - 1 ] ; if ( P [ i ] [ j ] == true ) C [ i ] [ j ] = 0 ; else { C [ i ] [ j ] = Integer . MAX_VALUE ; for ( k = i ; k <= j - 1 ; k ++ ) C [ i ] [ j ] = Integer . min ( C [ i ] [ j ] , C [ i ] [ k ] + C [ k + 1 ] [ j ] + 1 ) ; } } } return C [ 0 ] [ n - 1 ] ; } public static void main ( String args [ ] ) { String str = " ababbbabbababa " ; System . out . println ( " Min ▁ cuts ▁ needed ▁ for ▁ " + " Palindrome ▁ Partitioning ▁ is ▁ " + minPalPartion ( str ) ) ; } }


"Palindrome Substring Queries | A Java program to answer queries to check whether the substrings are palindrome or not efficiently ; Structure to represent a query . A query consists of ( L , R ) and we have to answer whether the substring from index - L to R is a palindrome or not ; A function to check if a string str is palindrome in the ranfe L to R ; Keep comparing characters while they are same ; A Function to find pow ( base , exponent ) % MOD in log ( exponent ) time ; A Function to calculate Modulo Multiplicative Inverse of ' n ' ; A Function to calculate the prefix hash ; A Function to calculate the suffix hash Suffix hash is nothing but the prefix hash of the reversed string ; A Function to answer the Queries ; Hash Value of Substring [ L , R ] ; Reverse Hash Value of Substring [ L , R ] ; If both are equal then the substring is a palindrome ; A Dynamic Programming Based Approach to compute the powers of 101 ; 101 ^ 0 = 1 ; Driver code ; A Table to store the powers of 101 ; Arrays to hold prefix and suffix hash values ; Compute Prefix Hash and Suffix Hash Arrays"
How can the above be solved in Java?

 public class GFG { static int p = 101 ; static int MOD = 1000000007 ; static class Query { int L , R ; public Query ( int L , int R ) { this . L = L ; this . R = R ; } } ; static boolean isPalindrome ( String str , int L , int R ) { while ( R > L ) { if ( str . charAt ( L ++ ) != str . charAt ( R -- ) ) { return ( false ) ; } } return ( true ) ; } static int modPow ( int base , int exponent ) { if ( exponent == 0 ) { return 1 ; } if ( exponent == 1 ) { return base ; } int temp = modPow ( base , exponent / 2 ) ; if ( exponent % 2 == 0 ) { return ( temp % MOD * temp % MOD ) % MOD ; } else { return ( ( ( temp % MOD * temp % MOD ) % MOD ) * base % MOD ) % MOD ; } } static int findMMI ( int n ) { return modPow ( n , MOD - 2 ) ; } static void computePrefixHash ( String str , int n , int prefix [ ] , int power [ ] ) { prefix [ 0 ] = 0 ; prefix [ 1 ] = str . charAt ( 0 ) ; for ( int i = 2 ; i <= n ; i ++ ) { prefix [ i ] = ( prefix [ i - 1 ] % MOD + ( str . charAt ( i - 1 ) % MOD * power [ i - 1 ] % MOD ) % MOD ) % MOD ; } return ; } static void computeSuffixHash ( String str , int n , int suffix [ ] , int power [ ] ) { suffix [ 0 ] = 0 ; suffix [ 1 ] = str . charAt ( n - 1 ) ; for ( int i = n - 2 , j = 2 ; i >= 0 && j <= n ; i -- , j ++ ) { suffix [ j ] = ( suffix [ j - 1 ] % MOD + ( str . charAt ( i ) % MOD * power [ j - 1 ] % MOD ) % MOD ) % MOD ; } return ; } static void queryResults ( String str , Query q [ ] , int m , int n , int prefix [ ] , int suffix [ ] , int power [ ] ) { for ( int i = 0 ; i <= m - 1 ; i ++ ) { int L = q [ i ] . L ; int R = q [ i ] . R ; long hash_LR = ( ( prefix [ R + 1 ] - prefix [ L ] + MOD ) % MOD * findMMI ( power [ L ] ) % MOD ) % MOD ; long reverse_hash_LR = ( ( suffix [ n - L ] - suffix [ n - R - 1 ] + MOD ) % MOD * findMMI ( power [ n - R - 1 ] ) % MOD ) % MOD ; if ( hash_LR == reverse_hash_LR ) { if ( isPalindrome ( str , L , R ) == true ) { System . out . printf ( " The ▁ Substring ▁ [ % d ▁ % d ] ▁ is ▁ a ▁ " + "palindrome
", L, R); } else { System . out . printf ( " The ▁...


"Palindrome by swapping only one character | Java program palindrome by swapping only one character ; convert the string to character array ; counts the number of differences which prevents the string from being palindrome . ; keeps a record of the characters that prevents the string from being palindrome . ; loops from the start of a string till the midpoint of the string ; difference is encountered preventing the string from being palindrome ; 3 rd differences encountered and its no longer possible to make is palindrome by one swap ; record the different character ; store the different characters ; its already palindrome ; only one difference is found ; if the middleChar matches either of the difference producing characters , return true ; two differences are found ; if the characters contained in the two sets are same , return true ; Driver code"
How can the above be solved in Java?

class GFG { public static boolean isPalindromePossible ( String input ) { int len = input . length ( ) , i ; char [ ] charStr = input . toCharArray ( ) ; int diffCount = 0 ; char [ ] [ ] diff = new char [ 2 ] [ 2 ] ; for ( i = 0 ; i < len / 2 ; i ++ ) { if ( charStr [ i ] != charStr [ len - i - 1 ] ) { if ( diffCount == 2 ) return false ; diff [ diffCount ] [ 0 ] = charStr [ i ] ; diff [ diffCount ++ ] [ 1 ] = charStr [ len - i - 1 ] ; } } switch ( diffCount ) { case 0 : return true ; case 1 : char midChar = charStr [ i ] ; if ( len % 2 != 0 && ( diff [ 0 ] [ 0 ] == midChar diff [ 0 ] [ 1 ] == midChar ) ) return true ; case 2 : if ( ( diff [ 0 ] [ 0 ] == diff [ 1 ] [ 0 ] && diff [ 0 ] [ 1 ] == diff [ 1 ] [ 1 ] ) || ( diff [ 0 ] [ 0 ] == diff [ 1 ] [ 1 ] && diff [ 0 ] [ 1 ] == diff [ 1 ] [ 0 ] ) ) return true ; } return false ; } public static void main ( String [ ] args ) { System . out . println ( isPalindromePossible ( " bbg " ) ) ; System . out . println ( isPalindromePossible ( " bdababd " ) ) ; System . out . println ( isPalindromePossible ( " gcagac " ) ) ; } }


"Palindrome pair in an array of words ( or strings ) | Java program to check if there is a pair that of above method using Trie ; Alphabet size ( # of symbols ) ; Trie node ; List < Integer > pos ; To store palindromic positions in str ; isLeaf is true if the node represents end of a word ; constructor ; Utility function to check if a string is a palindrome ; compare each character from starting with its corresponding character from last ; If not present , inserts reverse of key into Trie . If the key is prefix of a Trie node , just mark leaf node ; Start traversing word from the last ; If it is not available in Trie , then store it ; If current word is palindrome till this level , store index of current word . ; mark last node as leaf ; list to store result ; Returns true if key presents in Trie , else false ; If it is present also check upto which index it is palindrome ; If not present then return ; Function to check if a palindrome pair exists ; Construct trie ; Search for different keys ; Driver code"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; public class Palin_pair2 { static final int ALPHABET_SIZE = 26 ; static class TrieNode { TrieNode [ ] children = new TrieNode [ ALPHABET_SIZE ] ; int id ; boolean isLeaf ; public TrieNode ( ) { isLeaf = false ; pos = new ArrayList < > ( ) ; for ( int i = 0 ; i < ALPHABET_SIZE ; i ++ ) children [ i ] = null ; } } static boolean isPalindrome ( String str , int i , int len ) { while ( i < len ) { if ( str . charAt ( i ) != str . charAt ( len ) ) return false ; i ++ ; len -- ; } return true ; } static void insert ( TrieNode root , String key , int id ) { TrieNode pCrawl = root ; for ( int level = key . length ( ) - 1 ; level >= 0 ; level -- ) { int index = key . charAt ( level ) - ' a ' ; if ( pCrawl . children [ index ] == null ) pCrawl . children [ index ] = new TrieNode ( ) ; if ( isPalindrome ( key , 0 , level ) ) ( pCrawl . pos ) . add ( id ) ; pCrawl = pCrawl . children [ index ] ; } pCrawl . id = id ; pCrawl . pos . add ( id ) ; pCrawl . isLeaf = true ; } static List < List < Integer > > result ; static void search ( TrieNode root , String key , int id ) { TrieNode pCrawl = root ; for ( int level = 0 ; level < key . length ( ) ; level ++ ) { int index = key . charAt ( level ) - ' a ' ; if ( pCrawl . id >= 0 && pCrawl . id != id && isPalindrome ( key , level , key . length ( ) - 1 ) ) { List < Integer > l = new ArrayList < > ( ) ; l . add ( id ) ; l . add ( pCrawl . id ) ; result . add ( l ) ; } if ( pCrawl . children [ index ] == null ) return ; pCrawl = pCrawl . children [ index ] ; } for ( int i : pCrawl . pos ) { if ( i == id ) continue ; List < Integer > l = new ArrayList < > ( ) ; l . add ( id ) ; l . add ( i ) ; result . add ( l ) ; } } static boolean checkPalindromePair ( List < String > vect ) { TrieNode root = new TrieNode ( ) ; for ( int i = 0 ; i < vect . size ( ) ; i ++ ) insert ( root , vect . get ( i ) , i ) ; result = new ArrayList < > ( ) ; for ( int i = 0 ; i < vect . size ( ) ; i ++ ) { search (...


"Palindrome pair in an array of words ( or strings ) | Java program to find if there is a pair that can form a palindrome . ; Utility function to check if a string is a palindrome ; compare each character from starting with its corresponding character from last ; Function to check if a palindrome pair exists ; Consider each pair one by one ; concatenate both strings ; check if the concatenated string is palindrome ; check if the concatenated string is palindrome ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; import java . util . List ; public class Palin_pair1 { static boolean isPalindrome ( String str ) { int len = str . length ( ) ; for ( int i = 0 ; i < len / 2 ; i ++ ) if ( str . charAt ( i ) != str . charAt ( len - i - 1 ) ) return false ; return true ; } static boolean checkPalindromePair ( List < String > vect ) { for ( int i = 0 ; i < vect . size ( ) - 1 ; i ++ ) { for ( int j = i + 1 ; j < vect . size ( ) ; j ++ ) { String check_str = " " ; check_str = check_str + vect . get ( i ) + vect . get ( j ) ; if ( isPalindrome ( check_str ) ) return true ; check_str = vect . get ( j ) + vect . get ( i ) ; if ( isPalindrome ( check_str ) ) return true ; } } return false ; } public static void main ( String args [ ] ) { List < String > vect = Arrays . asList ( " geekf " , " geeks " , " or " , " keeg " , " abc " , " bc " ) ; if ( checkPalindromePair ( vect ) == true ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Palindromic Primes | Java Program to print all palindromic primes smaller than or equal to n . ; 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.  int 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 function"
How can the above be solved in Java?

 import java . util . * ; class GFG { static boolean oneDigit ( int num ) { return ( num >= 0 && num < 10 ) ; } static boolean isPalUtil ( int num , int dupNum ) { if ( oneDigit ( num ) ) return ( num == ( dupNum ) % 10 ) ; if ( ! isPalUtil ( num / 10 , dupNum ) ) return false ; dupNum /= 10 ; return ( num % 10 == ( dupNum ) % 10 ) ; } static boolean isPal ( int num ) { if ( num < 0 ) num = - num ; return isPalUtil ( num , dupNum ) ; } static void printPalPrimesLessThanN ( int n ) { boolean prime [ ] = new boolean [ n + 1 ] ; Arrays . fill ( prime , true ) ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= n ; i += p ) { prime [ i ] = false ; } } } for ( int p = 2 ; p <= n ; p ++ ) { if ( prime [ p ] && isPal ( p ) ) { System . out . print ( p + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int n = 100 ; System . out . printf ( " Palindromic ▁ primes ▁ smaller ▁ than ▁ or ▁ " + "equal to %d are :
", n); printPalPrimesLessThanN ( n ) ; } }


"Palindromic Selfie Numbers | Java program to find palindromic selfie numbers ; To store all permutations of digits in the number ; int number ; input number ; Function to reverse the digits of a number ; Append it at the beg ; num = num / 10 ; Reduce number until 0 ; Function to check palindromic selfie ; Length of the number required for calculating all permutations of the digits ; Remove the number and its palindrome from the obtained set as this is the LHS of multiplicative equality ; Iterate over all other numbers ; Check for equality x * palin ( x ) = y * palin ( y ) ; flag = true ; Answer found ; If no such number found ; Function to get all possible possible permutations of the digits in num ; Adds the new permutation obtained in the set ; Swap digits to get a different ordering ; Recurse to next pair of digits ; num = swap ( num , l , i ) ; Swap back ; Function that swaps the digits i and j in the num ; Convert int to char array ; Swap the ith and jth character ; Convert back to int and return ; Driver Function ; First example , input = 145572 ; Second example , input = 19362 ; Third example , input = 4669"
How can the above be solved in Java?

import java . util . * ; public class palindrome_selfie { Set < Integer > all_permutes = new HashSet < Integer > ( ) ; public palindrome_selfie ( int num ) { number = num ; } public int palindrome ( int num ) { int reversednum = 0 ; int d ; while ( num > 0 ) { reversednum = reversednum * 10 + d ; } return reversednum ; } public void palin_selfie ( ) { int l = String . valueOf ( number ) . length ( ) - 1 ; all_permutes . remove ( palindrome ( number ) ) ; all_permutes . remove ( number ) ; Iterator it = all_permutes . iterator ( ) ; while ( it . hasNext ( ) ) { int number2 = ( int ) it . next ( ) ; if ( number * palindrome ( number ) == number2 * palindrome ( number2 ) ) { System . out . println ( " Palindrome ▁ multiplicative " + " selfie ▁ of ▁ " + number + " ▁ is ▁ : ▁ " + number2 ) ; break ; } } if ( flag == false ) { System . out . println ( " Given ▁ number ▁ has ▁ no ▁ palindrome ▁ selfie . " ) ; } } public void permute ( int num , int l , int r ) { if ( l == r ) all_permutes . add ( num ) ; else { for ( int i = l ; i <= r ; i ++ ) { num = swap ( num , l , i ) ; permute ( num , l + 1 , r ) ; } } } public int swap ( int num , int i , int j ) { char temp ; char [ ] charArray = String . valueOf ( num ) . toCharArray ( ) ; temp = charArray [ i ] ; charArray [ i ] = charArray [ j ] ; charArray [ j ] = temp ; return Integer . valueOf ( String . valueOf ( charArray ) ) ; } public static void main ( String args [ ] ) { palindrome_selfie example1 = new palindrome_selfie ( 145572 ) ; example1 . palin_selfie ( ) ; palindrome_selfie example2 = new palindrome_selfie ( 19362 ) ; example2 . palin_selfie ( ) ; palindrome_selfie example3 = new palindrome_selfie ( 4669 ) ; example3 . palin_selfie ( ) ; } }


"Panalphabetic window in a string | Java Program to check whether given string contain panalphabetic window or not ; 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"
How can the above be solved in Java?

class GFG { static boolean isPanalphabeticWindow ( String s , int n ) { char ch = ' a ' ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == ch ) ch ++ ; if ( ch == ' z ' + 1 ) return true ; } return false ; } public static void main ( String [ ] args ) { String s = " abujm ▁ zvcd ▁ acefc ▁ deghf " + " ▁ gijklem ▁ n ▁ o ▁ p ▁ pafqrstuvwxyzfap " ; int n = s . length ( ) ; if ( isPanalphabeticWindow ( s , n ) ) System . out . print ( " YES " ) ; else System . out . print ( " NO " ) ; } }


"Panarithmic numbers within a given range | Java program to print practical Numbers in given range ; Function to compute divisors of a number ; Vector to store divisors ; 1 will always be a divisor ; Check if i is squareroot of A then only one time insert it in ans ; Function to check that a number can be represented as sum of distinct divisor or not ; The value of subset [ i ] [ j ] will be true if there is a subset of set [ 0. . j - 1 ] with sum equal to i ; If sum is 0 , then answer is true ; If sum is not 0 and set is empty , then answer is false ; Fill the subset table in bottom up manner ; Return the possibility of given sum ; Function to check a number is Practical or not ; Vector to store divisors ; If all numbers can be represented as sum of unique divisors ; Function to print Practical Numbers in a range ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . math . * ; class GFG { static ArrayList < Integer > get_divisors ( int A ) { ArrayList < Integer > ans = new ArrayList < > ( ) ; ans . add ( 1 ) ; for ( int i = 2 ; i <= Math . sqrt ( A ) ; i ++ ) { if ( A % i == 0 ) { ans . add ( i ) ; if ( ( i * i ) != A ) ans . add ( A / i ) ; } } return ans ; } static boolean Sum_Possible ( ArrayList < Integer > set , int sum ) { int n = set . size ( ) ; boolean subset [ ] [ ] = new boolean [ n + 1 ] [ sum + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) subset [ i ] [ 0 ] = true ; for ( int i = 1 ; i <= sum ; i ++ ) subset [ 0 ] [ i ] = false ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= sum ; j ++ ) { if ( j < set . get ( i - 1 ) ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] ; if ( j >= set . get ( i - 1 ) ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] || subset [ i - 1 ] [ j - set . get ( i - 1 ) ] ; } } return subset [ n ] [ sum ] ; } static boolean Is_Practical ( int A ) { ArrayList < Integer > divisors ; divisors = get_divisors ( A ) ; for ( int i = 2 ; i < A ; i ++ ) { if ( Sum_Possible ( divisors , i ) == false ) return false ; } return true ; } static void print_practica_No ( int A , int B ) { for ( int i = A ; i <= B ; i ++ ) { if ( Is_Practical ( i ) == true ) { System . out . print ( i + " ▁ " ) ; } } } public static void main ( String args [ ] ) { int A = 1 , B = 100 ; print_practica_No ( A , B ) ; } }


"Pancake sorting | Java program to sort array using pancake sort ; 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 ; Utility function to print array arr [ ] ; Driver function to check for above functions"
How can the above be solved in Java?

import java . io . * ; class PancakeSort { static void flip ( int arr [ ] , int i ) { int temp , start = 0 ; while ( start < i ) { temp = arr [ start ] ; arr [ start ] = arr [ i ] ; arr [ i ] = temp ; start ++ ; i -- ; } } static int findMax ( int arr [ ] , int n ) { int mi , i ; for ( mi = 0 , i = 0 ; i < n ; ++ i ) if ( arr [ i ] > arr [ mi ] ) mi = i ; return mi ; } static int pancakeSort ( int arr [ ] , int n ) { for ( int curr_size = n ; curr_size > 1 ; -- curr_size ) { int mi = findMax ( arr , curr_size ) ; if ( mi != curr_size - 1 ) { flip ( arr , mi ) ; flip ( arr , curr_size - 1 ) ; } } return 0 ; } static void printArray ( int arr [ ] , int arr_size ) { for ( int i = 0 ; i < arr_size ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( " " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 23 , 10 , 20 , 11 , 12 , 6 , 7 } ; int n = arr . length ; pancakeSort ( arr , n ) ; System . out . println ( " Sorted ▁ Array : ▁ " ) ; printArray ( arr , n ) ; } }


"Pandigital Product | Java code to check the number is Pandigital Product or not ; calculate the multiplicand , multiplier , and product eligible for pandigital ; To check the string formed from multiplicand multiplier and product is pandigital ; Driver function"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static boolean PandigitalProduct_1_9 ( int n ) { for ( int i = 1 ; i * i <= n ; i ++ ) if ( n % i == 0 && isPandigital ( " " + n + i + n / i ) ) return true ; return false ; } public static boolean isPandigital ( String str ) { if ( str . length ( ) != 9 ) return false ; char ch [ ] = str . toCharArray ( ) ; Arrays . sort ( ch ) ; return new String ( ch ) . equals ( "123456789" ) ; } public static void main ( String [ ] args ) { int n = 6952 ; if ( PandigitalProduct_1_9 ( n ) == true ) System . out . println ( " yes " ) ; else System . out . println ( " no " ) ; } }


"Paper Cut into Minimum Number of Squares | Java program to find minimum number of squares to cut a paper . ; To swap two numbers ; Returns min number of squares needed ; swap if a is small size side . ; Iterate until small size side is greater then 0 ; Update result ; Driver code"
How can the above be solved in Java?

class GFG { static void swap ( int a , int b ) { int temp = a ; a = b ; b = temp ; } static int minimumSquare ( int a , int b ) { int result = 0 , rem = 0 ; if ( a < b ) swap ( a , b ) ; while ( b > 0 ) { result += a / b ; rem = a % b ; a = b ; b = rem ; } return result ; } public static void main ( String [ ] args ) { int n = 13 , m = 29 ; System . out . println ( minimumSquare ( n , m ) ) ; } }