"Multiset Equivalence Problem | Java program to check if two given multisets are equivalent ; Create two unordered maps m1 and m2 and insert values of both vectors . ; Now we check if both unordered_maps are same of not . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean areSame ( int [ ] a , int [ ] b ) { if ( a . length != b . length ) return false ; HashMap < Integer , Integer > m1 , m2 ; m1 = new HashMap < Integer , Integer > ( ) ; m2 = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < a . length ; i ++ ) { if ( m1 . containsKey ( a [ i ] ) ) { m1 . put ( a [ i ] , m1 . get ( a [ i ] ) + 1 ) ; } else { m1 . put ( a [ i ] , 1 ) ; } if ( m2 . containsKey ( b [ i ] ) ) { m2 . put ( b [ i ] , m2 . get ( b [ i ] ) + 1 ) ; } else { m2 . put ( b [ i ] , 1 ) ; } } for ( Map . Entry < Integer , Integer > x : m1 . entrySet ( ) ) { if ( ! m2 . containsKey ( x . getKey ( ) ) || m2 . get ( x . getKey ( ) ) != x . getValue ( ) ) return false ; } return true ; } public static void main ( String args [ ] ) { int [ ] a = { 7 , 7 , 5 } ; int [ ] b = { 7 , 7 , 5 } ; if ( areSame ( a , b ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Multiset Equivalence Problem | Java program to check if two given multisets are equivalent ; sort the elements of both multisets ; Return true if both multisets are same . ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static boolean areSame ( Vector < Integer > a , Vector < Integer > b ) { Collections . sort ( a ) ; Collections . sort ( b ) ; return ( a == b ) ; } public static void main ( String [ ] args ) { Vector < Integer > a = new Vector < Integer > ( Arrays . asList ( 7 , 7 , 5 ) ) ; Vector < Integer > b = new Vector < Integer > ( Arrays . asList ( 7 , 5 , 5 ) ) ; if ( areSame ( a , b ) ) System . out . print ( "Yes
"); else System . out . print ( "No
"); } }


"Multistage Graph ( Shortest Path ) | Java program to find shortest distance in a multistage graph . ; Returns shortest distance from 0 to N - 1. ; dist [ i ] is going to store shortest distance from node i to node N - 1. ; Calculating shortest path for rest of the nodes ; Initialize distance from i to destination ( N - 1 ) ; Check all nodes of next stages to find shortest distance from i to N - 1. ; Reject if no edge exists ; We apply recursive equation to distance to target through j . and compare with minimum distance so far . ; Driver code ; Graph stored in the form of an adjacency Matrix"
How can the above be solved in Java?

class GFG { static int N = 8 ; static int INF = Integer . MAX_VALUE ; public static int shortestDist ( int [ ] [ ] graph ) { int [ ] dist = new int [ N ] ; dist [ N - 1 ] = 0 ; for ( int i = N - 2 ; i >= 0 ; i -- ) { dist [ i ] = INF ; for ( int j = i ; j < N ; j ++ ) { if ( graph [ i ] [ j ] == INF ) { continue ; } dist [ i ] = Math . min ( dist [ i ] , graph [ i ] [ j ] + dist [ j ] ) ; } } return dist [ 0 ] ; } public static void main ( String [ ] args ) { int [ ] [ ] graph = new int [ ] [ ] { { INF , 1 , 2 , 5 , INF , INF , INF , INF } , { INF , INF , INF , INF , 4 , 11 , INF , INF } , { INF , INF , INF , INF , 9 , 5 , 16 , INF } , { INF , INF , INF , INF , INF , INF , 2 , INF } , { INF , INF , INF , INF , INF , INF , INF , 18 } , { INF , INF , INF , INF , INF , INF , INF , 13 } , { INF , INF , INF , INF , INF , INF , INF , 2 } } ; System . out . println ( shortestDist ( graph ) ) ; } }


"MÃ ¼ nchhausen Number | Java code for Munchhausen Number ; pwr [ i ] is going to store i raised to power i . ; Function to check out whether the number is Munchhausen Number or not ; Precompute i raised to power i for every i ; The input here is fixed i . e . it will check up to n ; check the integer for Munchhausen Number , if yes then print out the number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static long [ ] pwr ; static Boolean isMunchhausen ( int n ) { long sum = 0l ; int temp = n ; while ( temp > 0 ) { int index = temp % 10 ; sum = sum + pwr [ index ] ; temp /= 10 ; } return ( sum == n ) ; } static void printMunchhausenNumbers ( int n ) { pwr = new long [ 10 ] ; for ( int i = 0 ; i < 10 ; i ++ ) pwr [ i ] = ( long ) Math . pow ( ( float ) i , ( float ) i ) ; for ( int i = 1 ; i <= n ; i ++ ) if ( isMunchhausen ( i ) == true ) System . out . println ( i ) ; } public static void main ( String [ ] args ) { int n = 10000 ; printMunchhausenNumbers ( n ) ; } }


"N 'th Smart Number | Java implementation to find n 'th smart number ; Limit on result ; Function to calculate n 'th smart number ; Initialize all numbers as not prime ; iterate to mark all primes and smart number ; Traverse all numbers till maximum limit ; ' i ' is maked as prime number because it is not multiple of any other prime ; mark all multiples of ' i ' as non prime ; If i is the third prime factor of j then add it to result as it has at least three prime factors . ; Sort all smart numbers ; return n 'th smart number ; Driver program to run the case"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int MAX = 3000 ; public static int smartNumber ( int n ) { Integer [ ] primes = new Integer [ MAX ] ; Arrays . fill ( primes , new Integer ( 0 ) ) ; Vector < Integer > result = new Vector < > ( ) ; for ( int i = 2 ; i < MAX ; i ++ ) { if ( primes [ i ] == 0 ) { primes [ i ] = 1 ; for ( int j = i * 2 ; j < MAX ; j = j + i ) { primes [ j ] -= 1 ; if ( ( primes [ j ] + 3 ) == 0 ) result . add ( j ) ; } } } Collections . sort ( result ) ; return result . get ( n - 1 ) ; } public static void main ( String [ ] args ) { int n = 50 ; System . out . println ( smartNumber ( n ) ) ; } }


"N 'th palindrome of K digits | A naive approach of Java program of finding nth palindrome of k digit ; Utility function to reverse the number n ; Boolean Function to check for palindromic number ; Function for finding nth palindrome of k digits ; Get the smallest k digit number ; check the number is palindrom or not ; if n 'th palindrome found break the loop ; Increment number for checking next palindrome ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int reverseNum ( int n ) { int rem , rev = 0 ; while ( n > 0 ) { rem = n % 10 ; rev = rev * 10 + rem ; n /= 10 ; } return rev ; } static boolean isPalindrom ( int num ) { return num == reverseNum ( num ) ; } static int nthPalindrome ( int n , int k ) { int num = ( int ) Math . pow ( 10 , k - 1 ) ; while ( true ) { if ( isPalindrom ( num ) ) -- n ; if ( n == 0 ) break ; ++ num ; } return num ; } public static void main ( String [ ] args ) { int n = 6 , k = 5 ; System . out . println ( n + " th ▁ palindrome ▁ of ▁ " + k + " ▁ digit ▁ = ▁ " + nthPalindrome ( n , k ) ) ; n = 10 ; k = 6 ; System . out . println ( n + " th ▁ palindrome ▁ of ▁ " + k + " ▁ digit ▁ = ▁ " + nthPalindrome ( n , k ) ) ; } }


"N 'th palindrome of K digits | Java program of finding nth palindrome of k digit ; Determine the first half digits ; Print the first half digits of palindrome ; If k is odd , truncate the last digit ; print the last half digits of palindrome ; Driver code"
How can the above be solved in Java?

class GFG { static void nthPalindrome ( int n , int k ) { int temp = ( k & 1 ) != 0 ? ( k / 2 ) : ( k / 2 - 1 ) ; int palindrome = ( int ) Math . pow ( 10 , temp ) ; palindrome += n - 1 ; System . out . print ( palindrome ) ; if ( ( k & 1 ) > 0 ) palindrome /= 10 ; while ( palindrome > 0 ) { System . out . print ( palindrome % 10 ) ; palindrome /= 10 ; } System . out . println ( " " ) ; } public static void main ( String [ ] args ) { int n = 6 , k = 5 ; System . out . print ( n + " th ▁ palindrome ▁ of ▁ " + k + " ▁ digit ▁ = ▁ " ) ; nthPalindrome ( n , k ) ; n = 10 ; k = 6 ; System . out . print ( n + " th ▁ palindrome ▁ of ▁ " + k + " ▁ digit ▁ = ▁ " ) ; nthPalindrome ( n , k ) ; } }


"N / 3 repeated number in an array with O ( 1 ) space | Java program to find if any element appears more than n / 3. ; take the integers as the maximum value of integer hoping the integer would not be present in the array ; if this element is previously seen , increment count1 . ; if this element is previously seen , increment count2 . ; if current element is different from both the previously seen variables , decrement both the counts . ; Again traverse the array and find the actual counts . ; Driver code"
How can the above be solved in Java?

class GFG { static int appearsNBy3 ( int arr [ ] , int n ) { int count1 = 0 , count2 = 0 ; int first = Integer . MIN_VALUE ; ; int second = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { if ( first == arr [ i ] ) count1 ++ ; else if ( second == arr [ i ] ) count2 ++ ; else if ( count1 == 0 ) { count1 ++ ; first = arr [ i ] ; } else if ( count2 == 0 ) { count2 ++ ; second = arr [ i ] ; } else { count1 -- ; count2 -- ; } } count1 = 0 ; count2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == first ) count1 ++ ; else if ( arr [ i ] == second ) count2 ++ ; } if ( count1 > n / 3 ) return first ; if ( count2 > n / 3 ) return second ; return - 1 ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 1 , 1 } ; int n = arr . length ; System . out . println ( appearsNBy3 ( arr , n ) ) ; } }


