"Boundary Traversal of binary tree | A binary tree node has data , pointer to left child and a pointer to right child ; A simple function to print leaf nodes of a binary tree ; Print it if it is a leaf node ; A function to print all left boundary nodes , except a leaf node . Print the nodes in TOP DOWN manner ; to ensure top down order , print the node before calling itself for left subtree ; do nothing if it is a leaf node , this way we avoid duplicates in output ; A function to print all right boundary nodes , except a leaf node Print the nodes in BOTTOM UP manner ; to ensure bottom up order , first call for right subtree , then print this node ; do nothing if it is a leaf node , this way we avoid duplicates in output ; A function to do boundary traversal of a given binary tree ; Print the left boundary in top - down manner . ; Print all leaf nodes ; Print the right boundary in bottom - up manner ; Driver program to test above functions"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; void printLeaves ( Node node ) { if ( node == null ) return ; printLeaves ( node . left ) ; if ( node . left == null && node . right == null ) System . out . print ( node . data + " ▁ " ) ; printLeaves ( node . right ) ; } void printBoundaryLeft ( Node node ) { if ( node == null ) return ; if ( node . left != null ) { System . out . print ( node . data + " ▁ " ) ; printBoundaryLeft ( node . left ) ; } else if ( node . right != null ) { System . out . print ( node . data + " ▁ " ) ; printBoundaryLeft ( node . right ) ; } } void printBoundaryRight ( Node node ) { if ( node == null ) return ; if ( node . right != null ) { printBoundaryRight ( node . right ) ; System . out . print ( node . data + " ▁ " ) ; } else if ( node . left != null ) { printBoundaryRight ( node . left ) ; System . out . print ( node . data + " ▁ " ) ; } } void printBoundary ( Node node ) { if ( node == null ) return ; System . out . print ( node . data + " ▁ " ) ; printBoundaryLeft ( node . left ) ; printLeaves ( node . left ) ; printLeaves ( node . right ) ; printBoundaryRight ( node . right ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 20 ) ; tree . root . left = new Node ( 8 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 12 ) ; tree . root . left . right . left = new Node ( 10 ) ; tree . root . left . right . right = new Node ( 14 ) ; tree . root . right = new Node ( 22 ) ; tree . root . right . right = new Node ( 25 ) ; tree . printBoundary ( tree . root ) ; } }


"Boundary Value Analysis : Nature of Roots of a Quadratic equation | Java program to check the nature of the roots ; BVA for nature of roots of a quadratic equation ; If a = 0 , D / 2 a will yield exception Hence it is not a valid Quadratic Equation ; If D > 0 , it will be Real Roots ; If D == 0 , it will be Equal Roots ; If D < 0 , it will be Imaginary Roots ; Function to check for all testcases ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void nature_of_roots ( int a , int b , int c ) { if ( a == 0 ) { System . out . print ( " Not ▁ a ▁ Quadratic ▁ Equation " + "
"); return ; } int D = b * b - 4 * a * c ; if ( D > 0 ) { System . out . print ( " Real ▁ Roots " + "
"); } else if ( D == 0 ) { System . out . print ( " Equal ▁ Roots " + "
"); } else { System . out . print ( " Imaginary ▁ Roots " + "
"); } } static void checkForAllTestCase ( ) { System . out . print ( " Testcase " + " 	 a 	 b 	 c 	 Actual ▁ Output " + "
"); System . out . println ( ) ; int a , b , c ; a = b = c = 0 ; int testcase = 1 ; while ( testcase <= 13 ) { if ( testcase == 1 ) { a = 0 ; b = 50 ; c = 50 ; } else if ( testcase == 2 ) { a = 1 ; b = 50 ; c = 50 ; } else if ( testcase == 3 ) { a = 50 ; b = 50 ; c = 50 ; } else if ( testcase == 4 ) { a = 99 ; b = 50 ; c = 50 ; } else if ( testcase == 5 ) { a = 100 ; b = 50 ; c = 50 ; } else if ( testcase == 6 ) { a = 50 ; b = 0 ; c = 50 ; } else if ( testcase == 7 ) { a = 50 ; b = 1 ; c = 50 ; } else if ( testcase == 8 ) { a = 50 ; b = 99 ; c = 50 ; } else if ( testcase == 9 ) { a = 50 ; b = 100 ; c = 50 ; } else if ( testcase == 10 ) { a = 50 ; b = 50 ; c = 0 ; } else if ( testcase == 11 ) { a = 50 ; b = 50 ; c = 1 ; } else if ( testcase == 12 ) { a = 50 ; b = 50 ; c = 99 ; } else if ( testcase == 13 ) { a = 50 ; b = 50 ; c = 100 ; } System . out . print ( " 	 " + testcase + " 	 " + a + " 	 " + b + " 	 " + c + " 	 " ) ; nature_of_roots ( a , b , c ) ; System . out . println ( ) ; testcase ++ ; } } public static void main ( String [ ] args ) { checkForAllTestCase ( ) ; } }


"Boundary elements of a Matrix | JAVA Code for Boundary elements of a Matrix ; Driver program to test above function"
How can the above be solved in Java?

class GFG { public static void printBoundary ( int a [ ] [ ] , int m , int n ) { for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i == 0 ) System . out . print ( a [ i ] [ j ] + " ▁ " ) ; else if ( i == m - 1 ) System . out . print ( a [ i ] [ j ] + " ▁ " ) ; else if ( j == 0 ) System . out . print ( a [ i ] [ j ] + " ▁ " ) ; else if ( j == n - 1 ) System . out . print ( a [ i ] [ j ] + " ▁ " ) ; else System . out . print ( " ▁ " ) ; } System . out . println ( " " ) ; } } public static void main ( String [ ] args ) { int a [ ] [ ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } } ; printBoundary ( a , 4 , 4 ) ; } }


"Boundary elements of a Matrix | JAVA Code for Finding sum of boundary elements ; Driver program to test above function"
How can the above be solved in Java?

class GFG { public static long getBoundarySum ( int a [ ] [ ] , int m , int n ) { long sum = 0 ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i == 0 ) sum += a [ i ] [ j ] ; else if ( i == m - 1 ) sum += a [ i ] [ j ] ; else if ( j == 0 ) sum += a [ i ] [ j ] ; else if ( j == n - 1 ) sum += a [ i ] [ j ] ; } } return sum ; } public static void main ( String [ ] args ) { int a [ ] [ ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } } ; long sum = getBoundarySum ( a , 4 , 4 ) ; System . out . println ( " Sum ▁ of ▁ boundary ▁ elements " + " ▁ is ▁ " + sum ) ; } }


"Boyer Moore Algorithm for Pattern Searching | Java Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm ; A utility function to get maximum of two integers ; The preprocessing function for Boyer Moore 's  bad character heuristic ; Initialize all occurrences as - 1 ; Fill the actual value of last occurrence of a character ( indeces of table are ascii and values are index of occurence ) ; A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm ; Fill the bad character array by calling the preprocessing function badCharHeuristic ( ) for given pattern ; s is shift of the pattern with respect to text ; there are n - m + 1 potential allignments ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at current shift , then index j will become - 1 after the above loop ; Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern . The condition s + m < n is necessary for the case when pattern occurs at the end of text txt [ s + m ] is character after the pattern in text ; Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern . The max function is used to make sure that we get a positive shift . We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character . ; Driver program to test above function"
How can the above be solved in Java?

class AWQ { static int NO_OF_CHARS = 256 ; static int max ( int a , int b ) { return ( a > b ) ? a : b ; } static void badCharHeuristic ( char [ ] str , int size , int badchar [ ] ) { for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) badchar [ i ] = - 1 ; for ( i = 0 ; i < size ; i ++ ) badchar [ ( int ) str [ i ] ] = i ; } static void search ( char txt [ ] , char pat [ ] ) { int m = pat . length ; int n = txt . length ; int badchar [ ] = new int [ NO_OF_CHARS ] ; badCharHeuristic ( pat , m , badchar ) ; int s = 0 ; while ( s <= ( n - m ) ) { int j = m - 1 ; while ( j >= 0 && pat [ j ] == txt [ s + j ] ) j -- ; if ( j < 0 ) { System . out . println ( " Patterns ▁ occur ▁ at ▁ shift ▁ = ▁ " + s ) ; s += ( s + m < n ) ? m - badchar [ txt [ s + m ] ] : 1 ; } else s += max ( 1 , j - badchar [ txt [ s + j ] ] ) ; } } public static void main ( String [ ] args ) { char txt [ ] = " ABAAABCD " . toCharArray ( ) ; char pat [ ] = " ABC " . toCharArray ( ) ; search ( txt , pat ) ; } }


"Boyer Moore Algorithm for Pattern Searching | Java Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm ; A utility function to get maximum of two integers ; The preprocessing function for Boyer Moore 's  bad character heuristic ; Initialize all occurrences as - 1 ; Fill the actual value of last occurrence of a character ( indices of table are ascii and values are index of occurence ) ; A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm ; Fill the bad character array by calling the preprocessing function badCharHeuristic ( ) for given pattern ; s is shift of the pattern with respect to text there are n - m + 1 potential allignments ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at current shift , then index j will become - 1 after the above loop ; Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern . The condition s + m < n is necessary for the case when pattern occurs at the end of text ; Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern . The max function is used to make sure that we get a positive shift . We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character . ; Driver program to test above function"
How can the above be solved in Java?

class AWQ { static int NO_OF_CHARS = 256 ; static int max ( int a , int b ) { return ( a > b ) ? a : b ; } static void badCharHeuristic ( char [ ] str , int size , int badchar [ ] ) { for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) badchar [ i ] = - 1 ; for ( int i = 0 ; i < size ; i ++ ) badchar [ ( int ) str [ i ] ] = i ; } static void search ( char txt [ ] , char pat [ ] ) { int m = pat . length ; int n = txt . length ; int badchar [ ] = new int [ NO_OF_CHARS ] ; badCharHeuristic ( pat , m , badchar ) ; int s = 0 ; while ( s <= ( n - m ) ) { int j = m - 1 ; while ( j >= 0 && pat [ j ] == txt [ s + j ] ) j -- ; if ( j < 0 ) { System . out . println ( " Patterns ▁ occur ▁ at ▁ shift ▁ = ▁ " + s ) ; s += ( s + m < n ) ? m - badchar [ txt [ s + m ] ] : 1 ; } else s += max ( 1 , j - badchar [ txt [ s + j ] ] ) ; } } public static void main ( String [ ] args ) { char txt [ ] = " ABAAABCD " . toCharArray ( ) ; char pat [ ] = " ABC " . toCharArray ( ) ; search ( txt , pat ) ; } }