"N Queen Problem using Branch And Bound | Java program to solve N Queen Problem using Branch and Bound ; A utility function to print solution ; A Optimized function to check if a queen can be placed on board [ row ] [ col ] ; A recursive utility function to solve N Queen problem ; Base case : If all queens are placed then return true ; Consider this column and try placing this queen in all rows one by one ; Check if queen can be placed on board [ i ] [ col ] ; Place this queen in board [ i ] [ col ] ; recur to place rest of the queens ; Remove queen from board [ i ] [ col ] ; If queen can not be place in any row in this colum col then return false ; * This function solves the N Queen problem using Branch * and Bound . It mainly uses solveNQueensUtil ( ) to solve * the problem . It returns false if queens cannot be * placed , otherwise return true and prints placement of * queens in the form of 1 s . Please note that there may * be more than one solutions , this function prints one * of the feasible solutions . ; Helper matrices ; Arrays to tell us which rows are occupied ; Keep two arrays to tell us which diagonals are occupied ; Initialize helper matrices ; Solution found ; Driver code"
How can the above be solved in Java?

 import java . io . * ; import java . util . Arrays ; class GFG { static int N = 8 ; static void printSolution ( int board [ ] [ ] ) { int N = board . length ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) System . out . printf ( " % 2d ▁ " , board [ i ] [ j ] ) ; System . out . printf ( "
"); } } static boolean isSafe ( int row , int col , int slashCode [ ] [ ] , int backslashCode [ ] [ ] , boolean rowLookup [ ] , boolean slashCodeLookup [ ] , boolean backslashCodeLookup [ ] ) { if ( slashCodeLookup [ slashCode [ row ] [ col ] ] backslashCodeLookup [ backslashCode [ row ] [ col ] ] rowLookup [ row ] ) return false ; return true ; } static boolean solveNQueensUtil ( int board [ ] [ ] , int col , int slashCode [ ] [ ] , int backslashCode [ ] [ ] , boolean rowLookup [ ] , boolean slashCodeLookup [ ] , boolean backslashCodeLookup [ ] ) { int N = board . length ; if ( col >= N ) return true ; for ( int i = 0 ; i < N ; i ++ ) { if ( isSafe ( i , col , slashCode , backslashCode , rowLookup , slashCodeLookup , backslashCodeLookup ) ) { board [ i ] [ col ] = 1 ; rowLookup [ i ] = true ; slashCodeLookup [ slashCode [ i ] [ col ] ] = true ; backslashCodeLookup [ backslashCode [ i ] [ col ] ] = true ; if ( solveNQueensUtil ( board , col + 1 , slashCode , backslashCode , rowLookup , slashCodeLookup , backslashCodeLookup ) ) return true ; board [ i ] [ col ] = 0 ; rowLookup [ i ] = false ; slashCodeLookup [ slashCode [ i ] [ col ] ] = false ; backslashCodeLookup [ backslashCode [ i ] [ col ] ] = false ; } } return false ; } static boolean solveNQueens ( ) { int board [ ] [ ] = new int [ N ] [ N ] ; int slashCode [ ] [ ] = new int [ N ] [ N ] ; int backslashCode [ ] [ ] = new int [ N ] [ N ] ; boolean [ ] rowLookup = new boolean [ N ] ; boolean slashCodeLookup [ ] = new boolean [ 2 * N - 1 ] ; boolean backslashCodeLookup [ ] = new boolean [ 2 * N - 1 ] ; for ( int r = 0 ; r < N ; r ++ ) for ( int c = 0 ; c < N ; c ++ ) { slashCode [ r ] = r + c ; backslashCode [ r ] = r - c + 7 ; } if (...


"N Queen Problem | Backtracking | Java program to solve N Queen Problem using backtracking ; ld is an array where its indices indicate row - col + N - 1 ( N - 1 ) is for shifting the difference to store negative indices ; rd is an array where its indices indicate row + col and used to check whether a queen can be placed on right diagonal or not ; column array where its indices indicates column and used to check whether a queen can be placed in that row or not ; A utility function to print solution ; A recursive utility function to solve N Queen problem ; base case : If all queens are placed then return true ; Consider this column and try placing this queen in all rows one by one ; A check if a queen can be placed on board [ row ] [ col ] . We just need to check ld [ row - col + n - 1 ] and rd [ row + coln ] where ld and rd are for left and right diagonal respectively ; Place this queen in board [ i ] [ col ] ; recur to place rest of the queens ; board [ i ] [ col ] = 0 ; BACKTRACK ; If the queen cannot be placed in any row in this colum col then return false ; This function solves the N Queen problem using Backtracking . It mainly uses solveNQUtil ( ) to solve the problem . It returns false if queens cannot be placed , otherwise , return true and prints placement of queens in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int N = 4 ; static int [ ] ld = new int [ 30 ] ; static int [ ] rd = new int [ 30 ] ; static int [ ] cl = new int [ 30 ] ; static void printSolution ( int board [ ] [ ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) System . out . printf ( " ▁ % d ▁ " , board [ i ] [ j ] ) ; System . out . printf ( "
"); } } static boolean solveNQUtil ( int board [ ] [ ] , int col ) { if ( col >= N ) return true ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( ld [ i - col + N - 1 ] != 1 && rd [ i + col ] != 1 ) && cl [ i ] != 1 ) { board [ i ] [ col ] = 1 ; ld [ i - col + N - 1 ] = rd [ i + col ] = cl [ i ] = 1 ; if ( solveNQUtil ( board , col + 1 ) ) return true ; ld [ i - col + N - 1 ] = rd [ i + col ] = cl [ i ] = 0 ; } } return false ; } static boolean solveNQ ( ) { int board [ ] [ ] = { { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; if ( solveNQUtil ( board , 0 ) == false ) { System . out . printf ( " Solution ▁ does ▁ not ▁ exist " ) ; return false ; } printSolution ( board ) ; return true ; } public static void main ( String [ ] args ) { solveNQ ( ) ; } }


"N Queen in O ( n ) space | Java code to for n Queen placement ; Function to check queens placement ; Helper Function to check if queen can be placed ; Function to display placed queen ; Driver Code"
How can the above be solved in Java?

class GfG { static void breakLine ( ) { System . out . print ( " -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - "); } static int MAX = 10 ; static int arr [ ] = new int [ MAX ] , no ; static void nQueens ( int k , int n ) { for ( int i = 1 ; i <= n ; i ++ ) { if ( canPlace ( k , i ) ) { arr [ k ] = i ; if ( k == n ) { display ( n ) ; } else { nQueens ( k + 1 , n ) ; } } } } static boolean canPlace ( int k , int i ) { for ( int j = 1 ; j <= k - 1 ; j ++ ) { if ( arr [ j ] == i || ( Math . abs ( arr [ j ] - i ) == Math . abs ( j - k ) ) ) { return false ; } } return true ; } static void display ( int n ) { breakLine ( ) ; System . out . print ( " Arrangement ▁ No . ▁ " + ++ no ) ; breakLine ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( arr [ i ] != j ) { System . out . print ( " 	 _ " ) ; } else { System . out . print ( " 	 Q " ) ; } } System . out . println ( " " ) ; } breakLine ( ) ; } public static void main ( String [ ] args ) { int n = 4 ; nQueens ( 1 , n ) ; } }


"N digit numbers divisible by 5 formed from the M digits | Java program to find the count of all possible N digit numbers which are divisible by 5 formed from M digits ; Function to find the count of all possible N digit numbers which are divisible by 5 formed from M digits ; If it is not possible to form n digit number from the given m digits without repetition ; If both zero and five exists ; Remaining N - 1 iterations ; Remaining N - 1 iterations ; Driver code"
How can the above be solved in Java?

class GFG { static int numbers ( int n , int arr [ ] , int m ) { int isZero = 0 , isFive = 0 ; int result = 0 ; if ( m < n ) { return - 1 ; } for ( int i = 0 ; i < m ; i ++ ) { if ( arr [ i ] == 0 ) { isZero = 1 ; } if ( arr [ i ] == 5 ) { isFive = 1 ; } } if ( isZero == 1 && isFive == 1 ) { result = 2 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { result = result * ( -- m ) ; } } else if ( isZero == 1 isFive == 1 ) { result = 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { result = result * ( -- m ) ; } } else { result = - 1 ; } return result ; } public static void main ( String [ ] args ) { int n = 3 , m = 6 ; int arr [ ] = { 2 , 3 , 5 , 6 , 7 , 9 } ; System . out . println ( numbers ( n , arr , m ) ) ; } }


"N digit numbers having difference between the first and last digits as K | Java program for the above approach ; Function to store and check the difference of digits ; Base Case ; Last digit of the number to check the difference from the first digit ; Condition to avoid repeated values ; Update the String pt ; Recursive Call ; Update the String pt ; Recursive Call ; Any number can come in between first and last except the zero ; Recursive Call ; Function to place digit of the number ; When N is 1 and K > 0 , then the single number will be the first and last digit it cannot have difference greater than 0 ; This loop place the digit at the starting ; Recursive Call ; Vector to store results ; Generate all the resultant number ; Print the result ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; @ SuppressWarnings ( " unchecked " ) class GFG { static void findNumbers ( String st , ArrayList result , int prev , int n , int K ) { if ( st . length ( ) == n ) { result . add ( Integer . parseInt ( st ) ) ; return ; } if ( st . length ( ) == n - 1 ) { if ( prev - K >= 0 ) { String pt = " " ; pt += ( char ) ( prev - K + 48 ) ; findNumbers ( st + pt , result , prev - K , n , K ) ; } if ( K != 0 && prev + K < 10 ) { String pt = " " ; pt += ( char ) ( prev + K + 48 ) ; findNumbers ( st + pt , result , prev + K , n , K ) ; } } else { for ( int j = 1 ; j <= 9 ; j ++ ) { String pt = " " ; pt += ( char ) ( j + 48 ) ; findNumbers ( st + pt , result , prev , n , K ) ; } } } static ArrayList numDifference ( int N , int K ) { ArrayList res = new ArrayList ( ) ; String st = " " ; if ( N == 1 && K == 0 ) { res . add ( 0 ) ; } else if ( N == 1 && K > 0 ) { return res ; } for ( int i = 1 ; i < 10 ; i ++ ) { String temp = " " ; temp += ( char ) ( 48 + i ) ; findNumbers ( st + temp , res , i , N , K ) ; st = " " ; } return res ; } static void numDifferenceUtil ( int N , int K ) { ArrayList res = new ArrayList ( ) ; res = numDifference ( N , K ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) { System . out . print ( res . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 2 , K = 9 ; numDifferenceUtil ( N , K ) ; } }


"N | Java program for finding N - th polite number ; function to find N - th polite number ; driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static double polite ( double n ) { n += 1 ; double base = 2 ; return n + ( Math . log ( ( n + ( Math . log ( n ) / Math . log ( base ) ) ) ) ) / Math . log ( base ) ; } public static void main ( String [ ] args ) { double n = 7 ; System . out . println ( ( int ) polite ( n ) ) ; } }


"N | Java program to answer queries for N - th prime factor of a number ; 2 - D vector that stores prime factors ; Function to pre - store prime factors of all numbers till 10 ^ 6 ; calculate unique prime factors for every number till 10 ^ 6 ; find prime factors ; store if prime factor ; Function that returns answer for every query ; Driver Code ; Function to pre - store unique prime factors ; 1 st query ; 2 nd query ; 3 rd query ; 4 th query"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int N = 1000001 ; static Vector < Integer > [ ] v = new Vector [ N ] ; static void preprocess ( ) { for ( int i = 1 ; i < N ; i ++ ) { int num = i ; for ( int j = 2 ; j <= Math . sqrt ( num ) ; j ++ ) { if ( num % j == 0 ) { v [ i ] . add ( j ) ; while ( num % j == 0 ) { num = num / j ; } } } if ( num > 2 ) v [ i ] . add ( num ) ; } } static int query ( int number , int n ) { return v [ number ] . get ( n - 1 ) ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < N ; i ++ ) v [ i ] = new Vector < Integer > ( ) ; preprocess ( ) ; int number = 6 , n = 1 ; System . out . print ( query ( number , n ) + "
"); number = 210 ; n = 3 ; System . out . print ( query ( number , n ) + "
"); number = 210 ; n = 2 ; System . out . print ( query ( number , n ) + "
"); number = 60 ; n = 2 ; System . out . print ( query ( number , n ) + "
"); } }


"N | Java program to find N - th term in George Cantor set of rational number ; let i = numerator ; let j = denominator ; to keep the check of no . of terms ; loop till k is not equal to n ; check if k is already equal to N then the first term is the required rational number ; loop for traversing from right to left downwards diagonally ; loop for traversing from left to right upwards diagonally ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void georgeCantor ( int n ) { int i = 1 ; int j = 1 ; int k = 1 ; while ( k < n ) { j ++ ; k ++ ; if ( k == n ) break ; while ( j > 1 && k < n ) { i ++ ; j -- ; k ++ ; } if ( k == n ) break ; i ++ ; k ++ ; if ( k == n ) break ; while ( i > 1 && k < n ) { i -- ; j ++ ; k ++ ; } } System . out . println ( " N - th ▁ term ▁ : ▁ " + i + " / " + j ) ; } public static void main ( String [ ] args ) { int n = 15 ; georgeCantor ( n ) ; } }


"N | Java program to find n - th number in the sorted list of multiples of two numbers . ; Return the n - th number in the sorted list of multiples of two numbers . ; Generating first n multiple of a . ; Sorting the sequence . ; Generating and storing first n multiple of b and storing if not present in the sequence . ; If not present in the sequence ; Storing in the sequence . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int nthElement ( int a , int b , int n ) { ArrayList < Integer > seq = new ArrayList < Integer > ( n * n + 1 ) ; for ( int i = 1 ; i <= n ; i ++ ) seq . add ( a * i ) ; Collections . sort ( seq ) ; for ( int i = 1 , k = n ; i <= n && k > 0 ; i ++ ) { if ( seq . indexOf ( b * i ) == - 1 ) { seq . add ( b * i ) ; Collections . sort ( seq ) ; k -- ; } } return seq . get ( n - 1 ) ; } public static void main ( String [ ] args ) { int a = 3 , b = 5 , n = 5 ; System . out . println ( nthElement ( a , b , n ) ) ; } }


"N | Java program to find n - th number which is both square and cube . ; Driver code"
How can the above be solved in Java?

class GFG { static int nthSquareCube ( int n ) { return n * n * n * n * n * n ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( nthSquareCube ( n ) ) ; } }


"N | Java program to find the N - th character in the string "1234567891011 . . " ; Function that returns the N - th character ; initially null string ; starting integer ; add integers in string ; one digit numbers added ; more than 1 digit number , generate equivalent number in a string s1 and concatenate s1 into s . ; add the number in string ; reverse the string ; attach the number ; if the length exceeds N ; Driver Code"
How can the above be solved in Java?

class GFG { static char NthCharacter ( int n ) { String s = " " ; int c = 1 ; for ( int i = 1 ; ; i ++ ) { if ( c < 10 ) s += Integer . toString ( c ) ; else { String s1 = " " ; int dup = c ; while ( dup > 0 ) { s1 += Integer . toString ( dup % 10 ) ; dup /= 10 ; } StringBuilder temp = new StringBuilder ( ) ; temp . append ( s1 ) ; temp = temp . reverse ( ) ; s += temp ; } c ++ ; if ( s . length ( ) >= n ) { return s . charAt ( n - 1 ) ; } } } public static void main ( String [ ] args ) { int n = 11 ; System . out . println ( NthCharacter ( n ) ) ; } }


"N | Java program to find the N - th term in 1 , 11 , 55 , 239 , 991 , ... . ; Function to find the N - th term ; calculates the N - th term ; Driver Code"
How can the above be solved in Java?

class GFG { static int numberSequence ( int n ) { int num = ( int ) ( Math . pow ( 4 , n ) - Math . pow ( 2 , n ) ) - 1 ; return num ; } public static void main ( String args [ ] ) { int n = 4 ; System . out . println ( numberSequence ( n ) ) ; } }


"N | Java program to find the N - th term in 1 , 11 , 55 , 239 , 991 , ... . ; Function to return the decimal value of a binary number ; Initializing base value to 1 , i . e 2 ^ 0 ; find the binary representation of the N - th number in sequence ; base case ; answer string ; add n - 1 1 's ; add 0 ; add n 1 's at end ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int binaryToDecimal ( String n ) { String num = n ; int dec_value = 0 ; int base = 1 ; int len = num . length ( ) ; for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( num . charAt ( i ) == '1' ) dec_value += base ; base = base * 2 ; } return dec_value ; } static int numberSequence ( int n ) { if ( n == 1 ) return 1 ; String s = " " ; for ( int i = 1 ; i < n ; i ++ ) s += '1' ; s += '0' ; for ( int i = 1 ; i <= n ; i ++ ) s += '1' ; int num = binaryToDecimal ( s ) ; return num ; } public static void main ( String args [ ] ) { int n = 4 ; System . out . println ( numberSequence ( n ) ) ; } }


"Naive algorithm for Pattern Searching | Java program for Naive Pattern Searching ; A loop to slide pat one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver code"
How can the above be solved in Java?

public class NaiveSearch { public static void search ( String txt , String pat ) { int M = pat . length ( ) ; int N = txt . length ( ) ; for ( int i = 0 ; i <= N - M ; i ++ ) { 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 ) ; } } public static void main ( String [ ] args ) { String txt = " AABAACAADAABAAABAA " ; String pat = " AABA " ; search ( txt , pat ) ; } }


"Nambiar Number Generator | Java implementation of the approach ; Function to return the Nambiar number of the given number ; If there is no digit to choose ; Choose the first digit ; Chosen digit 's parity ; To store the sum of the consecutive digits starting from the chosen digit ; While there are digits to choose ; Update the sum ; If the parity differs ; Return the current sum concatenated with the Numbiar number for the rest of the string ; Driver code"
How can the above be solved in Java?

class GFG { static String nambiarNumber ( String str , int i ) { if ( i >= str . length ( ) ) return " " ; int firstDigit = ( str . charAt ( i ) - '0' ) ; int digitParity = firstDigit % 2 ; int sumDigits = 0 ; while ( i < str . length ( ) ) { sumDigits += ( str . charAt ( i ) - '0' ) ; int sumParity = sumDigits % 2 ; if ( digitParity != sumParity ) { break ; } i ++ ; } return ( " " + sumDigits + nambiarNumber ( str , i + 1 ) ) ; } public static void main ( String [ ] args ) { String str = "9880127431" ; System . out . println ( nambiarNumber ( str , 0 ) ) ; } }


"Narcissistic number | Java program for checking of Narcissistic number ; Traversing through the string ; Since ascii value of numbers starts from 48 so we subtract it from sum ; Converting string to integer ; Comparing number and sum ; Driver Code"
How can the above be solved in Java?

class GFG { static String getResult ( String st ) { int sum = 0 ; int length = st . length ( ) ; for ( int i = 0 ; i < length ; i ++ ) { sum = sum + ( int ) Math . pow ( st . charAt ( i ) - '0' , length ) ; } int number = Integer . parseInt ( st ) ; if ( number == sum ) return " yes " ; else return " no " ; } public static void main ( String [ ] args ) { String st = "153" ; System . out . print ( getResult ( st ) ) ; } }


"Narcissistic number | Java program for checking of Narcissistic number ; function to count digits ; Returns true if n is Narcissistic number ; count the number of digits ; calculates the sum of digits raised to power ; Driver code"
How can the above be solved in Java?

import java . io . * ; import static java . lang . Math . * ; class narcissistic { int countDigit ( int n ) { if ( n == 0 ) return 0 ; return 1 + countDigit ( n / 10 ) ; } boolean check ( int n ) { int l = countDigit ( n ) ; int dup = n ; int sum = 0 ; while ( dup > 0 ) { sum += pow ( dup % 10 , l ) ; dup /= 10 ; } return ( n == sum ) ; } public static void main ( String args [ ] ) { narcissistic obj = new narcissistic ( ) ; int n = 1634 ; if ( obj . check ( n ) ) System . out . println ( " yes " ) ; else System . out . println ( " no " ) ; } }


"Natural Numbers | JAVA program to find sum of first n natural numbers . ; Returns sum of first n natural numbers ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findSum ( int n ) { int sum = 0 ; for ( int x = 1 ; x <= n ; x ++ ) sum = sum + x ; return sum ; } public static void main ( String args [ ] ) { int n = 5 ; System . out . println ( findSum ( n ) ) ; } }


"Nearest element with at | Java program to print nearest element with at least one common prime factor . ; Loop covers the every element of arr [ ] ; Loop that covers from 0 to i - 1 and i + 1 to n - 1 indexes simultaneously ; print position of closest element ; Recursive function to return gcd of a and b ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static void nearestGcd ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; ++ i ) { int closest = - 1 ; for ( int j = i - 1 , k = i + 1 ; j > 0 k <= n ; -- j , ++ k ) { if ( j >= 0 && __gcd ( arr [ i ] , arr [ j ] ) > 1 ) { closest = j + 1 ; break ; } if ( k < n && __gcd ( arr [ i ] , arr [ k ] ) > 1 ) { closest = k + 1 ; break ; } } System . out . print ( closest + " ▁ " ) ; } } static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } public static void main ( String args [ ] ) { int [ ] arr = { 2 , 9 , 4 , 3 , 13 } ; int n = arr . length ; nearestGcd ( arr , n ) ; } }


"Nearest element with at | Java program to print nearest element with at least one common prime factor . ; Pre - computation of smallest prime divisor of all numbers ; Prime number will have same divisor ; Function to calculate all divisors of input array ; Pre - compute all the divisors of array element by using prime factors ; Traverse all elements , ; For every divisor of current element , find closest element . ; Visit divisor if not visited ; Fetch the index of visited divisor ; Update the divisor index to current index ; Set the minimum distance ; Set the min distance of current index ' i ' to nearest one ; Add 1 as indexing starts from 0 ; Set the min distance of found index ' ind ' ; Add 1 as indexing starts from 0 ; Driver code ; Simple sieve to find smallest prime divisor of number from 2 to MAX ; function to calculate nearest distance of every array elements ; Print the nearest distance having GDC > 1"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int MAX = 100001 ; static int INF = Integer . MAX_VALUE ; static int [ ] primedivisor = new int [ MAX ] ; static int [ ] dist = new int [ MAX ] ; static int [ ] pos = new int [ MAX ] ; static int [ ] divInd = new int [ MAX ] ; static ArrayList < ArrayList < Integer > > divisors = new ArrayList < ArrayList < Integer > > ( ) ; static void sieveOfEratosthenes ( ) { for ( int i = 2 ; i * i < MAX ; ++ i ) { if ( primedivisor [ i ] == 0 ) { for ( int j = i * i ; j < MAX ; j += i ) { primedivisor [ j ] = i ; } } } for ( int i = 1 ; i < MAX ; ++ i ) { if ( primedivisor [ i ] == 0 ) { primedivisor [ i ] = i ; } } } static void findDivisors ( int arr [ ] , int n ) { for ( int i = 0 ; i < MAX ; ++ i ) { pos [ i ] = divInd [ i ] = - 1 ; dist [ i ] = INF ; } for ( int i = 0 ; i < n ; ++ i ) { int num = arr [ i ] ; while ( num > 1 ) { int div = primedivisor [ num ] ; divisors . get ( i ) . add ( div ) ; while ( num % div == 0 ) { num /= div ; } } } } static void nearestGCD ( int arr [ ] , int n ) { findDivisors ( arr , n ) ; for ( int i = 0 ; i < n ; ++ i ) { for ( int div : divisors . get ( i ) ) { if ( divInd [ div ] == - 1 ) { divInd [ div ] = i ; } else { int ind = divInd [ div ] ; divInd [ div ] = i ; if ( dist [ i ] > Math . abs ( ind - i ) ) { dist [ i ] = Math . abs ( ind - i ) ; pos [ i ] = ind + 1 ; } if ( dist [ ind ] > Math . abs ( ind - i ) ) { dist [ ind ] = Math . abs ( ind - i ) ; pos [ ind ] = i + 1 ; } } } } } public static void main ( String [ ] args ) { for ( int i = 0 ; i < MAX ; i ++ ) { divisors . add ( new ArrayList < Integer > ( ) ) ; } sieveOfEratosthenes ( ) ; int arr [ ] = { 2 , 9 , 4 , 3 , 13 } ; int n = arr . length ; nearestGCD ( arr , n ) ; for ( int i = 0 ; i < n ; ++ i ) { System . out . print ( pos [ i ] + " ▁ " ) ; } } }


"Nearest greater number by interchanging the digits | JAVA program to find nearest greater value ; Find all the possible permutation of Value A . ; Convert into Integer ; Find the minimum value of A by interchanging the digit of A and store min1 . ; Swap two string character ; Driver code ; Convert integer value into string to find all the permutation of the number ; count = 1 means number greater than B exists"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int min1 = Integer . MAX_VALUE ; static int count = 0 ; public int permutation ( String str1 , int i , int n , int p ) { if ( i == n ) { int q = Integer . parseInt ( str1 ) ; if ( q - p > 0 && q < min1 ) { min1 = q ; count = 1 ; } } else { for ( int j = i ; j <= n ; j ++ ) { str1 = swap ( str1 , i , j ) ; permutation ( str1 , i + 1 , n , p ) ; str1 = swap ( str1 , i , j ) ; } } return min1 ; } public String swap ( String str , int i , int j ) { char ch [ ] = str . toCharArray ( ) ; char temp = ch [ i ] ; ch [ i ] = ch [ j ] ; ch [ j ] = temp ; return String . valueOf ( ch ) ; } public static void main ( String [ ] args ) { int A = 213 ; int B = 111 ; GFG gfg = new GFG ( ) ; String str1 = Integer . toString ( A ) ; int len = str1 . length ( ) ; int h = gfg . permutation ( str1 , 0 , len - 1 , B ) ; if ( count == 1 ) System . out . println ( h ) ; else System . out . println ( - 1 ) ; } }


"Nearest power of 2 of frequencies of each digit of a given number | Java program for the above approach ; Function to find the nearest power of 2 for all frequencies in the Map freq ; Traverse the Map ; Calculate log of the current array element ; Find the nearest power of 2 for the current frequency ; Function to find nearest power of 2 for frequency of each digit of num ; Length of string ; Stores the frequency of each character in the string ; Traverse the string S ; Function call to generate nearest power of 2 for each frequency ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void nearestPowerOfTwoUtil ( HashMap < Character , Integer > freq ) { for ( char key : freq . keySet ( ) ) { System . out . print ( key + " ▁ - > ▁ " ) ; int lg = ( int ) ( Math . log ( freq . get ( key ) / Math . log ( 2 ) ) ) ; int a = ( int ) Math . pow ( 2 , lg ) ; int b = ( int ) Math . pow ( 2 , lg + 1 ) ; if ( ( freq . get ( key ) - a ) < ( b - freq . get ( key ) ) ) { System . out . println ( a ) ; } else { System . out . println ( b ) ; } } } static void nearestPowerOfTwo ( String S ) { int N = S . length ( ) ; HashMap < Character , Integer > freq = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { freq . put ( S . charAt ( i ) , freq . getOrDefault ( S . charAt ( i ) , 0 ) + 1 ) ; } nearestPowerOfTwoUtil ( freq ) ; } public static void main ( String [ ] args ) { String N = "16333331163" ; nearestPowerOfTwo ( N ) ; } }


"Nearest prime number in the array of every array element | Java program to find nearest prime number in the array for all array elements ; Create a boolean array and set all entries it as false . A value in prime [ i ] will be true if i is not a prime , else false ; Sieve of Eratosthenes function ; Update all multiples of i greater than or equal to the square of it numbers which are multiple of i and are less than i ^ 2 are already been marked . ; Function to find nearest prime number for all elements ; Compute and store all prime numbers up to maxm ; Store the indices of all primes ; If no primes are present in the array ; Store the current prime ; If the no further primes exist in the array ; For all indices less than that of the current prime ; If the current prime is nearer ; If the next prime is nearer ; Make the next prime as the current ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int max = 10000000 ; static boolean [ ] prime = new boolean [ max ] ; static void SieveOfEratosthenes ( int maxm ) { prime [ 0 ] = prime [ 1 ] = true ; for ( int i = 2 ; i * i <= maxm ; i ++ ) { if ( ! prime [ i ] ) { for ( int j = i * i ; j <= maxm ; j += i ) { prime [ j ] = true ; } } } } static void print_nearest_prime ( int arr [ ] , int N ) { int maxm = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; SieveOfEratosthenes ( maxm ) ; Vector < Integer > primes = new Vector < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! prime [ arr [ i ] ] ) primes . add ( i ) ; } if ( primes . size ( ) == 0 ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( - 1 + " ▁ " ) ; } return ; } int curr = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( curr == primes . size ( ) - 1 || i <= primes . get ( curr ) ) { System . out . print ( arr [ primes . get ( curr ) ] + " ▁ " ) ; continue ; } if ( Math . abs ( primes . get ( curr ) - i ) < Math . abs ( primes . get ( curr + 1 ) - i ) ) { System . out . print ( arr [ primes . get ( curr ) ] + " ▁ " ) ; } else { curr ++ ; System . out . print ( arr [ primes . get ( curr ) ] + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int N = 6 ; int arr [ ] = { 8 , 7 , 12 , 15 , 3 , 11 } ; print_nearest_prime ( arr , N ) ; } }


"Nearest smaller character to a character K from a Sorted Array | Java program to implement the above approach ; Function to return the nearest smaller character ; Stores the nearest smaller character ; Iterate till starts cross end ; Find the mid element ; Check if K is found ; Check if current character is less than K ; Increment the start ; Otherwise ; Increment end ; Return the character ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static char bs ( char ar [ ] , int n , int ele ) { int start = 0 ; int end = n - 1 ; char ch = ' @ ' ; while ( start <= end ) { int mid = start + ( end - start ) / 2 ; if ( ar [ mid ] == ele ) end = mid - 1 ; else if ( ar [ mid ] < ele ) { ch = ar [ mid ] ; start = mid + 1 ; } else end = mid - 1 ; } return ch ; } public static void main ( String [ ] args ) { char ar [ ] = { ' e ' , ' g ' , ' t ' , ' y ' } ; int n = ar . length ; char K = ' u ' ; char ch = bs ( ar , n , K ) ; if ( ch == ' @ ' ) System . out . print ( " - 1" ) ; else System . out . print ( ch ) ; } }


"Nearest smaller number to N having multiplicative inverse under modulo N equal to that number | Java program to implement the above approach ; Function to find the nearest smaller number satisfying the condition ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int clstNum ( int N ) { return ( N - 1 ) ; } public static void main ( String [ ] args ) { int N = 11 ; System . out . println ( clstNum ( N ) ) ; } }


"Nearest smaller power of 2 for every digit of a number | Java program to implement the above approach ; Function to find the nearest power of two for every digit of a given number ; Converting number to string ; Traverse the array ; Calculate log base 2 of the current digit s [ i ] ; Highest power of 2 <= s [ i ] ; ASCII conversion ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void highestPowerOfTwo ( int num ) { String s = Integer . toString ( num ) ; for ( int i = 0 ; i < ( int ) s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '0' ) { System . out . print ( "0" ) ; continue ; } int lg = ( int ) ( Math . log ( s . charAt ( i ) - '0' ) / Math . log ( 2 ) ) ; int p = ( int ) Math . pow ( 2 , lg ) ; System . out . print ( ( char ) ( p + 48 ) ) ; } } public static void main ( String args [ ] ) { int num = 4317 ; highestPowerOfTwo ( num ) ; } }


"Nesbitt 's Inequality | Java code to verify Nesbitt 's Inequality ; 3 parts of the inequality sum ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isValidNesbitt ( double a , double b , double c ) { double A = a / ( b + c ) ; double B = b / ( a + c ) ; double C = c / ( a + b ) ; double inequality = A + B + C ; return ( inequality >= 1.5 ) ; } public static void main ( String args [ ] ) { double a = 1.0 , b = 2.0 , c = 3.0 ; if ( isValidNesbitt ( a , b , c ) == true ) { System . out . print ( " Nesbitt ' s ▁ inequality " + " ▁ satisfied . " ) ; System . out . println ( " for ▁ real ▁ numbers ▁ " + a + " , ▁ " + b + " , ▁ " + c ) ; } else System . out . println ( " Nesbitts ▁ inequality " + " ▁ not ▁ satisfied " ) ; } }


"Newman Shanks Williams prime | Java Program for finding Newman - Shanks - Williams prime ; return nth Newman_Shanks_Williams prime ; Base case ; Finding nth Newman Shanks Williams prime ; Driver Program"
How can the above be solved in Java?

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


"Newman | JAVA Code for Newman - Conway Sequence ; Function to find the n - th element ; Declare array to store sequence ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { static int sequence ( int n ) { int f [ ] = new int [ n + 1 ] ; f [ 0 ] = 0 ; f [ 1 ] = 1 ; f [ 2 ] = 1 ; int i ; for ( i = 3 ; i <= n ; i ++ ) f [ i ] = f [ f [ i - 1 ] ] + f [ i - f [ i - 1 ] ] ; return f [ n ] ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( sequence ( n ) ) ; } }


"Newman | Java program to find nth element of Newman - Conway Sequence ; Recursion to find n - th element ; Driver Program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int sequence ( int n ) { if ( n == 1 n == 2 ) return 1 ; else return sequence ( sequence ( n - 1 ) ) + sequence ( n - sequence ( n - 1 ) ) ; } public static void main ( String args [ ] ) { int n = 10 ; System . out . println ( sequence ( n ) ) ; } }


"Newmanâ €“ Shanksâ €“ Williams prime | Java Program to find Newman - Shanks - Williams prime ; return nth Newman - Shanks - Williams prime ; Base case ; Recursive step ; Driver code"
How can the above be solved in Java?

class GFG { static int nswp ( int n ) { if ( n == 0 n == 1 ) return 1 ; return 2 * nswp ( n - 1 ) + nswp ( n - 2 ) ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( nswp ( n ) ) ; } }


"Newton 's Divided Difference Interpolation Formula | Java program for implementing Newton divided difference formula ; Function to find the product term ; Function for calculating divided difference table ; Function for applying Newton 's divided difference formula ; Function for displaying divided difference table ; Driver Function ; number of inputs given ; y [ ] [ ] is used for divided difference table where y [ ] [ 0 ] is used for input ; calculating divided difference table ; displaying divided difference table ; value to be interpolated ; printing the value"
How can the above be solved in Java?

import java . text . * ; import java . math . * ; class GFG { static float proterm ( int i , float value , float x [ ] ) { float pro = 1 ; for ( int j = 0 ; j < i ; j ++ ) { pro = pro * ( value - x [ j ] ) ; } return pro ; } static void dividedDiffTable ( float x [ ] , float y [ ] [ ] , int n ) { for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < n - i ; j ++ ) { y [ j ] [ i ] = ( y [ j ] [ i - 1 ] - y [ j + 1 ] [ i - 1 ] ) / ( x [ j ] - x [ i + j ] ) ; } } } static float applyFormula ( float value , float x [ ] , float y [ ] [ ] , int n ) { float sum = y [ 0 ] [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { sum = sum + ( proterm ( i , value , x ) * y [ 0 ] [ i ] ) ; } return sum ; } static void printDiffTable ( float y [ ] [ ] , int n ) { DecimalFormat df = new DecimalFormat ( " # . # # # # " ) ; df . setRoundingMode ( RoundingMode . HALF_UP ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n - i ; j ++ ) { String str1 = df . format ( y [ i ] [ j ] ) ; System . out . print ( str1 + " 	 ▁ " ) ; } System . out . println ( " " ) ; } } public static void main ( String [ ] args ) { int n = 4 ; float value , sum ; float y [ ] [ ] = new float [ 10 ] [ 10 ] ; float x [ ] = { 5 , 6 , 9 , 11 } ; y [ 0 ] [ 0 ] = 12 ; y [ 1 ] [ 0 ] = 13 ; y [ 2 ] [ 0 ] = 14 ; y [ 3 ] [ 0 ] = 16 ; dividedDiffTable ( x , y , n ) ; printDiffTable ( y , n ) ; value = 7 ; DecimalFormat df = new DecimalFormat ( " # . # # " ) ; df . setRoundingMode ( RoundingMode . HALF_UP ) ; System . out . println ( " Value at " + df . format ( value ) + " is " + df . format ( applyFormula ( value , x , y , n ) ) ) ; } }


"Newton Forward And Backward Interpolation | Java Program to interpolate using newton backward interpolation ; Calculation of u mentioned in formula ; Calculating factorial of given n ; Driver code ; number of values given ; y [ ] [ ] is used for difference table and y [ ] [ 0 ] used for input ; Calculating the backward difference table ; Displaying the backward difference table ; Value to interpolate at ; Initializing u and sum"
How can the above be solved in Java?

class GFG { static double u_cal ( double u , int n ) { double temp = u ; for ( int i = 1 ; i < n ; i ++ ) temp = temp * ( u + i ) ; return temp ; } static int fact ( int n ) { int f = 1 ; for ( int i = 2 ; i <= n ; i ++ ) f *= i ; return f ; } public static void main ( String [ ] args ) { int n = 5 ; double x [ ] = { 1891 , 1901 , 1911 , 1921 , 1931 } ; double [ ] [ ] y = new double [ n ] [ n ] ; y [ 0 ] [ 0 ] = 46 ; y [ 1 ] [ 0 ] = 66 ; y [ 2 ] [ 0 ] = 81 ; y [ 3 ] [ 0 ] = 93 ; y [ 4 ] [ 0 ] = 101 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = n - 1 ; j >= i ; j -- ) y [ j ] [ i ] = y [ j ] [ i - 1 ] - y [ j - 1 ] [ i - 1 ] ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) System . out . print ( y [ i ] [ j ] + " 	 " ) ; System . out . println ( " " ) ; ; } double value = 1925 ; double sum = y [ n - 1 ] [ 0 ] ; double u = ( value - x [ n - 1 ] ) / ( x [ 1 ] - x [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { sum = sum + ( u_cal ( u , i ) * y [ n - 1 ] [ i ] ) / fact ( i ) ; } System . out . println ( " Value at " + value + " ▁ is ▁ " + String . format ( " % .6g % n " , sum ) ) ; } }


"Next Greater Element in a Circular Linked List | Java program for the above approach ; Node structure of the circular Linked list ; Constructor ; Function to print the elements of a Linked list ; Iterate the linked list ; Print the data ; Function to find the next greater element for each node ; Stores the head of circular Linked list ; Stores the head of the resulting linked list ; Stores the temporary head of the resulting Linked list ; Iterate until head is not equal to H ; Used to iterate over the circular Linked List ; Stores if there exist any next Greater element ; Iterate until head is not equal to curr ; If the current node is smaller ; Update the value of Val ; Update curr ; If res is Null ; Create new Node with value curr . data ; Assign address of res to tempList ; Update tempList ; Assign address of the next node to tempList ; Update the value of head node ; Print the resulting Linked list ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static Node head ; static class Node { int data ; Node next ; public Node ( int data ) { this . data = data ; this . next = null ; } } static void print ( Node head ) { Node temp = head ; while ( temp != null ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . next ; } } static void NextGreaterElement ( Node head ) { Node H = head ; Node res = null ; Node tempList = null ; do { Node curr = head ; int Val = - 1 ; do { if ( head . data < curr . data ) { Val = curr . data ; break ; } curr = curr . next ; } while ( curr != head ) ; if ( res == null ) { res = new Node ( Val ) ; tempList = res ; } else { tempList . next = new Node ( Val ) ; tempList = tempList . next ; } head = head . next ; } while ( head != H ) ; print ( res ) ; } public static void main ( String [ ] args ) { head = new Node ( 1 ) ; head . next = new Node ( 5 ) ; head . next . next = new Node ( 12 ) ; head . next . next . next = new Node ( 10 ) ; head . next . next . next . next = new Node ( 0 ) ; head . next . next . next . next . next = head ; NextGreaterElement ( head ) ; } }


"Next Greater Element | Simple Java program to print next greater elements in a given array ; prints element and NGE pair for all elements of arr [ ] of size n ; Driver Code"
How can the above be solved in Java?

class Main { static void printNGE ( int arr [ ] , int n ) { int next , i , j ; for ( i = 0 ; i < n ; i ++ ) { next = - 1 ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] ) { next = arr [ j ] ; break ; } } System . out . println ( arr [ i ] + " ▁ - - ▁ " + next ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 11 , 13 , 21 , 3 } ; int n = arr . length ; printNGE ( arr , n ) ; } }


"Next Number with distinct digits | Java program to find next consecutive Number with all distinct digits ; Function to count distinct digits in a number ; To count the occurrence of digits in number from 0 to 9 ; Iterate over the digits of the number Flag those digits as found in the array ; Traverse the array arr and count the distinct digits in the array ; Function to return the total number of digits in the number ; Iterate over the digits of the number ; Function to return the next number with distinct digits ; Count the distinct digits in N + 1 ; Count the total number of digits in N + 1 ; Return the next consecutive number ; Increment Number by 1 ; Driver code"
How can the above be solved in Java?

class GFG { final static int INT_MAX = Integer . MAX_VALUE ; static int countDistinct ( int n ) { int arr [ ] = new int [ 10 ] ; int count = 0 ; while ( n != 0 ) { int r = n % 10 ; arr [ r ] = 1 ; n /= 10 ; } for ( int i = 0 ; i < 10 ; i ++ ) { if ( arr [ i ] != 0 ) count ++ ; } return count ; } static int countDigit ( int n ) { int c = 0 ; while ( n != 0 ) { int r = n % 10 ; c ++ ; n /= 10 ; } return c ; } static int nextNumberDistinctDigit ( int n ) { while ( n < INT_MAX ) { int distinct_digits = countDistinct ( n + 1 ) ; int total_digits = countDigit ( n + 1 ) ; if ( distinct_digits == total_digits ) { return n + 1 ; } else n ++ ; } return - 1 ; } public static void main ( String [ ] args ) { int n = 2019 ; System . out . println ( nextNumberDistinctDigit ( n ) ) ; } }


"Next Smaller Element | A Stack based Java program to find next smaller element for all array elements in same order as input . ; prints element and NSE pair for all elements of arr [ ] of size n ; push the first element to stack ; iterate for rest of the elements ; if stack is not empty , then pop an element from stack . If the popped element is greater than next , then a ) print the pair b ) keep popping while elements are greater and stack is not empty ; push next to stack so that we can find next smaller for it ; After iterating over the loop , the remaining elements in stack do not have the next smaller element , so print - 1 for them ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { public static void printNSE ( int arr [ ] , int n ) { Stack < Integer > s = new Stack < Integer > ( ) ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; s . push ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( s . empty ( ) ) { s . push ( arr [ i ] ) ; continue ; } while ( s . empty ( ) == false && s . peek ( ) > arr [ i ] ) { mp . put ( s . peek ( ) , arr [ i ] ) ; s . pop ( ) ; } s . push ( arr [ i ] ) ; } while ( s . empty ( ) == false ) { mp . put ( s . peek ( ) , - 1 ) ; s . pop ( ) ; } for ( int i = 0 ; i < n ; i ++ ) System . out . println ( arr [ i ] + " ▁ - - - > ▁ " + mp . get ( arr [ i ] ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 11 , 13 , 21 , 3 } ; int n = arr . length ; printNSE ( arr , n ) ; } }


"Next Smaller Element | A Stack based Java program to find next smaller element for all array elements in same order as input . ; prints element and NSE pair for all elements of arr [ ] of size n ; push the first element to stack ; iterate for rest of the elements ; if stack is not empty , then pop an element from stack . If the popped element is greater than next , then a ) print the pair b ) keep popping while elements are greater and stack is not empty ; push next to stack so that we can find next smaller for it ; After iterating over the loop , the remaining elements in stack do not have the next smaller element , so print - 1 for them ; Driver program to test above functions"
How can the above be solved in Java?


"Next Smaller Element | Simple Java program to print next smaller elements in a given array ; prints element and NSE pair for all elements of arr [ ] of size n ; Driver Code"
How can the above be solved in Java?

class Main { static void printNSE ( int arr [ ] , int n ) { int next , i , j ; for ( i = 0 ; i < n ; i ++ ) { next = - 1 ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] > arr [ j ] ) { next = arr [ j ] ; break ; } } System . out . println ( arr [ i ] + " ▁ - - ▁ " + next ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 11 , 13 , 21 , 3 } ; int n = arr . length ; printNSE ( arr , n ) ; } }


"Next greater Number than N with the same quantity of digits A and B | Java program to find next greater Number than N with the same quantity of digits A and B ; Recursive function to find the required number ; If the resulting number is >= n and count of a = count of b , return the number ; select minimum of two and call the function again ; Function to find the number next greater Number than N with the same quantity of digits A and B ; Driver code"
How can the above be solved in Java?

public class GFG { static long findNumUtil ( long res , int a , int aCount , int b , int bCount , int n ) { if ( res > 1e11 ) return ( long ) 1e11 ; if ( aCount == bCount && res >= n ) return res ; return Math . min ( findNumUtil ( res * 10 + a , a , aCount + 1 , b , bCount , n ) , findNumUtil ( res * 10 + b , a , aCount , b , bCount + 1 , n ) ) ; } static int findNum ( int n , int a , int b ) { int result = 0 ; int aCount = 0 ; int bCount = 0 ; return ( int ) findNumUtil ( result , a , aCount , b , bCount , n ) ; } public static void main ( String args [ ] ) { int N = 4500 ; int A = 4 ; int B = 7 ; System . out . println ( findNum ( N , A , B ) ) ; } }


"Next greater integer having one more number of set bits | Java implementation to find the next greater integer with one more number of set bits ; function to find the position of rightmost set bit . Returns - 1 if there are no set bits ; function to find the next greater integer ; position of rightmost unset bit of n by passing ~ n as argument ; if n consists of unset bits , then set the rightmost unset bit ; n does not consists of unset bits ; Driver code"
How can the above be solved in Java?

class GFG { static int getFirstSetBitPos ( int n ) { return ( ( int ) ( Math . log ( n & - n ) / Math . log ( 2 ) ) + 1 ) - 1 ; } static int nextGreaterWithOneMoreSetBit ( int n ) { int pos = getFirstSetBitPos ( ~ n ) ; if ( pos > - 1 ) return ( 1 << pos ) | n ; return ( ( n << 1 ) + 1 ) ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . print ( " Next ▁ greater ▁ integer ▁ = ▁ " + nextGreaterWithOneMoreSetBit ( n ) ) ; } }


"Next higher number using atmost one swap operation | JAVA implementation to find the next higher number using atmost one swap operation ; function to find the next higher number using atmost one swap operation ; to store the index of the largest digit encountered so far from the right ; to store the index of rightmost digit which has a digit greater to it on its right side ; finding the ' index ' of rightmost digit which has a digit greater to it on its right side ; required digit found , store its ' index ' and break ; if no such digit is found which has a larger digit on its right side ; to store the index of the smallest digit greater than the digit at ' index ' and right to it ; finding the index of the smallest digit greater than the digit at ' index ' and right to it ; swapping the digits ; required number ; Driver program to test above"
How can the above be solved in Java?

class GFG { static String nextHighUsingAtMostOneSwap ( String st ) { char num [ ] = st . toCharArray ( ) ; int l = num . length ; int posRMax = l - 1 ; int index = - 1 ; for ( int i = l - 2 ; i >= 0 ; i -- ) { if ( num [ i ] >= num [ posRMax ] ) posRMax = i ; else { index = i ; break ; } } if ( index == - 1 ) return " Not ▁ Possible " ; int greatSmallDgt = - 1 ; for ( int i = l - 1 ; i > index ; i -- ) { if ( num [ i ] > num [ index ] ) { if ( greatSmallDgt == - 1 ) greatSmallDgt = i ; else if ( num [ i ] <= num [ greatSmallDgt ] ) greatSmallDgt = i ; } } char temp = num [ index ] ; num [ index ] = num [ greatSmallDgt ] ; num [ greatSmallDgt ] = temp ; return ( String . valueOf ( num ) ) ; } public static void main ( String [ ] args ) { String num = "218765" ; System . out . println ( " Original ▁ number : ▁ " + num ) ; System . out . println ( " Next ▁ higher ▁ number : ▁ " + nextHighUsingAtMostOneSwap ( num ) ) ; } }


"Next higher number with same number of set bits | Java Implementation on above approach ; this function returns next higher number with same number of set bits as x . ; right most set bit ; reset the pattern and set next higher bit left part of x will be here ; nextHigherOneBit is now part [ D ] of the above explanation . isolate the pattern ; right adjust pattern ; correction factor ; rightOnesPattern is now part [ A ] of the above explanation . integrate new pattern ( Add [ D ] and [ A ] ) ; Driver code"
How can the above be solved in Java?

class GFG { static int snoob ( int x ) { int rightOne , nextHigherOneBit , rightOnesPattern , next = 0 ; if ( x > 0 ) { rightOne = x & - x ; nextHigherOneBit = x + rightOne ; rightOnesPattern = x ^ nextHigherOneBit ; rightOnesPattern = ( rightOnesPattern ) / rightOne ; rightOnesPattern >>= 2 ; next = nextHigherOneBit | rightOnesPattern ; } return next ; } public static void main ( String [ ] args ) { int x = 156 ; System . out . println ( " Next ▁ higher ▁ number ▁ with ▁ same " + " number ▁ of ▁ set ▁ bits ▁ is ▁ " + snoob ( x ) ) ; } }


"Next higher palindromic number using the same set of digits | Java implementation to find next higher palindromic number using the same set of digits ; function to reverse the digits in the range i to j in ' num ' ; function to find next higher palindromic number using the same set of digits ; if length of number is less than '3' then no higher palindromic number can be formed ; find the index of last digit in the 1 st half of ' num ' ; Start from the ( mid - 1 ) th digit and find the first digit that is smaller than the digit next to it . ; If no such digit is found , then all digits are in descending order which means there cannot be a greater palindromic number with same set of digits ; Find the smallest digit on right side of ith digit which is greater than num [ i ] up to index ' mid ' ; swap num [ i ] with num [ smallest ] ; as the number is a palindrome , the same swap of digits should be performed in the 2 nd half of ' num ' ; reverse digits in the range ( i + 1 ) to mid ; if n is even , then reverse digits in the range mid + 1 to n - i - 2 ; else if n is odd , then reverse digits in the range mid + 2 to n - i - 2 ; required next higher palindromic number ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class NextHigherPalindrome { public static void reverse ( char num [ ] , int i , int j ) { while ( i < j ) { char temp = num [ i ] ; num [ i ] = num [ j ] ; num [ j ] = temp ; i ++ ; j -- ; } } public static void nextPalin ( char num [ ] , int n ) { if ( n <= 3 ) { System . out . println ( " Not ▁ Possible " ) ; return ; } char temp ; int mid = n / 2 - 1 ; int i , j ; for ( i = mid - 1 ; i >= 0 ; i -- ) if ( num [ i ] < num [ i + 1 ] ) break ; if ( i < 0 ) { System . out . println ( " Not ▁ Possible " ) ; return ; } int smallest = i + 1 ; for ( j = i + 2 ; j <= mid ; j ++ ) if ( num [ j ] > num [ i ] && num [ j ] <= num [ smallest ] ) smallest = j ; temp = num [ i ] ; num [ i ] = num [ smallest ] ; num [ smallest ] = temp ; temp = num [ n - i - 1 ] ; num [ n - i - 1 ] = num [ n - smallest - 1 ] ; num [ n - smallest - 1 ] = temp ; reverse ( num , i + 1 , mid ) ; if ( n % 2 == 0 ) reverse ( num , mid + 1 , n - i - 2 ) ; else reverse ( num , mid + 2 , n - i - 2 ) ; String result = String . valueOf ( num ) ; System . out . println ( " Next ▁ Palindrome : ▁ " + result ) ; } public static void main ( String args [ ] ) { String str = "4697557964" ; char num [ ] = str . toCharArray ( ) ; int n = str . length ( ) ; nextPalin ( num , n ) ; } }


"Next word that does not contain a palindrome and has characters from first k | Java program to find lexicographically next word which contains first K letters of the English alphabet and does not contain a palindrome as it 's substring of length more than one. ; function to return lexicographically next word ; we made m as m + 97 that means our required string contains not more than m + 97 ( as per ASCII value ) in it . ; increment last alphabet to make next lexicographically next word . ; if i - th alphabet not in first k letters then make it as " a " and then increase ( i - 1 ) th letter ; to check whether formed string palindrome or not . ; increment i . ; if i less than or equals to one that means we not formed such word . ; Driver code"
How can the above be solved in Java?

public class GFG { static void findNextWord ( char [ ] s , int m ) { m += 97 ; int n = s . length ; int i = s . length - 1 ; s [ i ] ++ ; while ( i >= 0 && i <= n - 1 ) { if ( s [ i ] >= m ) { s [ i ] = ' a ' ; s [ -- i ] ++ ; } else if ( s [ i ] == s [ i - 1 ] s [ i ] == s [ i - 2 ] ) { s [ i ] ++ ; } else { i ++ ; } } if ( i <= - 1 ) { System . out . println ( " - 1" ) ; } else { System . out . println ( s ) ; } } public static void main ( String [ ] args ) { char [ ] str = " abcd " . toCharArray ( ) ; int k = 4 ; findNextWord ( str , k ) ; } }


"Nicomachu 's Theorem | Java program to verify Nicomachu 's Theorem ; Compute sum of cubes ; Check if sum is equal to given formula . ; driver function"
How can the above be solved in Java?

import java . io . * ; class GFG { static void NicomachuTheorum_sum ( int n ) { int sum = 0 ; for ( int k = 1 ; k <= n ; k ++ ) sum += k * k * k ; int triNo = n * ( n + 1 ) / 2 ; if ( sum == triNo * triNo ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String [ ] args ) { int n = 5 ; NicomachuTheorum_sum ( n ) ; } }


"NicomachusÃƒÆ ’ Ã † â €™ Ãƒâ € Ã ¢ â ‚¬ â „¢¢ ÃƒÆ ’ Ã † â €™¢ ÃƒÆ ’¢ Ãƒ ¢ Ã ¢ â ‚¬ Å ¡¬ Ãƒâ €¦¡¬ ÃƒÆ ’ Ã † â €™¢ ÃƒÆ ’¢ Ãƒ ¢ Ã ¢ â ‚¬ Å ¡¬ Ãƒâ €¦¾¢ s Theorem ( Sum of k | Efficient Java code to find sum of k - th group of positive odd integers . ; Return the sum of kth group of positive odd integer . ; Driver program to test above methods"
How can the above be solved in Java?

import java . util . Arrays ; import java . util . Collections ; class GFG { public static int kthgroupsum ( int k ) { return k * k * k ; } public static void main ( String [ ] args ) { int k = 3 ; System . out . print ( kthgroupsum ( k ) ) ; } }


"Nicomachusâ €™ s Theorem ( Sum of k | Java code to find sum of k - th group of positive odd integers . ; Return the sum of k - th group of positive odd integers . ; Finding first element of kth group . ; Finding the sum . ; Driver program to test above methods"
How can the above be solved in Java?

import java . util . Arrays ; import java . util . Collections ; class GFG { public static int kthgroupsum ( int k ) { int cur = ( k * ( k - 1 ) ) + 1 ; int sum = 0 ; while ( k -- > 0 ) { sum += cur ; cur += 2 ; } return sum ; } public static void main ( String [ ] args ) { int k = 3 ; System . out . print ( kthgroupsum ( k ) ) ; } }


"No of Factors of n ! | Java program to count number of factors of n ; Sieve of Eratosthenes to mark all prime number in array prime as 1 ; Initialize all numbers as prime ; Mark composites ; Returns the highest exponent of p in n ! ; Returns the no of factors in n ! ; ans stores the no of factors in n ! ; Find all primes upto n ; Multiply exponent ( of primes ) added with 1 ; if p is a prime then p is also a prime factor of n ! ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void sieve ( int n , int prime [ ] ) { for ( int i = 1 ; i <= n ; i ++ ) prime [ i ] = 1 ; prime [ 1 ] = 0 ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( prime [ i ] == 1 ) { for ( int j = i * i ; j <= n ; j += i ) prime [ j ] = 0 ; } } } static int expFactor ( int n , int p ) { int x = p ; int exponent = 0 ; while ( ( n / x ) > 0 ) { exponent += n / x ; x *= p ; } return exponent ; } static long countFactors ( int n ) { long ans = 1 ; int prime [ ] = new int [ n + 1 ] ; sieve ( n , prime ) ; for ( int p = 1 ; p <= n ; p ++ ) { if ( prime [ p ] == 1 ) ans *= ( expFactor ( n , p ) + 1 ) ; } return ans ; } public static void main ( String args [ ] ) { int n = 16 ; System . out . println ( " Count ▁ of ▁ factors ▁ of ▁ " + n + " ▁ is ▁ " + countFactors ( n ) ) ; } }


"No of pairs ( a [ j ] >= a [ i ] ) with k numbers in range ( a [ i ] , a [ j ] ) that are divisible by x | Java program to calculate the number pairs satisfying th condition ; function to calculate the number of pairs ; traverse through all elements ; current number 's divisor ; use binary search to find the element after k multiples of x ; use binary search to find the element after k + 1 multiples of x so that we get the answer bu subtracting ; the difference of index will be the answer ; Driver code ; function call to get the number of pairs"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countPairs ( int a [ ] , int n , int x , int k ) { Arrays . sort ( a ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int d = ( a [ i ] - 1 ) / x ; int it1 = Arrays . binarySearch ( a , Math . max ( ( d + k ) * x , a [ i ] ) ) ; int it2 = Arrays . binarySearch ( a , Math . max ( ( d + k + 1 ) * x , a [ i ] ) ) ; ans += it1 - it2 ; } return ans ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 3 , 5 , 7 } ; int n = a . length ; int x = 2 , k = 1 ; System . out . println ( countPairs ( a , n , x , k ) ) ; } }


"Noble integers in an array ( count of greater elements is equal to value ) | Java program to find Noble elements in an array . ; Returns a Noble integer if present , else returns - 1. ; If count of greater elements is equal to arr [ i ] ; Driver code"
How can the above be solved in Java?

import java . util . ArrayList ; class GFG { public static int nobleInteger ( int arr [ ] ) { int size = arr . length ; for ( int i = 0 ; i < size ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < size ; j ++ ) if ( arr [ i ] < arr [ j ] ) count ++ ; if ( count == arr [ i ] ) return arr [ i ] ; } return - 1 ; } public static void main ( String args [ ] ) { int [ ] arr = { 10 , 3 , 20 , 40 , 2 } ; int res = nobleInteger ( arr ) ; if ( res != - 1 ) System . out . println ( " The ▁ noble ▁ " + " integer ▁ is ▁ " + res ) ; else System . out . println ( " No ▁ Noble ▁ " + " Integer ▁ Found " ) ; } }


"Noble integers in an array ( count of greater elements is equal to value ) | Java program to find Noble elements in an array . ; Returns a Noble integer if present , else returns - 1. ; Return a Noble element if present before last . ; In case of duplicates , we reach last occurrence here . ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; public class Main { public static int nobleInteger ( int arr [ ] ) { Arrays . sort ( arr ) ; int n = arr . length ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] == arr [ i + 1 ] ) continue ; if ( arr [ i ] == n - i - 1 ) return arr [ i ] ; } if ( arr [ n - 1 ] == 0 ) return arr [ n - 1 ] ; return - 1 ; } public static void main ( String args [ ] ) { int [ ] arr = { 10 , 3 , 20 , 40 , 2 } ; int res = nobleInteger ( arr ) ; if ( res != - 1 ) System . out . println ( " The ▁ noble ▁ integer ▁ is ▁ " + res ) ; else System . out . println ( " No ▁ Noble ▁ Integer ▁ Found " ) ; } }


"Node having maximum number of nodes less than its value in its subtree | Java program for the above approach ; Stores the nodes to be deleted ; Structure of a Tree node ; Function to create a new node ; Function to compare the current node key with keys received from it left & right tree by Post Order traversal ; Base Case ; Find nodes lesser than the current root in the left subtree ; Find nodes lesser than the current root in the right subtree ; Stores all the nodes less than the current node 's ; Add the nodes which are less than current node in left [ ] ; Add the nodes which are less than current node in right [ ] ; Create a combined vector for pass to it 's parent ; Stores key that has maximum nodes ; Return the vector of nodes ; Driver Code ; Given Tree ; Function Call ; Print the node value"
How can the above be solved in Java?

import java . util . * ; class GFG { static HashMap < Integer , Boolean > mp = new HashMap < Integer , Boolean > ( ) ; static int max_v , rootIndex ; static class Node { int key ; Node left , right ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return ( temp ) ; } static Vector < Integer > findNodes ( Node root ) { if ( root == null ) { return new Vector < Integer > ( ) ; } Vector < Integer > left = findNodes ( root . left ) ; Vector < Integer > right = findNodes ( root . right ) ; Vector < Integer > combined = new Vector < Integer > ( ) ; int count = 0 ; for ( int i = 0 ; i < left . size ( ) ; i ++ ) { if ( left . get ( i ) < root . key ) { count += 1 ; } combined . add ( left . get ( i ) ) ; } for ( int i = 0 ; i < right . size ( ) ; i ++ ) { if ( right . get ( i ) < root . key ) { count += 1 ; } combined . add ( right . get ( i ) ) ; } combined . add ( root . key ) ; if ( count > max_v ) { rootIndex = root . key ; max_v = count ; } return combined ; } public static void main ( String [ ] args ) { Node root = newNode ( 3 ) ; root . left = newNode ( 4 ) ; root . right = newNode ( 6 ) ; root . right . left = newNode ( 4 ) ; root . right . right = newNode ( 5 ) ; root . left . left = newNode ( 10 ) ; root . left . right = newNode ( 2 ) ; max_v = 0 ; rootIndex = - 1 ; findNodes ( root ) ; System . out . print ( rootIndex ) ; } }


"Node whose removal minimizes the maximum size forest from an N | Java program to implement the above approach ; Function to create the graph ; Function to traverse the graph and find the minimum of maximum size forest after removing a node ; Traversing every child subtree except the parent node ; Traverse all subtrees ; Update the maximum size of forests ; Update the minimum of maximum size of forests obtained ; Condition to find the minimum of maximum size forest ; Update and store the corresponding node ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int mini = 105 , ans , n ; static Vector < Integer > [ ] g = new Vector [ 100 ] ; static int [ ] size = new int [ 100 ] ; static void create_graph ( ) { g [ 1 ] . add ( 2 ) ; g [ 2 ] . add ( 1 ) ; g [ 1 ] . add ( 3 ) ; g [ 3 ] . add ( 1 ) ; g [ 1 ] . add ( 4 ) ; g [ 4 ] . add ( 1 ) ; g [ 2 ] . add ( 5 ) ; g [ 5 ] . add ( 2 ) ; g [ 2 ] . add ( 6 ) ; g [ 6 ] . add ( 2 ) ; } static void dfs ( int node , int parent ) { size [ node ] = 1 ; int mx = 0 ; for ( int y : g [ node ] ) { if ( y == parent ) continue ; dfs ( y , node ) ; size [ node ] += size [ y ] ; mx = Math . max ( mx , size [ y ] ) ; } mx = Math . max ( mx , n - size [ node ] ) ; if ( mx < mini ) { mini = mx ; ans = node ; } } public static void main ( String [ ] args ) { n = 6 ; for ( int i = 0 ; i < g . length ; i ++ ) g [ i ] = new Vector < Integer > ( ) ; create_graph ( ) ; dfs ( 1 , - 1 ) ; System . out . print ( ans + "
"); } }


"Nodes with prime degree in an undirected Graph | Java implementation of the approach ; To store Prime Numbers ; Function to find the prime numbers till 10 ^ 5 ; Traverse all multiple of i and make it false ; Function to print the nodes having prime degree ; To store Adjacency List of a Graph ; Make Adjacency List ; To precompute prime numbers till 10 ^ 5 ; Traverse each vertex ; Find size of Adjacency List ; If length of Adj [ i ] is Prime then print it ; Driver code ; Vertices and Edges ; Edges ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int n = 10005 ; static boolean [ ] Prime = new boolean [ n + 1 ] ; static void SieveOfEratosthenes ( ) { int i , j ; Prime [ 0 ] = Prime [ 1 ] = false ; for ( i = 2 ; i * i <= 10005 ; i ++ ) { if ( Prime [ i ] ) { for ( j = 2 * i ; j < 10005 ; j += i ) { Prime [ j ] = false ; } } } } static void primeDegreeNodes ( int N , int M , int edges [ ] [ ] ) { Vector < Integer > [ ] Adj = new Vector [ N + 1 ] ; for ( int i = 0 ; i < Adj . length ; i ++ ) Adj [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < M ; i ++ ) { int x = edges [ i ] [ 0 ] ; int y = edges [ i ] [ 1 ] ; Adj [ x ] . add ( y ) ; Adj [ y ] . add ( x ) ; } SieveOfEratosthenes ( ) ; for ( int i = 1 ; i <= N ; i ++ ) { int x = Adj [ i ] . size ( ) ; if ( Prime [ x ] ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 4 , M = 6 ; int edges [ ] [ ] = { { 1 , 2 } , { 1 , 3 } , { 1 , 4 } , { 2 , 3 } , { 2 , 4 } , { 3 , 4 } } ; Arrays . fill ( Prime , true ) ; primeDegreeNodes ( N , M , edges ) ; } }


"Non Fibonacci Numbers | Java program to find n 'th Fibonacci number ; Returns n 'th Non-  Fibonacci number ; curr is to keep track of current fibonacci number , prev is previous , prevPrev is previous of previous . ; While count of non - fibonacci numbers doesn 't become  negative or zero ; Simple Fibonacci number logic ; ( curr - prev - 1 ) is count of non - Fibonacci numbers between curr and prev . ; n might be negative now . Make sure it becomes positive by removing last added gap . ; Now add the positive n to previous Fibonacci number to find the n 'th non-fibonacci. ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int nonFibonacci ( int n ) { int prevPrev = 1 , prev = 2 , curr = 3 ; while ( n > 0 ) { prevPrev = prev ; prev = curr ; curr = prevPrev + prev ; n = n - ( curr - prev - 1 ) ; } n = n + ( curr - prev - 1 ) ; return prev + n ; } public static void main ( String args [ ] ) { System . out . println ( nonFibonacci ( 5 ) ) ; } }


"Non | Efficient Java program to find first non - repeating element . ; Insert all array elements in hash table ; Traverse array again and return first element with count 1. ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int firstNonRepeating ( int arr [ ] , int n ) { Map < Integer , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . containsKey ( arr [ i ] ) ) { m . put ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; } else { m . put ( arr [ i ] , 1 ) ; } } for ( int i = 0 ; i < n ; i ++ ) if ( m . get ( arr [ i ] ) == 1 ) return arr [ i ] ; return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 9 , 4 , 9 , 6 , 7 , 4 } ; int n = arr . length ; System . out . println ( firstNonRepeating ( arr , n ) ) ; } }


"Non | Efficient Java program to print all non - repeating elements . ; Insert all array elements in hash table ; Traverse through map only and using for - each loop for iteration over Map . entrySet ( ) ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void firstNonRepeating ( int arr [ ] , int n ) { Map < Integer , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . containsKey ( arr [ i ] ) ) { m . put ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; } else { m . put ( arr [ i ] , 1 ) ; } } for ( Map . Entry < Integer , Integer > x : m . entrySet ( ) ) if ( x . getValue ( ) == 1 ) System . out . print ( x . getKey ( ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 9 , 4 , 9 , 6 , 7 , 4 } ; int n = arr . length ; firstNonRepeating ( arr , n ) ; } }


"Non | Java program for the above approach ; Function to print all pairs whose sum of Bitwise OR and AND is N ; Iterate from i = 0 to N ; Print pairs ( i , N - i ) ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static void findPairs ( int N ) { for ( int i = 0 ; i <= N ; i ++ ) { System . out . print ( " ( " + i + " , ▁ " + ( N - i ) + " ) , ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 5 ; findPairs ( N ) ; } }


"Non | Java program to count number of ways to connect n ( wheren is even ) points on a circle such that no two connecting lines cross each other and every point is connected with one other point . ; A dynamic programming based function to find nth Catalan number ; Table to store results of subproblems ; Initialize first two values in table ; Fill entries in catalan [ ] using recursive formula ; Return last entry ; Returns count of ways to connect n points on a circle such that no two connecting lines cross each other and every point is connected with one other point . ; Throw error if n is odd ; Else return n / 2 'th  Catalan number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int catalanDP ( int n ) { int [ ] catalan = new int [ n + 1 ] ; catalan [ 0 ] = catalan [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { catalan [ i ] = 0 ; for ( int j = 0 ; j < i ; j ++ ) catalan [ i ] += catalan [ j ] * catalan [ i - j - 1 ] ; } return catalan [ n ] ; } static int countWays ( int n ) { if ( n < 1 ) { System . out . println ( " Invalid " ) ; return 0 ; } return catalanDP ( n / 2 ) ; } public static void main ( String [ ] args ) { System . out . println ( countWays ( 6 ) + " ▁ " ) ; } }


"Non | Java program to find Non - overlapping sum ; function for calculating Non - overlapping sum of two array ; Insert elements of both arrays ; calculate non - overlapped sum ; Driver code ; size of array ; function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int findSum ( int [ ] A , int [ ] B , int n ) { HashMap < Integer , Integer > hash = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( hash . containsKey ( A [ i ] ) ) hash . put ( A [ i ] , 1 + hash . get ( A [ i ] ) ) ; else hash . put ( A [ i ] , 1 ) ; if ( hash . containsKey ( B [ i ] ) ) hash . put ( B [ i ] , 1 + hash . get ( B [ i ] ) ) ; else hash . put ( B [ i ] , 1 ) ; } int sum = 0 ; for ( Map . Entry entry : hash . entrySet ( ) ) { if ( Integer . parseInt ( ( entry . getValue ( ) ) . toString ( ) ) == 1 ) sum += Integer . parseInt ( ( entry . getKey ( ) ) . toString ( ) ) ; } return sum ; } public static void main ( String args [ ] ) { int [ ] A = { 5 , 4 , 9 , 2 , 3 } ; int [ ] B = { 2 , 8 , 7 , 6 , 3 } ; int n = A . length ; System . out . println ( findSum ( A , B , n ) ) ; } }


"Non | Java program to find Non - repeating Primes ; Function to find count of prime ; Find maximum value in the array ; Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to print Non - repeating primes ; Precompute primes using Sieve ; Create HashMap to store frequency of prime numbers ; Traverse through array elements and Count frequencies of all primes ; Traverse through map and print non repeating primes ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Boolean > findPrimes ( int arr [ ] , int n ) { int max_val = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; Vector < Boolean > prime = new Vector < > ( max_val + 1 ) ; for ( int i = 0 ; i < max_val + 1 ; i ++ ) prime . add ( i , Boolean . TRUE ) ; prime . add ( 0 , Boolean . FALSE ) ; prime . add ( 1 , Boolean . FALSE ) ; for ( int p = 2 ; p * p <= max_val ; p ++ ) { if ( prime . get ( p ) == true ) { for ( int i = p * 2 ; i <= max_val ; i += p ) prime . add ( i , Boolean . FALSE ) ; } } return prime ; } static void nonRepeatingPrimes ( int arr [ ] , int n ) { Vector < Boolean > prime = findPrimes ( arr , n ) ; HashMap < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime . get ( arr [ i ] ) ) if ( mp . containsKey ( arr [ i ] ) ) mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; else mp . put ( arr [ i ] , 1 ) ; } for ( Map . Entry < Integer , Integer > entry : mp . entrySet ( ) ) { if ( entry . getValue ( ) == 1 ) System . out . println ( entry . getKey ( ) ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 6 , 7 , 9 , 7 , 23 , 21 , 3 } ; int n = arr . length ; nonRepeatingPrimes ( arr , n ) ; } }


"Non | Java program to find first non - repeating element . ; Driver code"
How can the above be solved in Java?

class GFG { static int firstNonRepeating ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int j ; for ( j = 0 ; j < n ; j ++ ) if ( i != j && arr [ i ] == arr [ j ] ) break ; if ( j == n ) return arr [ i ] ; } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 9 , 4 , 9 , 6 , 7 , 4 } ; int n = arr . length ; System . out . print ( firstNonRepeating ( arr , n ) ) ; } }


"Non | Non - recursive program to delete the entire binary tree ; A binary tree node ; Non - recursive function to delete an entire binary tree . ; Base Case ; Create an empty queue for level order traversal ; Do level order traversal starting from root ; Deletes a tree and sets the root as NULL ; Driver program to test above functions ; create a binary tree ; delete entire binary tree"
How can the above be solved in Java?

import java . util . * ; class Node { int data ; Node left , right ; public Node ( int data ) { this . data = data ; left = right = null ; } } class BinaryTree { Node root ; void _deleteTree ( ) { if ( root == null ) return ; Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; while ( ! q . isEmpty ( ) ) { Node node = q . peek ( ) ; q . poll ( ) ; if ( node . left != null ) q . add ( node . left ) ; if ( node . right != null ) q . add ( node . right ) ; } } void deleteTree ( ) { _deleteTree ( ) ; root = null ; } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 15 ) ; tree . root . left = new Node ( 10 ) ; tree . root . right = new Node ( 20 ) ; tree . root . left . left = new Node ( 8 ) ; tree . root . left . right = new Node ( 12 ) ; tree . root . right . left = new Node ( 16 ) ; tree . root . right . right = new Node ( 25 ) ; tree . deleteTree ( ) ; } }


"Nonagonal number | Java Program find first n nonagonal number . ; Function to find nonagonal number series . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void Nonagonal ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) { System . out . print ( i * ( 7 * i - 5 ) / 2 ) ; System . out . print ( " ▁ " ) ; } } public static void main ( String args [ ] ) { int n = 10 ; Nonagonal ( n ) ; } }


"Nonagonal number | Java Program to find nth nonagonal number . ; Function to find nth nonagonal number . ; Formula to find nth nonagonal number . ; Driver function ."
How can the above be solved in Java?

import java . io . * ; class GFG { static int Nonagonal ( int n ) { return n * ( 7 * n - 5 ) / 2 ; } public static void main ( String args [ ] ) { int n = 10 ; System . out . println ( Nonagonal ( n ) ) ; } }


"Nth Even Fibonacci Number | Java code to find Even Fibonacci Series using normal Recursion ; Function which return nth even fibonnaci number ; calculation of Fn = 4 * ( Fn - 1 ) + Fn - 2 ; Driver Code"
How can the above be solved in Java?

class GFG { static long evenFib ( int n ) { if ( n < 1 ) return n ; if ( n == 1 ) return 2 ; return ( ( 4 * evenFib ( n - 1 ) ) + evenFib ( n - 2 ) ) ; } public static void main ( String [ ] args ) { int n = 7 ; System . out . println ( evenFib ( n ) ) ; } }


"Nth Even length Palindrome | Java program to find nth even length Palindrome ; Function to find nth even length Palindrome ; string r to store resultant palindrome . Initialize same as s ; In this loop string r stores reverse of string s after the string s in consecutive manner ; Driver code ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static String evenlength ( String n ) { String res = n ; for ( int j = n . length ( ) - 1 ; j >= 0 ; -- j ) res += n . charAt ( j ) ; return res ; } public static void main ( String [ ] args ) { String n = "10" ; System . out . println ( evenlength ( n ) ) ; } }


"Nth Square free number | Java Program to find the nth square free number ; Function to find nth square free number ; To maintain count of square free number ; Loop for square free numbers ; Checking whether square of a number is divisible by any number which is a perfect square ; If number is square free ; If the cnt becomes n , return the number ; driven code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int squareFree ( int n ) { int cnt = 0 ; for ( int i = 1 ; ; i ++ ) { boolean isSqFree = true ; for ( int j = 2 ; j * j <= i ; j ++ ) { if ( i % ( j * j ) == 0 ) { isSqFree = false ; break ; } } if ( isSqFree == true ) { cnt ++ ; if ( cnt == n ) return i ; } } } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( " " + squareFree ( n ) ) ; } }


"Nth Square free number | Java Program to find the nth square free number ; Maximum prime number to be considered for square divisibility ; Maximum value of result . We do binary search from 1 to MAX_RES ; 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 ; Store all prime numbers in a [ ] ; Function to count integers upto k which are having perfect squares as factors . i is index of next prime number whose square needs to be checked . curr is current number whos square to be checked . ; variable to store square of prime ; If value of greatest integer becomes zero ; Counting integers with squares as factor ; Inclusion ( Recur for next prime number ) ; Exclusion ( Recur for next prime number ) ; Final count ; Function to return nth square free number ; Computing primes and storing it in an array a [ ] ; Applying binary search ; ' c ' contains Number of square free numbers less than or equal to ' mid ' ; If c < n , then search right side of mid else search left side of mid ; nth square free number ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX_PRIME = 100000 ; static int MAX_RES = 2000000000 ; static void SieveOfEratosthenes ( Vector < Long > a ) { boolean prime [ ] = new boolean [ MAX_PRIME + 1 ] ; Arrays . fill ( prime , true ) ; for ( int p = 2 ; p * p <= MAX_PRIME ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX_PRIME ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= MAX_PRIME ; p ++ ) if ( prime [ p ] ) a . add ( ( long ) p ) ; } static long countSquares ( long i , long cur , long k , Vector < Long > a ) { long square = a . get ( ( int ) i ) * a . get ( ( int ) ( i ) ) ; long newCur = square * cur ; if ( newCur > k ) return 0 ; long cnt = k / ( newCur ) ; cnt += countSquares ( i + 1 , cur , k , a ) ; cnt -= countSquares ( i + 1 , newCur , k , a ) ; return cnt ; } static long squareFree ( long n ) { Vector < Long > a = new Vector < > ( ) ; SieveOfEratosthenes ( a ) ; long low = 1 ; long high = MAX_RES ; while ( low < high ) { long mid = low + ( high - low ) / 2 ; long c = mid - countSquares ( 0 , 1 , mid , a ) ; if ( c < n ) low = mid + 1 ; else high = mid ; } return low ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( squareFree ( n ) ) ; } }


"Nth Subset of the Sequence consisting of powers of K in increasing order of their Sum | Java program for above approach ; Function to print the required N - th subset ; Nearest power of 2 <= N ; Now insert k ^ p in the answer ; update n ; Print the ans in sorted order ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static void printSubset ( long n , int k ) { ArrayList < Long > answer = new ArrayList < > ( ) ; while ( n > 0 ) { long p = ( long ) ( Math . log ( n ) / Math . log ( 2 ) ) ; ; answer . add ( ( long ) ( Math . pow ( k , p ) ) ) ; n %= ( int ) Math . pow ( 2 , p ) ; } Collections . sort ( answer ) ; for ( Long x : answer ) { System . out . print ( x + " ▁ " ) ; } } public static void main ( String [ ] args ) { long n = 5 ; int k = 4 ; printSubset ( n , k ) ; } }


"Nth Subset of the Sequence consisting of powers of K in increasing order of their Sum | Java program to print subset at the nth position ordered by the sum of the elements ; Function to print the elements of the subset at pos n ; Initialize count = 0 and x = 0 ; Create a vector for storing the elements of subsets ; Doing until all the set bits of n are used ; This part is executed only when the last bit is set ; Right shift the bit by one position ; Increasing the count each time by one ; Printing the values os elements ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static void printsubset ( int n , int k ) { int count = 0 , x = 0 ; ArrayList < Integer > vec = new ArrayList < > ( ) ; while ( n != 0 ) { x = n & 1 ; if ( x != 0 ) { vec . add ( ( int ) Math . pow ( k , count ) ) ; } n = n >> 1 ; count ++ ; } for ( int i = 0 ; i < vec . size ( ) ; i ++ ) System . out . print ( vec . get ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 7 , k = 4 ; printsubset ( n , k ) ; } }


"Nth Term of a Fibonacci Series of Primes formed by concatenating pairs of Primes in a given range | Java program to implement the above approach ; Stores at each index if it 's a  prime or not  ; Sieve of Eratosthenes to generate all possible primes ; If p is a prime ; Set all multiples of p as non - prime ; Function to generate the required Fibonacci Series ; Stores all primes between n1 and n2 ; Generate all primes between n1 and n2 ; Stores all concatenations of each pair of primes ; Generate all concatenations of each pair of primes ; Stores the primes out of the numbers generated above ; Store the unique primes ; Find the minimum ; Find the minimum ; Find N ; Print the N - th term of the Fibonacci Series ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int prime [ ] = new int [ 100001 ] ; static void SieveOfEratosthenes ( ) { for ( int i = 0 ; i < 100001 ; i ++ ) prime [ i ] = 1 ; int p = 2 ; while ( p * p <= 100000 ) { if ( prime [ p ] == 1 ) { for ( int i = p * p ; i < 100001 ; i += p ) prime [ i ] = 0 ; } p += 1 ; } } static int join ( int a , int b ) { int mul = 1 ; int bb = b ; while ( b != 0 ) { mul *= 10 ; b /= 10 ; } a *= mul ; a += bb ; return a ; } static void fibonacciOfPrime ( int n1 , int n2 ) { SieveOfEratosthenes ( ) ; Vector < Integer > initial = new Vector < > ( ) ; for ( int i = n1 ; i <= n2 ; i ++ ) if ( prime [ i ] == 1 ) initial . add ( i ) ; Vector < Integer > now = new Vector < > ( ) ; for ( int i = 0 ; i < initial . size ( ) ; i ++ ) { for ( int j = 0 ; j < initial . size ( ) ; j ++ ) { int a = ( int ) initial . get ( i ) ; int b = ( int ) initial . get ( j ) ; if ( a != b ) { int c = join ( a , b ) ; now . add ( c ) ; } } } Vector < Integer > current = new Vector < > ( ) ; for ( int i = 0 ; i < now . size ( ) ; i ++ ) if ( prime [ ( int ) now . get ( i ) ] == 1 ) current . add ( ( int ) now . get ( i ) ) ; int cnt [ ] = new int [ 1000009 ] ; for ( int i = 0 ; i < 1000001 ; i ++ ) cnt [ i ] = 0 ; Vector < Integer > current_set = new Vector < > ( ) ; for ( int i = 0 ; i < current . size ( ) ; i ++ ) { cnt [ ( int ) current . get ( i ) ] ++ ; if ( cnt [ ( int ) current . get ( i ) ] == 1 ) current_set . add ( ( int ) current . get ( i ) ) ; } long first = 1000000000 ; for ( int i = 0 ; i < current_set . size ( ) ; i ++ ) first = Math . min ( first , ( int ) current_set . get ( i ) ) ; long second = 0 ; for ( int i = 0 ; i < current_set . size ( ) ; i ++ ) second = Math . max ( second , ( int ) current_set . get ( i ) ) ; int count = current_set . size ( ) - 1 ; long curr = 1 ; long c = 0 ; while ( curr < count ) { c = first + second ; first = second ; second = c ; curr += 1 ; } System . out . println ( c ) ; } public static void main ( String [ ] args ) { int x = 2 ; int y = 40 ;...


"Nth XOR Fibonacci number | Java implementation of the above approach ; Function to return the nth XOR Fibonacci number ; Driver code"
How can the above be solved in Java?

class GFG { static int nthXorFib ( int n , int a , int b ) { if ( n == 0 ) return a ; if ( n == 1 ) return b ; if ( n == 2 ) return ( a ^ b ) ; return nthXorFib ( n % 3 , a , b ) ; } public static void main ( String [ ] args ) { int a = 1 , b = 2 , n = 10 ; System . out . println ( nthXorFib ( n , a , b ) ) ; } }


"Nth angle of a Polygon whose initial angle and per angle increment is given | Java program for the above approach ; Function to check if the angle is possible or not ; Angular sum of a N - sided polygon ; Angular sum of N - sided given polygon ; Check if both sum are equal ; Function to find the nth angle ; Calculate nth angle ; Return the nth angle ; Driver Code ; Checks the possibility of the polygon exist or not ; Print nth angle of the polygon"
How can the above be solved in Java?

class GFG { static boolean possible ( int N , int a , int b , int n ) { int sum_of_angle = 180 * ( N - 2 ) ; int Total_angle = ( N * ( ( 2 * a ) + ( N - 1 ) * b ) ) / 2 ; if ( sum_of_angle != Total_angle ) return false ; else return true ; } static int nth_angle ( int N , int a , int b , int n ) { int nth = 0 ; nth = a + ( n - 1 ) * b ; return nth ; } public static void main ( String [ ] args ) { int N = 3 , a = 30 , b = 30 , n = 3 ; if ( possible ( N , a , b , n ) ) System . out . print ( nth_angle ( N , a , b , n ) ) ; else System . out . print ( " Not ▁ Possible " ) ; } }


"Nth character in Concatenated Decimal String | Java program to get Nth character in concatenated Decimal String ; Utility method to get dth digit of number N ; Method to return Nth character in concatenated decimal string ; sum will store character escaped till now ; dist will store numbers escaped till now ; loop for number lengths ; nine * len will be incremented characters and nine will be incremented numbers ; restore variables to previous correct state ; get distance from last one digit less maximum number ; d will store dth digit of current number ; method will return dth numbered digit of ( dist + diff ) number ; Driver code"
How can the above be solved in Java?

class GFG { static char getDigit ( int N , int d ) { String str = Integer . toString ( N ) ; return str . charAt ( d - 1 ) ; } static char getNthChar ( int N ) { int sum = 0 , nine = 9 ; int dist = 0 , len ; for ( len = 1 ; ; len ++ ) { sum += nine * len ; dist += nine ; if ( sum >= N ) { sum -= nine * len ; dist -= nine ; N -= sum ; break ; } nine *= 10 ; } int diff = ( int ) ( Math . ceil ( ( double ) ( N ) / ( double ) ( len ) ) ) ; int d = N % len ; if ( d == 0 ) d = len ; return getDigit ( dist + diff , d ) ; } public static void main ( String [ ] args ) { int N = 251 ; System . out . println ( getNthChar ( N ) ) ; } }


"Nth natural number after removing all numbers consisting of the digit 9 | Java program for the above approach ; Function to find Nth number in base 9 ; Stores the Nth number ; Iterate while N is greater than 0 ; Update result ; Divide N by 9 ; Multiply p by 10 ; Return result ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static long findNthNumber ( long N ) { long result = 0 ; long p = 1 ; while ( N > 0 ) { result += ( p * ( N % 9 ) ) ; N = N / 9 ; p = p * 10 ; } return result ; } public static void main ( String [ ] args ) { int N = 9 ; System . out . print ( findNthNumber ( N ) ) ; } }