"Boyer Moore Algorithm | Good Suffix heuristic | Java program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern in given text string ; preprocessing for strong good suffix rule ; m is the length of pattern ; if character at position i - 1 is not equivalent to character at j - 1 , then continue searching to right of the pattern for border ; the character preceding the occurrence of t in pattern P is different than the mismatching character in P , we stop skipping the occurrences and shift the pattern from i to j ; Update the position of next border ; p [ i - 1 ] matched with p [ j - 1 ] , border is found . store the beginning position of border ; Preprocessing for case 2 ; set the border position of the first character of the pattern to all indices in array shift having shift [ i ] = 0 ; suffix becomes shorter than bpos [ 0 ] , use the position of next widest border as value of j ; Search for a pattern in given text using Boyer Moore algorithm with Good suffix rule ; s is shift of the pattern with respect to text ; initialize all occurrence of shift to 0 ; do preprocessing ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at the current shift , then index j will become - 1 after the above loop ; pat [ i ] != pat [ s + j ] so shift the pattern shift [ j + 1 ] times ; Driver Code"
How can the above be solved in Java?

 class GFG { static void preprocess_strong_suffix ( int [ ] shift , int [ ] bpos , char [ ] pat , int m ) { int i = m , j = m + 1 ; bpos [ i ] = j ; while ( i > 0 ) { while ( j <= m && pat [ i - 1 ] != pat [ j - 1 ] ) { if ( shift [ j ] == 0 ) shift [ j ] = j - i ; j = bpos [ j ] ; } i -- ; j -- ; bpos [ i ] = j ; } } static void preprocess_case2 ( int [ ] shift , int [ ] bpos , char [ ] pat , int m ) { int i , j ; j = bpos [ 0 ] ; for ( i = 0 ; i <= m ; i ++ ) { if ( shift [ i ] == 0 ) shift [ i ] = j ; if ( i == j ) j = bpos [ j ] ; } } static void search ( char [ ] text , char [ ] pat ) { int s = 0 , j ; int m = pat . length ; int n = text . length ; int [ ] bpos = new int [ m + 1 ] ; int [ ] shift = new int [ m + 1 ] ; for ( int i = 0 ; i < m + 1 ; i ++ ) shift [ i ] = 0 ; preprocess_strong_suffix ( shift , bpos , pat , m ) ; preprocess_case2 ( shift , bpos , pat , m ) ; while ( s <= n - m ) { j = m - 1 ; while ( j >= 0 && pat [ j ] == text [ s + j ] ) j -- ; if ( j < 0 ) { System . out . printf ( "pattern occurs at shift = %d
", s); s += shift [ 0 ] ; } else s += shift [ j + 1 ] ; } } public static void main ( String [ ] args ) { char [ ] text = " ABAAAABAACD " . toCharArray ( ) ; char [ ] pat = " ABA " . toCharArray ( ) ; search ( text , pat ) ; } }


"Brahmagupta Fibonacci Identity | Java code to verify Brahmagupta Fibonacci identity ; represent the product as sum of 2 squares ; check identity criteria ; Driver code ; 1 ^ 2 + 2 ^ 2 ; 3 ^ 2 + 4 ^ 2 ; express product of sum of 2 squares as sum of ( sum of 2 squares )"
How can the above be solved in Java?

class GFG { static void find_sum_of_two_squares ( int a , int b ) { int ab = a * b ; for ( int i = 0 ; i * i <= ab ; i ++ ) { for ( int j = i ; i * i + j * j <= ab ; j ++ ) { if ( i * i + j * j == ab ) System . out . println ( i + " ^ 2 ▁ + ▁ " + j + " ^ 2 ▁ = ▁ " + ab ) ; } } } public static void main ( String [ ] args ) { int a = 1 * 1 + 2 * 2 ; int b = 3 * 3 + 4 * 4 ; System . out . println ( " Representation ▁ of ▁ a ▁ * ▁ b ▁ " + " as ▁ sum ▁ of ▁ 2 ▁ squares : " ) ; find_sum_of_two_squares ( a , b ) ; } }


"Break a number such that sum of maximum divisors of all parts is minimum | JAVA Code for Break a number such that sum of maximum divisors of all parts is minimum ; Function to check if a number is prime or not . ; If n is an even number ( we can write it as sum of two primes ) ; If n is odd and n - 2 is prime . ; If n is odd , n - 3 must be even . ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isPrime ( int n ) { int i = 2 ; while ( i * i <= n ) { if ( n % i == 0 ) return false ; i ++ ; } return true ; } static int minimumSum ( int n ) { if ( isPrime ( n ) ) return 1 ; if ( n % 2 == 0 ) return 2 ; if ( isPrime ( n - 2 ) ) return 2 ; return 3 ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( minimumSum ( n ) ) ; } }


"Break the number into three parts | Java program to count number of ways to break a number in three parts ; Function to count number of ways to make the given number n ; driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static long count_of_ways ( long n ) { long count = 0 ; count = ( n + 1 ) * ( n + 2 ) / 2 ; return count ; } public static void main ( String [ ] args ) { long n = 3 ; System . out . println ( count_of_ways ( n ) ) ; } }


"Breaking a number such that first part is integral division of second by a power of 10 | Java program to count ways to divide a String in two parts a and b such that b / pow ( 10 , p ) == a ; subString representing int a ; no of digits in a ; consider only most significant l1 characters of remaining String for int b ; if any of a or b contains leading 0 s discard this combination ; if both are equal ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int calculate ( String N ) { int len = N . length ( ) ; int l = ( len ) / 2 ; int count = 0 ; for ( int i = 1 ; i <= l ; i ++ ) { String s = N . substring ( 0 , i ) ; int l1 = s . length ( ) ; String t = N . substring ( i , l1 + i ) ; if ( s . charAt ( 0 ) == '0' || t . charAt ( 0 ) == '0' ) continue ; if ( s . compareTo ( t ) == 0 ) count ++ ; } return count ; } public static void main ( String [ ] args ) { String N = "2202200" ; System . out . print ( calculate ( N ) ) ; } }


"Breaking an Integer to get Maximum Product |  ; The main function that returns the max possible product ; n equals to 2 or 3 must be handled explicitly ; Keep removing parts of size 3 while n is greater than 4 ; Keep multiplying 3 to res ; The last part multiplied by previous parts ; Driver code"
How can the above be solved in Java?

public class GFG { static int maxProd ( int n ) { if ( n == 2 n == 3 ) return ( n - 1 ) ; int res = 1 ; while ( n > 4 ) { n -= 3 ; res *= 3 ; } return ( n * res ) ; } public static void main ( String [ ] args ) { System . out . println ( " Maximum ▁ Product ▁ is ▁ " + maxProd ( 45 ) ) ; } }


"Breaking an Integer to get Maximum Product | Java program to find maximum product by breaking the Integer ; method return x ^ a in log ( a ) time ; Method returns maximum product obtained by breaking N ; base case 2 = 1 + 1 ; base case 3 = 2 + 1 ; breaking based on mod with 3 ; If divides evenly , then break into all 3 ; If division gives mod as 1 , then break as 4 + power of 3 for remaining part ; If division gives mod as 2 , then break as 2 + power of 3 for remaining part ; Driver code to test above methods"
How can the above be solved in Java?

class GFG { static int power ( int x , int a ) { int res = 1 ; while ( a > 0 ) { if ( ( a & 1 ) > 0 ) res = res * x ; x = x * x ; a >>= 1 ; } return res ; } static int breakInteger ( int N ) { if ( N == 2 ) return 1 ; if ( N == 3 ) return 2 ; int maxProduct = - 1 ; switch ( N % 3 ) { case 0 : maxProduct = power ( 3 , N / 3 ) ; break ; case 1 : maxProduct = 2 * 2 * power ( 3 , ( N / 3 ) - 1 ) ; break ; case 2 : maxProduct = 2 * power ( 3 , N / 3 ) ; break ; } return maxProduct ; } public static void main ( String [ ] args ) { int maxProduct = breakInteger ( 10 ) ; System . out . println ( maxProduct ) ; } }


"Brilliant Numbers | Java implementation for the above approach ; Function to generate all prime numbers less than n ; Initialize all entries of boolean array as true . A value in isPrime [ i ] will finally be false if i is Not a prime ; If isPrime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to return the number of digits in a number ; Function to check if N is a Brilliant number ; Generating primes using Sieve ; Traversing all numbers to find first pair ; Driver Code ; Given Number ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void SieveOfEratosthenes ( int n , boolean isPrime [ ] ) { isPrime [ 0 ] = isPrime [ 1 ] = false ; for ( int i = 2 ; i <= n ; i ++ ) isPrime [ i ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( isPrime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) isPrime [ i ] = false ; } } } static int countDigit ( int n ) { int count = 0 ; while ( n != 0 ) { n = n / 10 ; ++ count ; } return count ; } static boolean isBrilliant ( int n ) { int flag = 0 ; boolean isPrime [ ] = new boolean [ n + 1 ] ; SieveOfEratosthenes ( n , isPrime ) ; for ( int i = 2 ; i < n ; i ++ ) { int x = n / i ; if ( isPrime [ i ] && isPrime [ x ] && ( x * i ) == n ) { if ( countDigit ( i ) == countDigit ( x ) ) return true ; } } return false ; } public static void main ( String [ ] args ) { int n = 1711 ; if ( isBrilliant ( n ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Bubble Sort On Doubly Linked List | Java program to sort a doubly linked list using bubble sort ; structure of a node ; Function to insert a node at the beginning of a linked list ; Function to print nodes in a given linked list ; Bubble sort the given linked list ; Checking for empty list ; Driver code ; start with empty linked list ; Create linked list from the array arr [ ] . Created linked list will be 1 -> 11 -> 2 -> 56 -> 12 ; print list before sorting ; sort the linked list ; print list after sorting"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node prev ; Node next ; } ; static Node insertAtTheBegin ( Node start_ref , int data ) { Node ptr1 = new Node ( ) ; ptr1 . data = data ; ptr1 . next = start_ref ; if ( start_ref != null ) ( start_ref ) . prev = ptr1 ; start_ref = ptr1 ; return start_ref ; } static void printList ( Node start ) { Node temp = start ; System . out . println ( ) ; while ( temp != null ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . next ; } } static Node bubbleSort ( Node start ) { int swapped , i ; Node ptr1 ; Node lptr = null ; if ( start == null ) return null ; do { swapped = 0 ; ptr1 = start ; while ( ptr1 . next != lptr ) { if ( ptr1 . data > ptr1 . next . data ) { int t = ptr1 . data ; ptr1 . data = ptr1 . next . data ; ptr1 . next . data = t ; swapped = 1 ; } ptr1 = ptr1 . next ; } lptr = ptr1 ; } while ( swapped != 0 ) ; return start ; } public static void main ( String args [ ] ) { int arr [ ] = { 12 , 56 , 2 , 11 , 1 , 90 } ; int list_size , i ; Node start = null ; for ( i = 0 ; i < 6 ; i ++ ) start = insertAtTheBegin ( start , arr [ i ] ) ; System . out . printf ( " Linked list before sorting "); printList ( start ) ; start = bubbleSort ( start ) ; System . out . printf ( " Linked list after sorting "); printList ( start ) ; } }


"Bucket Sort To Sort an Array with Negative Numbers | Java program to sort an array of positive and negative numbers using bucket sort ; Function to sort arr [ ] of size n using bucket sort ; 1 ) Create n empty buckets ; 2 ) Put array elements in different buckets ; int bi = ( int ) ( n * arr . get ( i ) ) ; Index in bucket ; 3 ) Sort individual buckets ; 4 ) Concatenate all buckets into arr [ ] ; This function mainly splits array into two and then calls bucketSort ( ) for two arrays . ; traverse array elements ; store - Ve elements by converting into + ve element ; store + ve elements ; First store elements of Neg [ ] array by converting into - ve ; store + ve element ; Driver program to test above function"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void bucketSort ( Vector < Double > arr , int n ) { @ SuppressWarnings ( " unchecked " ) Vector < Double > b [ ] = new Vector [ n ] ; for ( int i = 0 ; i < b . length ; i ++ ) b [ i ] = new Vector < Double > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { b [ bi ] . add ( arr . get ( i ) ) ; } for ( int i = 0 ; i < n ; i ++ ) Collections . sort ( b [ i ] ) ; int index = 0 ; arr . clear ( ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < b [ i ] . size ( ) ; j ++ ) arr . add ( b [ i ] . get ( j ) ) ; } static void sortMixed ( double arr [ ] , int n ) { Vector < Double > Neg = new Vector < > ( ) ; Vector < Double > Pos = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) Neg . add ( - 1 * arr [ i ] ) ; else Pos . add ( arr [ i ] ) ; } bucketSort ( Neg , ( int ) Neg . size ( ) ) ; bucketSort ( Pos , ( int ) Pos . size ( ) ) ; for ( int i = 0 ; i < Neg . size ( ) ; i ++ ) arr [ i ] = - 1 * Neg . get ( Neg . size ( ) - 1 - i ) ; for ( int j = Neg . size ( ) ; j < n ; j ++ ) arr [ j ] = Pos . get ( j - Neg . size ( ) ) ; } public static void main ( String [ ] args ) { double arr [ ] = { - 0.897 , 0.565 , 0.656 , - 0.1234 , 0 , 0.3434 } ; int n = arr . length ; sortMixed ( arr , n ) ; System . out . print ( "Sorted array is
"); for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Bucket Sort | Java program to sort an array using bucket sort ; Function to sort arr [ ] of size n using bucket sort ; 1 ) Create n empty buckets ; 2 ) Put array elements in different buckets ; 3 ) Sort individual buckets ; 4 ) Concatenate all buckets into arr [ ] ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . util . Collections ; class GFG { static void bucketSort ( float arr [ ] , int n ) { if ( n <= 0 ) return ; @ SuppressWarnings ( " unchecked " ) Vector < Float > [ ] buckets = new Vector [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { buckets [ i ] = new Vector < Float > ( ) ; } for ( int i = 0 ; i < n ; i ++ ) { float idx = arr [ i ] * n ; buckets [ ( int ) idx ] . add ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) { Collections . sort ( buckets [ i ] ) ; } int index = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < buckets [ i ] . size ( ) ; j ++ ) { arr [ index ++ ] = buckets [ i ] . get ( j ) ; } } } public static void main ( String args [ ] ) { float arr [ ] = { ( float ) 0.897 , ( float ) 0.565 , ( float ) 0.656 , ( float ) 0.1234 , ( float ) 0.665 , ( float ) 0.3434 } ; int n = arr . length ; bucketSort ( arr , n ) ; System . out . println ( " Sorted ▁ array ▁ is ▁ " ) ; for ( float el : arr ) { System . out . print ( el + " ▁ " ) ; } } }


"Build a DFA to accept Binary strings that starts or ends with "01" | Java program to check if a string either starts or ends with 01 ; Function for transition state A ; State transition to B if the character is 0 ; State transition to D if the character is 1 ; Function for transition state B ; Check if the string has ended ; State transition to C if the character is 1 ; State transition to D if the character is 0 ; Function for transition state C ; Function for transition state D ; State transition to D if the character is 1 ; State transition to E if the character is 0 ; Function for transition state E ; State transition to E if the character is 0 ; State transition to F if the character is 1 ; Function for transition state F ; State transition to D if the character is 1 ; State transition to E if the character is 0 ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void checkstateA ( String n ) { if ( n . charAt ( 0 ) == '0' ) stateB ( n . substring ( 1 ) ) ; else stateD ( n . substring ( 1 ) ) ; } static void stateB ( String n ) { if ( n . length ( ) == 0 ) System . out . println ( " string ▁ not ▁ accepted " ) ; else { if ( n . charAt ( 0 ) == '1' ) stateC ( n . substring ( 1 ) ) ; else stateD ( n . substring ( 1 ) ) ; } } static void stateC ( String n ) { System . out . println ( " String ▁ accepted " ) ; } static void stateD ( String n ) { if ( n . length ( ) == 0 ) System . out . println ( " string ▁ not ▁ accepted " ) ; else { if ( n . charAt ( 0 ) == '1' ) stateD ( n . substring ( 1 ) ) ; else stateE ( n . substring ( 1 ) ) ; } } static void stateE ( String n ) { if ( n . length ( ) == 0 ) System . out . println ( " string ▁ not ▁ accepted " ) ; else { if ( n . charAt ( 0 ) == '0' ) stateE ( n . substring ( 1 ) ) ; else stateF ( n . substring ( 1 ) ) ; } } static void stateF ( String n ) { if ( n . length ( ) == 0 ) System . out . println ( " string ▁ accepred " ) ; else { if ( n . charAt ( 0 ) == '1' ) stateD ( n . substring ( 1 ) ) ; else stateE ( n . substring ( 1 ) ) ; } } public static void main ( String args [ ] ) { String n = "0100101" ; checkstateA ( n ) ; } }


"Build original array from the given sub | Java implementation of the approach ; Function to add edge to graph ; Function to calculate indegrees of all the vertices ; If there is an edge from i to x then increment indegree of x ; Function to perform topological sort ; Push every node to the queue which has no incoming edge ; Since edge u is removed , update the indegrees of all the nodes which had an incoming edge from u ; Function to generate the array from the given sub - sequences ; Create the graph from the input sub - sequences ; Add edge between every two consecutive elements of the given sub - sequences ; Get the indegrees for all the vertices ; Get the topological order of the created graph ; Driver code ; Size of the required array ; Given sub - sequences of the array ; Get the resultant array as vector ; Printing the array"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void addEdge ( ArrayList < ArrayList < Integer > > adj , int u , int v ) { adj . get ( u ) . add ( v ) ; } static void getindeg ( ArrayList < ArrayList < Integer > > adj , int V , ArrayList < Integer > indeg ) { for ( int i = 0 ; i < V ; i ++ ) { for ( int x : adj . get ( i ) ) { indeg . set ( x , indeg . get ( x ) + 1 ) ; } } } static ArrayList < Integer > topo ( ArrayList < ArrayList < Integer > > adj , int V , ArrayList < Integer > indeg ) { Queue < Integer > q = new LinkedList < > ( ) ; for ( int i = 0 ; i < V ; i ++ ) { if ( indeg . get ( i ) == 0 ) { q . add ( i ) ; } } ArrayList < Integer > res = new ArrayList < Integer > ( ) ; while ( q . size ( ) > 0 ) { int u = q . poll ( ) ; res . add ( u ) ; for ( int x : adj . get ( u ) ) { indeg . set ( x , indeg . get ( x ) - 1 ) ; if ( indeg . get ( x ) == 0 ) { q . add ( x ) ; } } } return res ; } static ArrayList < Integer > makearray ( ArrayList < ArrayList < Integer > > v , int V ) { ArrayList < ArrayList < Integer > > adj = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 0 ; i < V ; i ++ ) { adj . add ( new ArrayList < Integer > ( ) ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { for ( int j = 0 ; j < v . get ( i ) . size ( ) - 1 ; j ++ ) { addEdge ( adj , v . get ( i ) . get ( j ) , v . get ( i ) . get ( j + 1 ) ) ; } } ArrayList < Integer > indeg = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < V ; i ++ ) { indeg . add ( 0 ) ; } getindeg ( adj , V , indeg ) ; ArrayList < Integer > res = topo ( adj , V , indeg ) ; return res ; } public static void main ( String [ ] args ) { int n = 10 ; ArrayList < ArrayList < Integer > > subseqs = new ArrayList < ArrayList < Integer > > ( ) ; subseqs . add ( new ArrayList < Integer > ( Arrays . asList ( 9 , 1 , 2 , 8 , 3 ) ) ) ; subseqs . add ( new ArrayList < Integer > ( Arrays . asList ( 6 , 1 , 2 ) ) ) ; subseqs . add ( new ArrayList < Integer > ( Arrays . asList ( 9 , 6 , 3 , 4 ) ) ) ; subseqs . add ( new ArrayList < Integer >...


"Burst Balloon to maximize coins | Java program to illustrate Burst balloon problem ; Add Bordering Balloons ; Declaring DP array ; For a sub - array from indices left , right . This innermost loop finds the last balloon burst ; Driver code ; Size of the array ; Calling function"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { public static int getMax ( int [ ] A , int N ) { int [ ] B = new int [ N + 2 ] ; B [ 0 ] = B [ N + 1 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) B [ i ] = A [ i - 1 ] ; int [ ] [ ] dp = new int [ N + 2 ] [ N + 2 ] ; for ( int length = 1 ; length < N + 1 ; length ++ ) { for ( int left = 1 ; left < N - length + 2 ; left ++ ) { int right = left + length - 1 ; for ( int last = left ; last < right + 1 ; last ++ ) { dp [ left ] [ right ] = Math . max ( dp [ left ] [ right ] , dp [ left ] [ last - 1 ] + B [ left - 1 ] * B [ last ] * B [ right + 1 ] + dp [ last + 1 ] [ right ] ) ; } } } return dp [ 1 ] [ N ] ; } public static void main ( String args [ ] ) { int [ ] A = { 1 , 2 , 3 , 4 , 5 } ; int N = A . length ; System . out . println ( getMax ( A , N ) ) ; } }


"Buy minimum items without change and given coins | Java implementation of above approach ; See if we can buy less than 10 items Using 10 Rs coins and one r Rs coin ; We can always buy 10 items ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minItems ( int k , int r ) { for ( int i = 1 ; i < 10 ; i ++ ) if ( ( i * k - r ) % 10 == 0 || ( i * k ) % 10 == 0 ) return i ; return 10 ; } public static void main ( String args [ ] ) { int k = 15 ; int r = 2 ; System . out . println ( minItems ( k , r ) ) ; } }


"C ++ program to concatenate a string given number of times | Java program to concatenate given string n number of times ; Function which return string by concatenating it . ; Copying given string to temporary string . ; Concatenating strings ; Driver code"
How can the above be solved in Java?

class GFG { static String repeat ( String s , int n ) { String s1 = s ; for ( int i = 1 ; i < n ; i ++ ) s += s1 ; return s ; } public static void main ( String [ ] args ) { String s = " geeks " ; int n = 3 ; System . out . println ( repeat ( s , n ) ) ; } }


"C Program To Check whether Matrix is Skew Symmetric or not | java program to check whether given matrix is skew - symmetric or not ; Utility function to create transpose matrix ; Utility function to check skew - symmetric matrix condition ; Utility function to print a matrix ; Driver program to test above functions ; Function create transpose matrix ; Check whether matrix is skew - symmetric or not"
How can the above be solved in Java?

import java . io . * ; class GFG { static int ROW = 3 ; static int COL = 3 ; static void transpose ( int transpose_matrix [ ] [ ] , int matrix [ ] [ ] ) { for ( int i = 0 ; i < ROW ; i ++ ) for ( int j = 0 ; j < COL ; j ++ ) transpose_matrix [ j ] [ i ] = matrix [ i ] [ j ] ; } static boolean check ( int transpose_matrix [ ] [ ] , int matrix [ ] [ ] ) { for ( int i = 0 ; i < ROW ; i ++ ) for ( int j = 0 ; j < COL ; j ++ ) if ( matrix [ i ] [ j ] != - transpose_matrix [ i ] [ j ] ) return false ; return true ; } static void printMatrix ( int matrix [ ] [ ] ) { for ( int i = 0 ; i < ROW ; i ++ ) { for ( int j = 0 ; j < COL ; j ++ ) System . out . print ( matrix [ i ] [ j ] + " ▁ " ) ; System . out . println ( ) ; } } public static void main ( String [ ] args ) { int matrix [ ] [ ] = { { 0 , 5 , - 4 } , { - 5 , 0 , 1 } , { 4 , - 1 , 0 } , } ; int transpose_matrix [ ] [ ] = new int [ ROW ] [ COL ] ; transpose ( transpose_matrix , matrix ) ; System . out . println ( " Transpose ▁ matrix : ▁ " ) ; printMatrix ( transpose_matrix ) ; if ( check ( transpose_matrix , matrix ) ) System . out . println ( " Skew ▁ Symmetric ▁ Matrix " ) ; else System . out . println ( " Not ▁ Skew ▁ Symmetric ▁ Matrix " ) ; } }


"Cake Distribution Problem | Java implementation of the approach ; Function to return the remaining count of cakes ; Sum for 1 cycle ; no . of full cycle and remainder ; Driver Code"
How can the above be solved in Java?

class GFG { static int cntCakes ( int n , int m ) { int sum = ( n * ( n + 1 ) ) / 2 ; int quo = m / sum ; int rem = m % sum ; double ans = m - quo * sum ; double x = ( - 1 + Math . pow ( ( 8 * rem ) + 1 , 0.5 ) ) / 2 ; ans = ans - x * ( x + 1 ) / 2 ; return ( int ) ans ; } public static void main ( String [ ] args ) { int n = 3 ; int m = 8 ; int ans = cntCakes ( n , m ) ; System . out . println ( ans ) ; } }


"Calculate Root Mean Kth power of all array elements | Java program for the above approach ; Function to find the Nth root ; Initially guessing random numberbetween 0 and 9 ; Smaller eps for more accuracy ; Initialize difference between the two roots by Integer . MAX_VALUE ; xK denotes current value of x ; Iterate until desired accuracy is reached ; Find the current value from previous value by newton 's method ; Function to calculate the Root Mean kth power of array elements ; Calculate sum of kth power ; Calculate Mean ; Calculate kth Root of mean ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static double nthRoot ( int A , int N ) { double xPre = ( Math . random ( ) * 10 ) % 10 ; double eps = 1e-3 ; double delX = Integer . MAX_VALUE ; double xK = 0 ; while ( delX > eps ) { xK = ( ( N - 1.0 ) * xPre + ( double ) A / Math . pow ( xPre , N - 1 ) ) / ( double ) N ; delX = Math . abs ( xK - xPre ) ; xPre = xK ; } return xK ; } static float RMNValue ( int arr [ ] , int n , int k ) { int Nth = 0 ; float mean = 0 , root = 0 ; for ( int i = 0 ; i < n ; i ++ ) { Nth += Math . pow ( arr [ i ] , k ) ; } mean = ( Nth / ( float ) ( n ) ) ; root = ( float ) nthRoot ( ( int ) mean , k ) ; return root ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 4 , 6 , 8 } ; int N = arr . length ; int K = 3 ; System . out . print ( RMNValue ( arr , N , K ) ) ; } }


"Calculate Sum of ratio of special characters to length of substrings of the given string | Java Program to implement the above approach ; Stores frequency of special characters in the array ; Stores prefix sum ; Function to check whether a character is special or not ; If current character is special ; Otherwise ; Function to find sum of ratio of count of special characters and length of subStrings ; Calculate the prefix sum of special nodes ; Generate prefix sum array ; Calculate ratio for subString ; Driver Code ;"
How can the above be solved in Java?

import java . util . * ; class GFG { static int N = 1000000 + 5 ; static int [ ] prefix = new int [ N ] ; static int [ ] sum = new int [ N ] ; static int isSpecial ( char c , char [ ] special ) { for ( char i : special ) if ( i == c ) return 1 ; return 0 ; } static double countRatio ( char [ ] s , char [ ] special ) { int n = s . length ; for ( int i = 0 ; i < n ; i ++ ) { prefix [ i ] = ( isSpecial ( s [ i ] , special ) ) ; if ( i > 0 ) prefix [ i ] += prefix [ i - 1 ] ; } for ( int i = 0 ; i < n ; i ++ ) { sum [ i ] = prefix [ i ] ; if ( i > 0 ) sum [ i ] += sum [ i - 1 ] ; } double ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int count = sum [ n - 1 ] - ( i > 1 ? sum [ i - 2 ] : 0 ) ; count -= ( i < n ? sum [ n - i - 1 ] : 0 ) ; ans += ( double ) count / ( double ) i ; } return ans ; } public static void main ( String [ ] args ) { String s = " abcd " ; char [ ] special = { ' b ' , ' c ' } ; double ans = countRatio ( s . toCharArray ( ) , special ) ; System . out . format ( " % .6f " , ans ) ; } }


"Calculate Volume of Dodecahedron | Java program to calculate Volume of dodecahedron ; utility Function ; driver function"
How can the above be solved in Java?

import java . io . * ; class GFG { static double vol_of_dodecahedron ( int side ) { return ( ( ( 15 + ( 7 * ( Math . sqrt ( 5 ) ) ) ) / 4 ) * ( Math . pow ( side , 3 ) ) ) ; } public static void main ( String [ ] args ) { int side = 4 ; System . out . print ( " Volume ▁ of ▁ dodecahedron ▁ = ▁ " ) ; System . out . println ( vol_of_dodecahedron ( side ) ) ; } }


"Calculate absolute difference between minimum and maximum sum of pairs in an array | Java program for the above approach ; Function to find the difference between the maximum and minimum sum of a pair ( arr [ i ] , arr [ j ] ) from the array such that i < j and arr [ i ] < arr [ j ] ; Stores the maximum from the suffix of the array ; Set the last element ; Traverse the remaining array ; Update the maximum from suffix for the remaining indices ; Stores the maximum sum of any pair ; Calculate the maximum sum ; Stores the maximum sum of any pair ; Stores the minimum of suffixes from the given array ; Set the last element ; Traverse the remaining array ; Update the maximum from suffix for the remaining indices ; Calculate the minimum sum ; Return the resultant difference ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int GetDiff ( int A [ ] , int N ) { int SuffMaxArr [ ] = new int [ N ] ; SuffMaxArr [ N - 1 ] = A [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; -- i ) { SuffMaxArr [ i ] = Math . max ( SuffMaxArr [ i + 1 ] , A [ i + 1 ] ) ; } int MaximumSum = Integer . MIN_VALUE ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] < SuffMaxArr [ i ] ) MaximumSum = Math . max ( MaximumSum , A [ i ] + SuffMaxArr [ i ] ) ; } int MinimumSum = Integer . MAX_VALUE ; int SuffMinArr [ ] = new int [ N ] ; SuffMinArr [ N - 1 ] = Integer . MAX_VALUE ; for ( int i = N - 2 ; i >= 0 ; -- i ) { SuffMinArr [ i ] = Math . min ( SuffMinArr [ i + 1 ] , A [ i + 1 ] ) ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] < SuffMinArr [ i ] ) { MinimumSum = Math . min ( MinimumSum , A [ i ] + SuffMinArr [ i ] ) ; } } return Math . abs ( MaximumSum - MinimumSum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 1 , 3 , 7 , 5 , 6 } ; int N = arr . length ; System . out . println ( GetDiff ( arr , N ) ) ; } }


"Calculate area and height of an isosceles triangle whose sides are radii of a circle | Java program for the above approach ; Function to convert given angle from degree to radian ; Function to calculate height and area of the triangle OAB ; Stores the angle OAB and OBA ; Stores the angle in radians ; Stores the height ; Print height of the triangle ; Stores the base of triangle OAB ; Stores the area of the triangle ; Print the area of triangle OAB ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static double Convert ( double degree ) { double pi = 3.14159265359 ; return ( degree * ( pi / 180 ) ) ; } static void areaAndHeightOfTraingle ( double radius , double a ) { if ( a >= 180 a == 0 ) { System . out . println ( " Not ▁ possible " ) ; return ; } double base_angle = ( 180 - a ) / 2 ; double radians = Convert ( base_angle ) ; double height = Math . sin ( radians ) * radius ; System . out . println ( " Height ▁ of ▁ triangle ▁ " + height ) ; double Base = Math . cos ( radians ) * radius ; double area = Base * height ; System . out . println ( " Area ▁ of ▁ triangle ▁ " + area ) ; } public static void main ( String [ ] args ) { double R = 5 , angle = 120 ; areaAndHeightOfTraingle ( R , angle ) ; } }


"Calculate cost of visiting all array elements in increasing order | java program for the above approach ; Pair class ; Function to calculate total cost of visiting array elements in increasing order ; Stores the pair of element and their positions ; Traverse the array arr [ ] ; Push the pair { arr [ i ] , i } in v ; Sort the vector in ascending order . ; Stores the total cost ; Stores the index of last element visited ; Traverse the vector v ; Increment ans ; Assign ; Return ans ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static class Pair { int first ; int second ; Pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int calculateDistance ( int arr [ ] , int N ) { Pair v [ ] = new Pair [ N ] ; for ( int i = 0 ; i < N ; i ++ ) v [ i ] = new Pair ( arr [ i ] , i ) ; Arrays . sort ( v , ( p1 , p2 ) -> { if ( p1 . first != p2 . first ) return p1 . first - p2 . first ; return p1 . second - p2 . second ; } ) ; int ans = 0 ; int last = 0 ; for ( Pair j : v ) { ans += Math . abs ( j . second - last ) ; last = j . second ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 3 , 2 , 5 , 1 } ; int N = arr . length ; System . out . println ( calculateDistance ( arr , N ) ) ; } }


"Calculate money placed in boxes after N days based on given conditions | Java program for above approach ; Function to find total money placed in the box ; Number of complete weeks ; Remaining days in the last week ; Driver Code ; Input ; Function call to find the total money placed"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void totalMoney ( int N ) { int CompWeeks = N / 7 ; int RemDays = N % 7 ; int X = 28 * CompWeeks + 7 * ( CompWeeks * ( CompWeeks - 1 ) / 2 ) ; int Y = RemDays * ( RemDays + 1 ) / 2 + CompWeeks * RemDays ; int cost = X + Y ; System . out . print ( cost ) ; } public static void main ( String [ ] args ) { int N = 15 ; totalMoney ( N ) ; } }


"Calculate money placed in boxes after N days based on given conditions | Java program for the above approach ; Function to find the total money placed in boxes after N days ; Stores the total money ; Iterate for N days ; Adding the Week number ; Adding previous amount + 1 ; Return the total amount ; Driver Code ; Input ; Function call to find total money placed"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int totalMoney ( int N ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { ans += i / 7 ; ans += ( i % 7 + 1 ) ; } return ans ; } public static void main ( String [ ] args ) { int N = 15 ; System . out . println ( totalMoney ( N ) ) ; } }


"Calculate number of nodes between two vertices in an acyclic Graph by DFS method | Java program for the above approach ; Function to return the count of nodes in the path from source to destination ; Mark the node visited ; If dest is reached ; Traverse all adjacent nodes ; If not already visited ; If there is path , then include the current node ; Return 0 if there is no path between src and dest through the current node ; Function to return the count of nodes between two given vertices of the acyclic Graph ; Initialize an adjacency list ; Populate the edges in the list ; Mark all the nodes as not visited ; Count nodes in the path from src to dest ; Return the nodes between src and dest ; Driver Code ; Given number of vertices and edges ; Given source and destination vertices ; Given edges"
How can the above be solved in Java?

import java . util . Vector ; class GFG { static int dfs ( int src , int dest , int [ ] vis , Vector < Integer > [ ] adj ) { vis [ src ] = 1 ; if ( src == dest ) { return 1 ; } for ( int u : adj [ src ] ) { if ( vis [ u ] == 0 ) { int temp = dfs ( u , dest , vis , adj ) ; if ( temp != 0 ) { return temp + 1 ; } } } return 0 ; } static int countNodes ( int V , int E , int src , int dest , int edges [ ] [ ] ) { Vector < Integer > [ ] adj = new Vector [ V + 1 ] ; for ( int i = 0 ; i < adj . length ; i ++ ) adj [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < E ; i ++ ) { adj [ edges [ i ] [ 0 ] ] . add ( edges [ i ] [ 1 ] ) ; adj [ edges [ i ] [ 1 ] ] . add ( edges [ i ] [ 0 ] ) ; } int vis [ ] = new int [ V + 1 ] ; int count = dfs ( src , dest , vis , adj ) ; return count - 2 ; } public static void main ( String [ ] args ) { int V = 8 , E = 7 ; int src = 5 , dest = 2 ; int edges [ ] [ ] = { { 1 , 4 } , { 4 , 5 } , { 4 , 2 } , { 2 , 6 } , { 6 , 3 } , { 2 , 7 } , { 3 , 8 } } ; System . out . print ( countNodes ( V , E , src , dest , edges ) ) ; } }


"Calculate score for the given binary string | Java implementation of the approach ; Function to return the score for the given binary string ; Traverse through string character ; Initialize current chunk 's size ; Get current character ; Calculate total chunk size of same characters ; Add / subtract pow ( chunkSize , 2 ) depending upon character ; Return the score ; Driver code"
How can the above be solved in Java?

class GFG { public static int calcScore ( String str ) { int score = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; ) { int chunkSize = 1 ; char currentChar = str . charAt ( i ++ ) ; while ( i < len && str . charAt ( i ) == currentChar ) { chunkSize ++ ; i ++ ; } if ( currentChar == '1' ) score += Math . pow ( chunkSize , 2 ) ; else score -= Math . pow ( chunkSize , 2 ) ; } return score ; } public static void main ( String [ ] args ) { String str = "11011" ; System . out . println ( calcScore ( str ) ) ; } }


"Calculate score of a string consisting of balanced parentheses | Java program to implement the above approach ; Function to calculate score of parentheses ; Stores index of character of String ; Stores total scores obtained from the String ; Iterate over characters of the String ; If s [ i ] is ' ( ' ; If top element of stack is ' ( ' ; Stores score of inner parentheses ; Calculate score of inner parentheses ; Update count ; Pop from stack ; Insert score of inner parentheses ; Update i ; Calculate score of the String ; Update ans ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static long scoreOfParentheses ( String S ) { Stack < String > s = new Stack < > ( ) ; int i = 0 ; long ans = 0 ; while ( i < S . length ( ) ) { if ( S . charAt ( i ) == ' ( ' ) s . add ( " ( " ) ; else { if ( s . peek ( ) == " ( " ) { s . pop ( ) ; s . add ( "1" ) ; } else { long count = 0 ; while ( s . peek ( ) != " ( " ) { count += Integer . parseInt ( s . peek ( ) ) ; s . pop ( ) ; } s . pop ( ) ; s . add ( String . valueOf ( 2 * count ) ) ; } } i ++ ; } while ( ! s . isEmpty ( ) ) { ans += Integer . parseInt ( s . peek ( ) ) ; s . pop ( ) ; } return ans ; } public static void main ( String [ ] args ) { String S1 = " ( ( ) ( ( ) ) ) " ; System . out . print ( scoreOfParentheses ( S1 ) + "
"); } }


"Calculate score of parentheses from a given string | Java program for the above approach ; Function to calculate the score of the parentheses using stack ; To keep track of the score ; Initially , push 0 to stack ; Traverse the string s ; If ' ( ' is encountered , then push 0 to stack ; Otherwise ; Balance the last ' ( ' , and store the score of inner parentheses ; If tmp is not zero , it means inner parentheses exists ; Otherwise , it means no inner parentheses exists ; Pass the score of this level to parent parentheses ; Print the score ; Driver code ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void scoreOfParentheses ( String s ) { Stack < Integer > stack = new Stack < > ( ) ; stack . push ( 0 ) ; for ( char c : s . toCharArray ( ) ) { if ( c == ' ( ' ) stack . push ( 0 ) ; else { int tmp = stack . pop ( ) ; int val = 0 ; if ( tmp > 0 ) val = tmp * 2 ; else val = 1 ; stack . push ( stack . pop ( ) + val ) ; } } System . out . println ( stack . peek ( ) ) ; } public static void main ( String [ ] args ) { String S = " ( ( ) ( ( ) ) ) " ; scoreOfParentheses ( S ) ; } }


"Calculate speed , distance and time | Java Program to calculate speed distance and time ; Function to calculate speed ; Function to calculate distance traveled ; Function to calculate time taken ; Driver code ; Calling function cal_speed ( ) ; Calling function cal_dis ( ) ; Calling function cal_time ( )"
How can the above be solved in Java?

class GFG { static double cal_speed ( double dist , double time ) { System . out . print ( " Distance ( km ) : " + dist) ; System . out . print ( " Time ( hr ) : " + time) ; return dist / time ; } static double cal_dis ( double speed , double time ) { System . out . print ( " Time ( hr ) : " + time) ; System . out . print ( " Speed ( km / hr ) : " + speed) ; return speed * time ; } static double cal_time ( double dist , double speed ) { System . out . print ( " Distance ( km ) : "+ dist) ; System . out . print ( " Speed ( km / hr ) : " + speed) ; return speed * dist ; } public static void main ( String [ ] args ) { System . out . println ( " The calculated Speed ( km / hr ) is : "+ cal_speed ( 45.9 , 2.0 ) ) ; System . out . println ( " The calculated Distance ( km ) : "+ cal_dis ( 62.9 , 2.5 ) ) ; System . out . println ( " The calculated Time ( hr ) : "+ cal_time ( 48.0 , 4.5 ) ) ; } }


"Calculate sum of all integers from 1 to N , excluding perfect power of 2 | Java implementation of the above approach ; Function to find the required summation ; Find the sum of first N integers using the formula ; Find the sum of numbers which are exact power of 2 by using the formula ; Print the final Sum ; Driver Code ; Function to find the sum"
How can the above be solved in Java?

import java . lang . Math ; class GFG { public static void findSum ( int N ) { int sum = ( N ) * ( N + 1 ) / 2 ; int r = ( int ) ( Math . log ( N ) / Math . log ( 2 ) ) + 1 ; int expSum = ( int ) ( Math . pow ( 2 , r ) ) - 1 ; System . out . println ( sum - expSum ) ; } public static void main ( String [ ] args ) { int N = 2 ; findSum ( N ) ; } }


"Calculate sum of all numbers present in a string | Java program to calculate sum of all numbers present in a string containing alphanumeric characters ; Function to calculate sum of all numbers present in a string containing alphanumeric characters ; A temporary string ; holds sum of all numbers present in the string ; read each character in input string ; if current character is a digit ; if current character is an alphabet ; increment sum by number found earlier ( if any ) ; reset temporary string to empty ; atoi ( temp . c_str ( ) ) takes care of trailing numbers ; Driver code ; input alphanumeric string ; Function call"
How can the above be solved in Java?

class GFG { static int findSum ( String str ) { String temp = "0" ; int sum = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char ch = str . charAt ( i ) ; if ( Character . isDigit ( ch ) ) temp += ch ; else { sum += Integer . parseInt ( temp ) ; temp = "0" ; } } return sum + Integer . parseInt ( temp ) ; } public static void main ( String [ ] args ) { String str = "12abc20yz68" ; System . out . println ( findSum ( str ) ) ; } }


"Calculate sum of scores after N days based on given conditions | Java Program to implement the above approach ; Function to c sum of calculate sum of scores after n days ; Store the required sum ; Store the score on previous monday and current day respectively ; Iterate over the range [ 1 , n ] ; If the current day is monday ; Increment score of prev_monday by 1 ; Update score of current day ; Add score of current day and increment score for next day ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findScoreSum ( int n ) { int total = 0 ; int prev_monday = 0 , curr_day = 0 ; for ( int day = 1 ; day <= n ; day ++ ) { if ( day % 7 == 1 ) { prev_monday ++ ; curr_day = prev_monday ; } total += curr_day ++ ; } System . out . println ( total ) ; } public static void main ( String [ ] args ) { int N = 8 ; findScoreSum ( N ) ; } }


"Calculate sum of scores after N days based on given conditions | Java program for the above approach ; Function to calculate sum of scores after n days ; Store the number of full weeks ; Stores the remaining days in the last week ; Store the sum of scores in the first F full weeks ; Store the sum of scores in the last week ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void findScoreSum ( int n ) { int F = n / 7 ; int D = n % 7 ; int fullWeekScore = ( 49 + 7 * F ) * F / 2 ; int lastNonFullWeekScore = ( 2 * F + D + 1 ) * D / 2 ; System . out . println ( fullWeekScore + lastNonFullWeekScore ) ; } public static void main ( String [ ] args ) { int N = 8 ; findScoreSum ( N ) ; } }


"Calculate sum of the array generated by given operations | Java program for the above approach ; Function to find the sum of the array formed by performing given set of operations while traversing the array ops [ ] ; If the size of array is 0 ; Stores the required sum ; Traverse the array ops [ ] ; If the character is C , remove the top element from the stack ; If the character is D , then push 2 * top element into stack ; If the character is + , add sum of top two elements from the stack ; Otherwise , push x and add it to ans ; Print the resultant sum ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void findTotalSum ( String ops [ ] ) { if ( ops . length == 0 ) { System . out . println ( 0 ) ; return ; } Stack < Integer > pts = new Stack < > ( ) ; int ans = 0 ; for ( int i = 0 ; i < ops . length ; i ++ ) { if ( ops [ i ] == " C " ) { ans -= pts . pop ( ) ; } else if ( ops [ i ] == " D " ) { pts . push ( pts . peek ( ) * 2 ) ; ans += pts . peek ( ) ; } else if ( ops [ i ] == " + " ) { int a = pts . pop ( ) ; int b = pts . peek ( ) ; pts . push ( a ) ; ans += ( a + b ) ; pts . push ( a + b ) ; } else { int n = Integer . parseInt ( ops [ i ] ) ; ans += n ; pts . push ( n ) ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String arr [ ] = { "5" , " - 2" , " C " , " D " , " + " } ; findTotalSum ( arr ) ; } }


"Calculate the CGPA and CGPA % of marks obtained by a Student in N subjects | Java program to calculate the CGPA and CGPA percentage of a student ; Variable to store the grades in every subject ; Variables to store CGPA and the sum of all the grades ; Computing the grades ; Computing the sum of grades ; Computing the CGPA ; Driver code"
How can the above be solved in Java?

import java . util . Scanner ; class CGPA { public static double CgpaCalc ( double [ ] marks , int n ) { double grade [ ] = new double [ n ] ; double cgpa , sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { grade [ i ] = ( marks [ i ] / 10 ) ; } for ( int i = 0 ; i < n ; i ++ ) { sum += grade [ i ] ; } cgpa = sum / n ; return cgpa ; } public static void main ( String args [ ] ) { int n = 5 ; double [ ] marks = { 90 , 80 , 70 , 80 , 90 } ; double cgpa = CgpaCalc ( marks , n ) ; System . out . println ( " CGPA ▁ = ▁ " + cgpa ) ; System . out . println ( " CGPA ▁ Percentage ▁ = ▁ " + String . format ( " % .2f " , cgpa * 9.5 ) ) ; } }


"Calculate the IST : Indian Standard Time | Java implementation of the approach ; Function to calculate Indian Standard Time ; Separate integer part ; Separate float part and return ceil value ; Driver code ; Number of hours ( 1 - 24 ) ; Rotations in degrees"
How can the above be solved in Java?

import java . math . * ; class GFG { public static void cal_IST ( int h , double r ) { double IST = ( h * r * 1.0 ) / 360 ; int int_IST = ( int ) IST ; int float_IST = ( int ) Math . ceil ( ( int ) ( ( IST - int_IST ) * 60 ) ) ; System . out . println ( int_IST + " : " + float_IST ) ; } public static void main ( String [ ] args ) { int h = 20 ; double r = 150 ; cal_IST ( h , r ) ; } }


"Calculate the Sum of GCD over all subarrays | Java program to find Sum of GCD over all subarrays . ; Utility function to calculate sum of gcd of all sub - arrays . ; Fixing the starting index of a subarray ; Fixing the ending index of a subarray ; Finding the GCD of this subarray ; Adding this GCD in our sum ; Driver Code"
How can the above be solved in Java?

 class GFG { static int findGCDSum ( int n , int a [ ] ) { int GCDSum = 0 ; int tempGCD = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { tempGCD = 0 ; for ( int k = i ; k <= j ; k ++ ) { tempGCD = __gcd ( tempGCD , a [ k ] ) ; } GCDSum += tempGCD ; } } return GCDSum ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int n = 5 ; int a [ ] = { 1 , 2 , 3 , 4 , 5 } ; int totalSum = findGCDSum ( n , a ) ; System . out . print ( totalSum + "
"); } }


"Calculate the Sum of GCD over all subarrays | Java program to find Sum of GCD over all subarrays ; int a [ 100001 ] ; ; Build Sparse Table ; Building the Sparse Table for GCD [ L , R ] Queries ; Utility Function to calculate GCD in range [ L , R ] ; Calculating where the answer is stored in our Sparse Table ; Utility Function to find next - farther position where gcd is same ; BinarySearch for Next Position for EndPointer ; Utility function to calculate sum of gcd ; Initializing all the values ; Finding the next position for endPointer ; Adding the suitable sum to our answer ; Changing prevEndPointer ; Recalculating tempGCD ; Driver code"
How can the above be solved in Java?

class GFG { static int [ ] [ ] SparseTable = new int [ 100001 ] [ 51 ] ; static void buildSparseTable ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { SparseTable [ i ] [ 0 ] = a [ i ] ; } for ( int j = 1 ; j <= 19 ; j ++ ) { for ( int i = 0 ; i <= n - ( 1 << j ) ; i ++ ) { SparseTable [ i ] [ j ] = __gcd ( SparseTable [ i ] [ j - 1 ] , SparseTable [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] ) ; } } } static int queryForGCD ( int L , int R ) { int returnValue ; int j = ( int ) ( Math . log ( R - L + 1 ) ) ; returnValue = __gcd ( SparseTable [ L ] [ j ] , SparseTable [ R - ( 1 << j ) + 1 ] [ j ] ) ; return returnValue ; } static int nextPosition ( int tempGCD , int startPointer , int prevEndPointer , int n ) { int high = n - 1 ; int low = prevEndPointer ; int mid = prevEndPointer ; int nextPos = prevEndPointer ; while ( high >= low ) { mid = ( ( high + low ) >> 1 ) ; if ( queryForGCD ( startPointer , mid ) == tempGCD ) { nextPos = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return nextPos + 1 ; } static int calculateSum ( int a [ ] , int n ) { buildSparseTable ( a , n ) ; int endPointer , startPointer , prevEndPointer , tempGCD ; int tempAns = 0 ; for ( int i = 0 ; i < n ; i ++ ) { endPointer = i ; startPointer = i ; prevEndPointer = i ; tempGCD = a [ i ] ; while ( endPointer < n ) { endPointer = nextPosition ( tempGCD , startPointer , prevEndPointer , n ) ; tempAns += ( ( endPointer - prevEndPointer ) * tempGCD ) ; prevEndPointer = endPointer ; if ( endPointer < n ) { tempGCD = __gcd ( tempGCD , a [ endPointer ] ) ; } } } return tempAns ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int n = 6 ; int a [ ] = { 2 , 2 , 2 , 3 , 5 , 5 } ; System . out . println ( calculateSum ( a , n ) ) ; } }


"Calculate the angle between hour hand and minute hand | Java program to find angle between hour and minute hands ; Function to calculate the angle ; validate the input ; Calculate the angles moved by hour and minute hands with reference to 12 : 00 ; Find the difference between two angles ; smaller angle of two possible angles ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int calcAngle ( double h , double m ) { if ( h < 0 m < 0 h > 12 m > 60 ) System . out . println ( " Wrong ▁ input " ) ; if ( h == 12 ) h = 0 ; if ( m == 60 ) { m = 0 ; h += 1 ; if ( h > 12 ) h = h - 12 ; } int hour_angle = ( int ) ( 0.5 * ( h * 60 + m ) ) ; int minute_angle = ( int ) ( 6 * m ) ; int angle = Math . abs ( hour_angle - minute_angle ) ; angle = Math . min ( 360 - angle , angle ) ; return angle ; } public static void main ( String [ ] args ) { System . out . println ( calcAngle ( 9 , 60 ) + " ▁ degree " ) ; System . out . println ( calcAngle ( 3 , 30 ) + " ▁ degree " ) ; } }


"Calculate the loss incurred in selling the given items at discounted price | Java implementation of the approach ; Function to return the x % of n ; Function to return the total loss ; To store the total loss ; Original price of the item ; The price at which the item will be sold ; The discounted price of the item ; Loss incurred ; Driver code ; Total items"
How can the above be solved in Java?

class GFG { static float percent ( int n , int x ) { float p = n * x ; p /= 100 ; return p ; } static float getLoss ( int price [ ] , int quantity [ ] , int X [ ] , int n ) { float loss = 0 ; for ( int i = 0 ; i < n ; i ++ ) { float originalPrice = price [ i ] ; float sellingPrice = originalPrice + percent ( ( int ) originalPrice , X [ i ] ) ; float afterDiscount = sellingPrice - percent ( ( int ) sellingPrice , X [ i ] ) ; loss += ( ( originalPrice - afterDiscount ) * quantity [ i ] ) ; } return loss ; } public static void main ( String args [ ] ) { int price [ ] = { 20 , 48 , 200 , 100 } ; int quantity [ ] = { 20 , 48 , 1 , 1 } ; int X [ ] = { 0 , 48 , 200 , 5 } ; int n = X . length ; System . out . print ( getLoss ( price , quantity , X , n ) ) ; } }


"Calculate the number of set bits for every number from 0 to N | Java implementation of the approach ; Function to find the count of set bits in all the integers from 0 to n ; Driver code"
How can the above be solved in Java?

class GFG { static void findSetBits ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) System . out . print ( Integer . bitCount ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 5 ; findSetBits ( n ) ; } }


"Calculate the number of set bits for every number from 0 to N | Java implementation of the approach ; Function to find the count of set bits in all the integers from 0 to n ; dp [ i ] will store the count of set bits in i ; Count of set bits in 0 is 0 ; For every number starting from 1 ; If current number is even ; Count of set bits in i is equal to the count of set bits in ( i / 2 ) ; If current element is odd ; Count of set bits in i is equal to the count of set bits in ( i / 2 ) + 1 ; Print the count of set bits in i ; Driver code"
How can the above be solved in Java?

class GFG { static void findSetBits ( int n ) { int [ ] dp = new int [ n + 1 ] ; System . out . print ( dp [ 0 ] + " ▁ " ) ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i % 2 == 0 ) { dp [ i ] = dp [ i / 2 ] ; } else { dp [ i ] = dp [ i / 2 ] + 1 ; } System . out . print ( dp [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 5 ; findSetBits ( n ) ; } }


"Calculate total wall area of houses painted | Java code of above approach ; Function to find the total area of walls painted in N row - houses ; Stores total area of N row - houses that needs to be painted ; Traverse the array of wall heights ; Update total area painted ; Update total ; Traverse all the houses and print the shared walls ; Update total ; Print total area needs to paint ; Driver code ; Given N , W & L ; Given heights of houses ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void areaToPaint ( int N , int W , int L , int Heights [ ] ) { int total = 0 ; for ( int i = 0 ; i < N ; i ++ ) { total += 2 * Heights [ i ] * W ; } total += L * ( Heights [ 0 ] + Heights [ N - 1 ] ) ; for ( int i = 1 ; i < N ; i ++ ) { total += L * Math . abs ( Heights [ i ] - Heights [ i - 1 ] ) ; } System . out . print ( total ) ; } public static void main ( String [ ] args ) { int N = 7 , W = 1 , L = 1 ; int Heights [ ] = { 4 , 3 , 1 , 2 , 3 , 4 , 2 } ; areaToPaint ( N , W , L , Heights ) ; } }


"Calculate volume and surface area of a cone | Java program to calculate Volume and Surface area of cone ; Function to calculate Volume of cone ; Function to calculate Surface area of cone ; Driver Code ; Printing value of volume and surface area"
How can the above be solved in Java?

class GFG { static float pi = 3.14159f ; public static float volume ( float r , float h ) { return ( float ) 1 / 3 * pi * h * r * r ; } public static float surface_area ( float r , float s ) { return pi * r * s + pi * r * r ; } public static void main ( String args [ ] ) { float radius = 5 ; float slant_height = 13 ; float height = 12 ; float vol , sur_area ; System . out . print ( " Volume ▁ Of ▁ Cone ▁ : ▁ " ) ; System . out . println ( volume ( radius , height ) ) ; System . out . print ( " Surface ▁ Area ▁ Of ▁ Cone ▁ : ▁ " ) ; System . out . println ( surface_area ( radius , slant_height ) ) ; } }


"Calculating Factorials using Stirling Approximation | Java program for calculating factorial of a number using Stirling Approximation ; function for calculating factorial ; evaluating factorial using stirling approximation ; Driver Code"
How can the above be solved in Java?

class GFG { public static int stirlingFactorial ( double n ) { if ( n == 1 ) return 1 ; double z ; z = Math . sqrt ( 2 * 3.14 * n ) * Math . pow ( ( n / e ) , n ) ; return ( int ) ( z ) ; } public static void main ( String [ ] args ) { System . out . println ( stirlingFactorial ( 1 ) ) ; System . out . println ( stirlingFactorial ( 2 ) ) ; System . out . println ( stirlingFactorial ( 3 ) ) ; System . out . println ( stirlingFactorial ( 4 ) ) ; System . out . println ( stirlingFactorial ( 5 ) ) ; System . out . println ( stirlingFactorial ( 6 ) ) ; System . out . println ( stirlingFactorial ( 7 ) ) ; } }


"Calculating n | Java Program to find n - th real root of x ; Initialize boundary values ; used for taking approximations of the answer ; Do binary search ; Driver code"
How can the above be solved in Java?

class GFG { static void findNthRoot ( double x , int n ) { double low , high ; if ( x >= 0 && x <= 1 ) { low = x ; high = 1 ; } else { low = 1 ; high = x ; } double epsilon = 0.00000001 ; double guess = ( low + high ) / 2 ; while ( Math . abs ( ( Math . pow ( guess , n ) ) - x ) >= epsilon ) { if ( Math . pow ( guess , n ) > x ) { high = guess ; } else { low = guess ; } guess = ( low + high ) / 2 ; } System . out . println ( guess ) ; } public static void main ( String [ ] args ) { double x = 5 ; int n = 2 ; findNthRoot ( x , n ) ; } }


"Camel and Banana Puzzle | DP | Java program of the above approach ; Stores the overlapping state ; Recursive function to find the maximum number of bananas that can be transferred to A distance using memoization ; Base Case where count of bananas is less that the given distance ; Base Case where count of bananas is less that camel 's capacity ; Base Case where distance = 0 ; If the current state is already calculated ; Stores the maximum count of bananas ; Stores the number of trips to transfer B bananas using a camel of capacity C ; Loop to iterate over all the breakpoints in range [ 1 , A ] ; Recursive call over the remaining path ; Update the maxCount ; Memoize the current value ; Return answer ; Function to find the maximum number of bananas that can be transferred ; Initialize dp array with - 1 ; Function Call ; Driver Code"
How can the above be solved in Java?

public class GFG { final static int dp [ ] [ ] = new int [ 1001 ] [ 3001 ] ; static int recBananaCnt ( int A , int B , int C ) { if ( B <= A ) { return 0 ; } if ( B <= C ) { return B - A ; } if ( A == 0 ) { return B ; } if ( dp [ A ] [ B ] != - 1 ) { return dp [ A ] [ B ] ; } int maxCount = Integer . MIN_VALUE ; int tripCount = B % C == 0 ? ( ( 2 * B ) / C ) - 1 : ( ( 2 * B ) / C ) + 1 ; for ( int i = 1 ; i <= A ; i ++ ) { int curCount = recBananaCnt ( A - i , B - tripCount * i , C ) ; if ( curCount > maxCount ) { maxCount = curCount ; dp [ A ] [ B ] = maxCount ; } } return maxCount ; } static int maxBananaCnt ( int A , int B , int C ) { for ( int i = 0 ; i < 1001 ; i ++ ) for ( int j = 0 ; j < 3001 ; j ++ ) dp [ i ] [ j ] = - 1 ; return recBananaCnt ( A , B , C ) ; } public static void main ( String [ ] args ) { int A = 1000 ; int B = 3000 ; int C = 1000 ; System . out . println ( maxBananaCnt ( A , B , C ) ) ; } }


"CamelCase Pattern Matching | Java to find CamelCase Pattern matching ; Function that prints the camel case pattern matching ; Map to store the hashing of each words with every uppercase letter found ; Traverse the words array that contains all the String ; Initialise str as empty ; length of String words [ i ] ; For every uppercase letter found map that uppercase to original words ; Traverse the map for pattern matching ; If pattern matches then print the corresponding mapped words ; If word not found print " No ▁ match ▁ found " ; Driver 's Code ; Pattern to be found ; Function call to find the words that match to the given pattern"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void CamelCase ( ArrayList < String > words , String pattern ) { Map < String , List < String > > map = new HashMap < String , List < String > > ( ) ; for ( int i = 0 ; i < words . size ( ) ; i ++ ) { String str = " " ; int l = words . get ( i ) . length ( ) ; for ( int j = 0 ; j < l ; j ++ ) { if ( words . get ( i ) . charAt ( j ) >= ' A ' && words . get ( i ) . charAt ( j ) <= ' Z ' ) { str += words . get ( i ) . charAt ( j ) ; map . put ( str , list ( map . get ( str ) , words . get ( i ) ) ) ; } } } boolean wordFound = false ; for ( Map . Entry < String , List < String > > it : map . entrySet ( ) ) { if ( it . getKey ( ) . equals ( pattern ) ) { wordFound = true ; for ( String s : it . getValue ( ) ) System . out . print ( s + "
"); } } if ( ! wordFound ) { System . out . print ( " No ▁ match ▁ found " ) ; } } private static List < String > list ( List < String > list , String str ) { List < String > temp = new ArrayList < String > ( ) ; if ( list != null ) temp . addAll ( list ) ; temp . add ( str ) ; return temp ; } public static void main ( String [ ] args ) { String arr [ ] = { " Hi " , " Hello " , " HelloWorld " , " HiTech " , " HiGeek " , " HiTechWorld " , " HiTechCity " , " HiTechLab " } ; ArrayList < String > words = new ArrayList < String > ( Arrays . asList ( arr ) ) ; String pattern = " HT " ; CamelCase ( words , pattern ) ; } }


"Canada Numbers | Java implementation for the above approach ; Function to calculate sum of all trivial divisors of given natural number ; Final result of summation of trivial divisors ; Find all divisors which divides ' num ' ; if ' i ' is divisor of ' num ' ; if both divisors are same then add it only once else add both ; Function to return sum of squares of digits of N ; Function to check if N is a Canada number ; Driver Code ; Given Number ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int divSum ( int num ) { int result = 0 ; for ( int i = 1 ; i <= Math . sqrt ( num ) ; i ++ ) { if ( num % i == 0 ) { if ( i == ( num / i ) ) result += i ; else result += ( i + num / i ) ; } } return ( result - 1 - num ) ; } static int getSum ( int n ) { int sum = 0 ; while ( n != 0 ) { int r = n % 10 ; sum = sum + r * r ; n = n / 10 ; } return sum ; } static boolean isCanada ( int n ) { return divSum ( n ) == getSum ( n ) ; } public static void main ( String [ ] args ) { int n = 125 ; if ( isCanada ( n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Capacity To Ship Packages Within D Days | Java program for the above approach ; Function to check if the weights can be delivered in D days or not ; Stores the count of days required to ship all the weights if the maximum capacity is mx ; Traverse all the weights ; If total weight is more than the maximum capacity ; If days are more than D , then return false ; Return true for the days < D ; Function to find the least weight capacity of a boat to ship all the weights within D days ; Stores the total weights to be shipped ; Find the sum of weights ; Stores the maximum weight in the array that has to be shipped ; Store the ending value for the search space ; Store the required result ; Perform binary search ; Store the middle value ; If mid can be shipped , then update the result and end value of the search space ; Search for minimum value in the right part ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isValid ( int [ ] weight , int n , int D , int mx ) { int st = 1 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += weight [ i ] ; if ( sum > mx ) { st ++ ; sum = weight [ i ] ; } if ( st > D ) return false ; } return true ; } static void shipWithinDays ( int [ ] weight , int D , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += weight [ i ] ; int s = weight [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { s = Math . max ( s , weight [ i ] ) ; } int e = sum ; int res = - 1 ; while ( s <= e ) { int mid = s + ( e - s ) / 2 ; if ( isValid ( weight , n , D , mid ) ) { res = mid ; e = mid - 1 ; } else s = mid + 1 ; } System . out . println ( res ) ; } public static void main ( String [ ] args ) { int [ ] weight = { 9 , 8 , 10 } ; int D = 3 ; int N = weight . length ; shipWithinDays ( weight , D , N ) ; } }


"Capitalize the first and last character of each word in a string | Java program to capitalise the first and last character of each word in a string . ; Create an equivalent char array of given string ; k stores index of first character and i is going to store index of last character . ; Check if the character is a small letter If yes , then Capitalise ; Driver code"
How can the above be solved in Java?

class GFG { static String FirstAndLast ( String str ) { char [ ] ch = str . toCharArray ( ) ; for ( int i = 0 ; i < ch . length ; i ++ ) { int k = i ; while ( i < ch . length && ch [ i ] != ' ▁ ' ) i ++ ; ch [ k ] = ( char ) ( ch [ k ] >= ' a ' && ch [ k ] <= ' z ' ? ( ( int ) ch [ k ] - 32 ) : ( int ) ch [ k ] ) ; ch [ i - 1 ] = ( char ) ( ch [ i - 1 ] >= ' a ' && ch [ i - 1 ] <= ' z ' ? ( ( int ) ch [ i - 1 ] - 32 ) : ( int ) ch [ i - 1 ] ) ; } return new String ( ch ) ; } public static void main ( String args [ ] ) { String str = " Geeks ▁ for ▁ Geeks " ; System . out . println ( str ) ; System . out . println ( FirstAndLast ( str ) ) ; } }


"Card Shuffle Problem | TCS Digital Advanced Coding Question | Java implementation of the approach ; Total cards ; Function to perform the current round ; Create the required empty piles ; Add cards to the piles one by one ; After all the piles have been reversed the new order will be first card of the first pile , second card of the first pile , ... , last pile of the last pile ( from top to bottom ) ; Function to perform all the rounds ; Create the initial list with all the cards ; Perform all the rounds ; Return the nth card ; Driver code ; nth card will be at ( n - 1 ) th index"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int CARDS = 100 ; static void currentRound ( List < Integer > list , int totalPiles ) { List < List < Integer > > piles = new ArrayList < > ( ) ; for ( int i = 0 ; i < totalPiles ; i ++ ) piles . add ( new ArrayList < Integer > ( ) ) ; int j = 0 ; for ( int i = 0 ; i < CARDS ; i ++ ) { piles . get ( j ) . add ( list . get ( i ) ) ; j = ( j + 1 ) % totalPiles ; } int pileNo = 0 , i = 0 ; j = 0 ; while ( i < CARDS ) { list . set ( i , piles . get ( pileNo ) . get ( j ) ) ; j ++ ; if ( j >= piles . get ( pileNo ) . size ( ) ) { pileNo ++ ; j = 0 ; } i ++ ; } } static int performRounds ( int piles [ ] , int rounds , int n ) { List < Integer > list = new ArrayList < > ( ) ; for ( int i = 1 ; i <= CARDS ; i ++ ) list . add ( i ) ; for ( int i = 0 ; i < rounds ; i ++ ) currentRound ( list , piles [ i ] ) ; return list . get ( n ) ; } public static void main ( String [ ] args ) { int piles [ ] = { 2 , 2 } ; int rounds = piles . length ; int n = 4 ; n -- ; System . out . print ( performRounds ( piles , rounds , n ) ) ; } }


"Cartesian tree from inorder traversal | Segment Tree | Java implementation of the approach ; Node of the BST ; Array to store segment tree ; Function to create segment - tree to answer range - max query ; Base case ; Maximum index in left range ; Maximum index in right range ; If value at l1 > r1 ; Else ; Returning the maximum in range ; Function to answer range max query ; Base cases ; Maximum in left range ; Maximum in right range ; l1 = - 1 means left range was out - side required range ; Returning the maximum among two ranges ; Function to print the inorder traversal of the binary tree ; Base case ; Traversing the left sub - tree ; Printing current node ; Traversing the right sub - tree ; Function to build cartesian tree ; Base case ; Maximum in the range ; Creating current node ; Creating left sub - tree ; Creating right sub - tree ; Returning current node ; Driver code ; In - order traversal of cartesian tree ; Size of the array ; Building the segment tree ; Building && printing cartesian tree"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxLen = 30 ; static class node { int data ; node left ; node right ; node ( int data ) { left = null ; right = null ; this . data = data ; } } ; static int segtree [ ] = new int [ maxLen * 4 ] ; static int buildTree ( int l , int r , int i , int [ ] arr ) { if ( l == r ) { segtree [ i ] = l ; return l ; } int l1 = buildTree ( l , ( l + r ) / 2 , 2 * i + 1 , arr ) ; int r1 = buildTree ( ( l + r ) / 2 + 1 , r , 2 * i + 2 , arr ) ; if ( arr [ l1 ] > arr [ r1 ] ) segtree [ i ] = l1 ; else segtree [ i ] = r1 ; return segtree [ i ] ; } static int rangeMax ( int l , int r , int rl , int rr , int i , int [ ] arr ) { if ( r < rl l > rr ) return - 1 ; if ( l >= rl && r <= rr ) return segtree [ i ] ; int l1 = rangeMax ( l , ( l + r ) / 2 , rl , rr , 2 * i + 1 , arr ) ; int r1 = rangeMax ( ( l + r ) / 2 + 1 , r , rl , rr , 2 * i + 2 , arr ) ; if ( l1 == - 1 ) return r1 ; if ( r1 == - 1 ) return l1 ; if ( arr [ l1 ] > arr [ r1 ] ) return l1 ; else return r1 ; } static void inorder ( node curr ) { if ( curr == null ) return ; inorder ( curr . left ) ; System . out . print ( curr . data + " ▁ " ) ; inorder ( curr . right ) ; } static node createCartesianTree ( int l , int r , int [ ] arr , int n ) { if ( r < l ) return null ; int m = rangeMax ( 0 , n - 1 , l , r , 0 , arr ) ; node curr = new node ( arr [ m ] ) ; curr . left = createCartesianTree ( l , m - 1 , arr , n ) ; curr . right = createCartesianTree ( m + 1 , r , arr , n ) ; return curr ; } public static void main ( String args [ ] ) { int arr [ ] = { 8 , 11 , 21 , 100 , 5 , 70 , 55 } ; int n = arr . length ; buildTree ( 0 , n - 1 , 0 , arr ) ; inorder ( createCartesianTree ( 0 , n - 1 , arr , n ) ) ; } }


"Cassiniâ €™ s Identity | Java implementation to demonstrate working of CassiniaTMs Identity ; Returns ( - 1 ) ^ n ; Driver method"
How can the above be solved in Java?

class Gfg { static int cassini ( int n ) { return ( n & 1 ) != 0 ? - 1 : 1 ; } public static void main ( String args [ ] ) { int n = 5 ; System . out . println ( cassini ( n ) ) ; } }


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

class Main { static int ceilSearch ( int arr [ ] , int low , int high , int x ) { int i ; if ( x <= arr [ low ] ) return low ; for ( i = low ; i < high ; i ++ ) { if ( arr [ i ] == x ) return i ; if ( arr [ i ] < x && arr [ i + 1 ] >= x ) return i + 1 ; } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 8 , 10 , 10 , 12 , 19 } ; int n = arr . length ; int x = 3 ; int index = ceilSearch ( arr , 0 , n - 1 , x ) ; if ( index == - 1 ) System . out . println ( " Ceiling ▁ of ▁ " + x + " ▁ doesn ' t ▁ exist ▁ in ▁ array " ) ; else System . out . println ( " ceiling ▁ of ▁ " + x + " ▁ is ▁ " + arr [ index ] ) ; } }


"Ceiling in a sorted array |  ; Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to the first element , then return the first element ; If x is greater than the last element , then return - 1 ; get the index of middle element of arr [ low . . high ] ; If x is same as middle element , then return mid ; If x is greater than arr [ mid ] , then either arr [ mid + 1 ] is ceiling of x or ceiling lies in arr [ mid + 1. . . high ] ; If x is smaller than arr [ mid ] , then either arr [ mid ] is ceiling of x or ceiling lies in arr [ low ... mid - 1 ] ; Driver program to check above functions"
How can the above be solved in Java?

class Main { static int ceilSearch ( int arr [ ] , int low , int high , int x ) { int mid ; if ( x <= arr [ low ] ) return low ; if ( x > arr [ high ] ) return - 1 ; mid = ( low + high ) / 2 ; if ( arr [ mid ] == x ) return mid ; else if ( arr [ mid ] < x ) { if ( mid + 1 <= high && x <= arr [ mid + 1 ] ) return mid + 1 ; else return ceilSearch ( arr , mid + 1 , high , x ) ; } else { if ( mid - 1 >= low && x > arr [ mid - 1 ] ) return mid ; else return ceilSearch ( arr , low , mid - 1 , x ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 8 , 10 , 10 , 12 , 19 } ; int n = arr . length ; int x = 8 ; int index = ceilSearch ( arr , 0 , n - 1 , x ) ; if ( index == - 1 ) System . out . println ( " Ceiling ▁ of ▁ " + x + " ▁ doesn ' t ▁ exist ▁ in ▁ array " ) ; else System . out . println ( " ceiling ▁ of ▁ " + x + " ▁ is ▁ " + arr [ index ] ) ; } }


"Ceiling of every element in same array | Java implementation of efficient algorithm to find floor of every element ; Prints greater elements on left side of every element ; Create a sorted copy of arr [ ] ; Traverse through arr [ ] and do binary search for every element . ; Find the first element that is greater than the given element ; Since arr [ i ] also exists in array , * ( it - 1 ) will be same as arr [ i ] . Let us check * ( it - 2 ) is also same as arr [ i ] . If true , then arr [ i ] exists twice in array , so ceiling is same same as arr [ i ] ; If next element is also same , then there are multiple occurrences , so print it ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void printPrevGreater ( int arr [ ] , int n ) { if ( n == 1 ) { System . out . println ( " - 1" ) ; return ; } int v [ ] = Arrays . copyOf ( arr , arr . length ) ; Arrays . sort ( v ) ; for ( int i = 0 ; i < n ; i ++ ) { int it = Arrays . binarySearch ( v , arr [ i ] ) ; it ++ ; if ( ( it - 1 ) != 0 && v [ it - 2 ] == arr [ i ] ) { System . out . print ( arr [ i ] + " ▁ " ) ; } else if ( it != v . length ) System . out . print ( v [ it ] + " ▁ " ) ; else System . out . print ( - 1 + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 5 , 11 , 10 , 20 , 12 } ; int n = arr . length ; printPrevGreater ( arr , n ) ; } }


"Center element of matrix equals sums of half diagonals | Java program to find maximum elements that can be made equal with k updates ; Function to Check center element is equal to the individual sum of all the half diagonals ; Find sums of half diagonals ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { static int MAX = 100 ; static boolean HalfDiagonalSums ( int mat [ ] [ ] , int n ) { int diag1_left = 0 , diag1_right = 0 ; int diag2_left = 0 , diag2_right = 0 ; for ( int i = 0 , j = n - 1 ; i < n ; i ++ , j -- ) { if ( i < n / 2 ) { diag1_left += mat [ i ] [ i ] ; diag2_left += mat [ j ] [ i ] ; } else if ( i > n / 2 ) { diag1_right += mat [ i ] [ i ] ; diag2_right += mat [ j ] [ i ] ; } } return ( diag1_left == diag2_right && diag2_right == diag2_left && diag1_right == diag2_left && diag2_right == mat [ n / 2 ] [ n / 2 ] ) ; } public static void main ( String args [ ] ) { int a [ ] [ ] = { { 2 , 9 , 1 , 4 , - 2 } , { 6 , 7 , 2 , 11 , 4 } , { 4 , 2 , 9 , 2 , 4 } , { 1 , 9 , 2 , 4 , 4 } , { 0 , 2 , 4 , 2 , 5 } } ; System . out . print ( HalfDiagonalSums ( a , 5 ) ? " Yes " : " No " ) ; } }


"Centered Dodecagonal Number | Java Program to find nth centered dodecagonal number ; Function to calculate centered dodecagonal number ; Formula to calculate nth centered dodecagonal number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static long centeredDodecagonal ( long n ) { return 6 * n * ( n - 1 ) + 1 ; } public static void main ( String [ ] args ) { long n = 2 ; System . out . println ( centeredDodecagonal ( n ) ) ; n = 9 ; System . out . println ( centeredDodecagonal ( n ) ) ; } }


"Centered Hexadecagonal Number | Java Program to find nth centered hexadecagonal number ; centered hexadecagonal function ; Formula to calculate nth centered hexadecagonal number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int center_hexadecagonal_num ( int n ) { return 8 * n * n - 8 * n + 1 ; } public static void main ( String args [ ] ) { int n = 2 ; System . out . print ( n + " th ▁ centered ▁ " + " hexadecagonal ▁ number : ▁ " ) ; System . out . println ( center_hexadecagonal_num ( n ) ) ; n = 12 ; System . out . print ( n + " th ▁ centered ▁ " + " hexadecagonal ▁ number : ▁ " ) ; System . out . println ( center_hexadecagonal_num ( n ) ) ; } }


"Centered Octadecagonal Number | Java Program to find the nth centered octadecagonal number ; centered octadecagon function ; Formula to calculate nth centered octadecagonal number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int center_octadecagon_num ( int n ) { return 9 * n * n - 9 * n + 1 ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . print ( n + " th ▁ centered ▁ " + " octadecagonal ▁ number ▁ : ▁ " ) ; System . out . println ( center_octadecagon_num ( n ) ) ; n = 13 ; System . out . print ( n + " th ▁ centered ▁ " + " octadecagonal ▁ number ▁ : ▁ " ) ; System . out . println ( center_octadecagon_num ( n ) ) ; } }


"Centered Octagonal Number | Java Program to find nth centered octagonal number ; Function to find centered octagonal number ; Formula to calculate nth centered octagonal number and return it into main function ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int centeredoctagonalNumber ( int n ) { return 4 * n * ( n - 1 ) + 1 ; } public static void main ( String args [ ] ) { int n = 6 ; System . out . print ( n + " th ▁ centered ▁ " + " octagonal ▁ number : ▁ " ) ; System . out . println ( centeredoctagonalNumber ( n ) ) ; n = 11 ; System . out . print ( n + " th ▁ centered ▁ " + " octagonal ▁ number : ▁ " ) ; System . out . println ( centeredoctagonalNumber ( n ) ) ; } }


"Centered Pentadecagonal Number | Java Program to find nth centered pentadecagonal number ; centered pentadecagonal function ; Formula to calculate nth centered pentadecagonal number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static long center_pentadecagonal_num ( long n ) { return ( 15 * n * n - 15 * n + 2 ) / 2 ; } public static void main ( String [ ] args ) { long n = 3 ; System . out . print ( n + " th ▁ number ▁ : ▁ " ) ; System . out . println ( center_pentadecagonal_num ( n ) ) ; n = 10 ; System . out . print ( n + " th ▁ number ▁ : ▁ " ) ; System . out . println ( center_pentadecagonal_num ( n ) ) ; } }


"Centered Square Number | Java program to find nth Centered square number ; Function to calculate Centered square number function ; Formula to calculate nth Centered square number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int centered_square_num ( int n ) { return n * n + ( ( n - 1 ) * ( n - 1 ) ) ; } public static void main ( String [ ] args ) { int n = 7 ; System . out . print ( n + " th ▁ Centered " + " ▁ square ▁ number : ▁ " + centered_square_num ( n ) ) ; } }


"Centered cube number | Java Program to find nth Centered cube number ; Function to find Centered cube number ; Formula to calculate nth Centered cube number & return it into main function . ; Driver code"
How can the above be solved in Java?

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


"Centered decagonal number | Java Program to find nth centered decagonal number ; Centered decagonal number function ; Formula to calculate nth centered decagonal number & return it into main function . ; Driver Code"
How can the above be solved in Java?

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


"Centered heptagonal number | Java program to find n - th Centered heptagonal number ; Function to find Centered heptagonal number ; Formula to calculate nth Centered heptagonal number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static long centered_heptagonal_num ( long n ) { return ( 7 * n * n - 7 * n + 2 ) / 2 ; } public static void main ( String [ ] args ) { long n = 5 ; System . out . println ( n + " th ▁ Centered ▁ " + " heptagonal ▁ number ▁ : ▁ " + centered_heptagonal_num ( n ) ) ; } }


"Centered hexagonal number | Java Program to find nth centered hexadecimal number ; Function to find centered hexadecimal number ; Formula to calculate nth centered hexadecimal number and return it into main function ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int centeredHexagonalNumber ( int n ) { return 3 * n * ( n - 1 ) + 1 ; } public static void main ( String args [ ] ) { int n = 10 ; System . out . print ( n + " th ▁ centered ▁ " + " hexagonal ▁ number : ▁ " ) ; System . out . println ( centeredHexagonalNumber ( n ) ) ; } }


"Centered nonadecagonal number | Java Program to find nth centered nonadecagonal number ; centered nonadecagonal function ; Formula to calculate nth centered nonadecagonal number ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int center_nonadecagon_num ( int n ) { return ( 19 * n * n - 19 * n + 2 ) / 2 ; } public static void main ( String [ ] args ) { int n = 2 ; System . out . print ( n + " th ▁ centered ▁ " + " nonadecagonal ▁ number ▁ : ▁ " ) ; System . out . println ( center_nonadecagon_num ( n ) ) ; n = 7 ; System . out . print ( n + " th ▁ centered ▁ " + " nonadecagonal ▁ number ▁ : ▁ " ) ; System . out . println ( center_nonadecagon_num ( n ) ) ; } }


"Centered pentagonal number | Program to find nth Centered pentagonal number ; centered pentagonal number function ; Formula to calculate nth Centered pentagonal number and return it into main function . ; Driver Code"
How can the above be solved in Java?

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


"Centered tetrahedral number | Java Program to find nth Centered tetrahedral number ; Function to find centered Centered tetrahedral number ; Formula to calculate nth Centered tetrahedral number and return it into main function . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int centeredTetrahedralNumber ( int n ) { return ( 2 * n + 1 ) * ( n * n + n + 3 ) / 3 ; } public static void main ( String [ ] args ) { int n = 6 ; System . out . println ( centeredTetrahedralNumber ( n ) ) ; } }


"Centered triangular number | Java Program to find the nth Centered Triangular number ; function for Centered Triangular number ; formula for find Centered Triangular number nth term ; Driver Code ; For 3 rd Centered Triangular number ; For 12 th Centered Triangular number"
How can the above be solved in Java?

import java . io . * ; class GFG { static int Centered_Triangular_num ( int n ) { return ( 3 * n * n + 3 * n + 2 ) / 2 ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( Centered_Triangular_num ( n ) ) ; n = 12 ; System . out . println ( Centered_Triangular_num ( n ) ) ; } }


"Centered tridecagonal number | Java Program to find nth centered tridecagonal number ; Function to find nth centered tridecagonal number ; Formula to calculate nth centered tridecagonal number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static long centeredTridecagonalNum ( long n ) { return ( 13 * n * ( n - 1 ) + 2 ) / 2 ; } public static void main ( String [ ] args ) { long n = 3 ; System . out . println ( centeredTridecagonalNum ( n ) ) ; n = 10 ; System . out . println ( centeredTridecagonalNum ( n ) ) ; } }


"Central angle of a N sided Regular Polygon | Java program for the above approach ; Function to calculate central angle of a polygon ; Calculate the angle ; Driver code"
How can the above be solved in Java?

class GFG { static double calculate_angle ( double n ) { double total_angle = 360 ; return total_angle / n ; } public static void main ( String [ ] args ) { double N = 5 ; System . out . println ( calculate_angle ( N ) ) ; } }


"Central binomial coefficient | Java implementation to find the Nth Central Binomial Coefficient ; Function to find the value of Nth Central Binomial Coefficient ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Driver Code"
How can the above be solved in Java?

class GFG { static int binomialCoeff ( int n , int k ) { int [ ] [ ] C = new int [ n + 1 ] [ k + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= Math . min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } public static void main ( String [ ] args ) { int n = 3 ; int k = n ; n = 2 * n ; System . out . println ( binomialCoeff ( n , k ) ) ; } }


"Centrosymmetric Matrix | Java Program to check whether given matrix is centrosymmetric or not . ; Finding the middle row of the matrix ; for each row upto middle row . ; If each element and its corresponding element is not equal then return false . ; Driven Program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int N = 3 ; static boolean checkCentrosymmetricted ( int n , int m [ ] [ ] ) { int mid_row ; if ( ( n & 1 ) > 0 ) mid_row = n / 2 + 1 ; else mid_row = n / 2 ; for ( int i = 0 ; i < mid_row ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( m [ i ] [ j ] != m [ n - i - 1 ] [ n - j - 1 ] ) return false ; } } return true ; } public static void main ( String [ ] args ) { int n = 3 ; int m [ ] [ ] = { { 1 , 3 , 5 } , { 6 , 8 , 6 } , { 5 , 3 , 1 } } ; if ( checkCentrosymmetricted ( n , m ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }