"Sum of digits of a given number to a given power | Java program to illustrate the given problem ; Function to calculate sum ; Driver Code"
How can the above be solved in Java?

public class base_power { static int calculate ( int n , int power ) { int sum = 0 ; int bp = ( int ) Math . pow ( n , power ) ; while ( bp != 0 ) { int d = bp % 10 ; sum += d ; bp /= 10 ; } return sum ; } public static void main ( String [ ] args ) { int n = 5 ; int power = 4 ; System . out . println ( calculate ( n , power ) ) ; } }


"Sum of digits written in different bases from 2 to n | Java program to find sum of digits of n in different bases from 2 to n - 1. ; function to calculate sum of digit for a given base ; Sum of digits ; Calculating the number ( n ) by taking mod with the base and adding remainder to the result and parallelly reducing the num value . ; returning the result ; function calling for multiple bases ; Driver Code"
How can the above be solved in Java?

class GFG { static int solve ( int n , int base ) { int result = 0 ; while ( n > 0 ) { int remainder = n % base ; result = result + remainder ; n = n / base ; } return result ; } static void printSumsOfDigits ( int n ) { for ( int base = 2 ; base < n ; ++ base ) System . out . print ( solve ( n , base ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 8 ; printSumsOfDigits ( n ) ; } }


"Sum of each element raised to ( prime | Java implementation of the approach ; Function to return the required sum ; Driver code"
How can the above be solved in Java?

public class GFG { public static int getSum ( int arr [ ] , int p ) { return arr . length ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 6 , 8 } ; int p = 7 ; System . out . print ( getSum ( arr , p ) ) ; } }


"Sum of element whose prime factors are present in array | Java program to find the sum of the elements of an array whose prime factors are present in the same array ; Stores smallest prime factor for every number ; Function to calculate SPF ( Smallest Prime Factor ) for every number till MAXN ; Marking smallest prime factor for every number to be itself . ; Separately marking spf for every even number as 2 ; If i is prime ; Marking SPF for all numbers divisible by i ; Marking spf [ j ] if it is not previously marked ; Function to return the sum of the elements of an array whose prime factors are present in the same array ; Function call to calculate smallest prime factors of all the numbers upto MAXN ; Create map for each element ; If smallest prime factor of num is present in array ; Each factor of arr [ i ] is present in the array ; Driver program ; Function call to print required answer"
How can the above be solved in Java?

import java . util . * ; public class GFG { final static int MAXN = 1000001 ; static int spf [ ] = new int [ MAXN ] ; static void sieve ( ) { spf [ 1 ] = 1 ; for ( int i = 2 ; i < MAXN ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < MAXN ; i += 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i < MAXN ; i ++ ) { if ( spf [ i ] == i ) { for ( int j = i * i ; j < MAXN ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } } } static int sumFactors ( int arr [ ] , int n ) { sieve ( ) ; Map map = new HashMap ( ) ; for ( int i = 0 ; i < MAXN ; ++ i ) map . put ( i , 0 ) ; for ( int i = 0 ; i < n ; ++ i ) map . put ( arr [ i ] , 1 ) ; int sum = 0 ; for ( int i = 0 ; i < n ; ++ i ) { int num = arr [ i ] ; while ( num != 1 && ( int ) ( map . get ( spf [ num ] ) ) == 1 ) { num /= spf [ num ] ; } if ( num == 1 ) sum += arr [ i ] ; } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 11 , 55 , 25 , 100 } ; int n = arr . length ; System . out . println ( sumFactors ( arr , n ) ) ; } }


"Sum of elements from an array having even parity | Java program to find the sum of the elements from an array which have even parity ; Function that returns true if x has even parity ; We basically count set bits https : www . geeksforgeeks . org / count - set - bits - in - an - integer / ; Function to return the sum of the elements from an array which have even parity ; If a [ i ] has even parity ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean checkEvenParity ( int x ) { int parity = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; parity ++ ; } if ( parity % 2 == 0 ) return true ; else return false ; } static long sumlist ( int a [ ] , int n ) { long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( checkEvenParity ( a [ i ] ) ) sum += a [ i ] ; } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 3 , 5 , 9 } ; int n = arr . length ; System . out . println ( sumlist ( arr , n ) ) ; } }


"Sum of elements in 1 st array such that number of elements less than or equal to them in 2 nd array is maximum | Java implementation of the approach ; Function to return the required sum ; Creating hash array initially filled with zero ; Calculate the frequency of elements of arr2 [ ] ; Running sum of hash array such that hash [ i ] will give count of elements less than or equal to i in arr2 [ ] ; To store the maximum value of the number of elements in arr2 [ ] which are smaller than or equal to some element of arr1 [ ] ; Calculate the sum of elements from arr1 [ ] corresponding to maximum frequency ; Return the required sum ; Driver code"
How can the above be solved in Java?

class GFG { static int MAX = 100000 ; static int findSumofEle ( int arr1 [ ] , int m , int arr2 [ ] , int n ) { int hash [ ] = new int [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) { hash [ arr2 [ i ] ] ++ ; } for ( int i = 1 ; i < MAX ; i ++ ) { hash [ i ] = hash [ i ] + hash [ i - 1 ] ; } int maximumFreq = 0 ; for ( int i = 0 ; i < m ; i ++ ) { maximumFreq = Math . max ( maximumFreq , hash [ arr1 [ i ] ] ) ; } int sumOfElements = 0 ; for ( int i = 0 ; i < m ; i ++ ) { sumOfElements += ( maximumFreq == hash [ arr1 [ i ] ] ) ? arr1 [ i ] : 0 ; } return sumOfElements ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 2 , 5 , 6 , 8 } ; int arr2 [ ] = { 4 , 10 } ; int m = arr1 . length ; int n = arr2 . length ; System . out . println ( findSumofEle ( arr1 , m , arr2 , n ) ) ; } }


"Sum of elements in an array whose difference with the mean of another array is less than k | Java implementation of the approach ; Function for finding sum of elements whose diff with mean is not more than k ; Find the mean of second array ; Find sum of elements from array1 whose difference with mean in not more than k ; Return result ; Driver code"
How can the above be solved in Java?

class GFG { static int findSumofEle ( int [ ] arr1 , int m , int [ ] arr2 , int n , int k ) { float arraySum = 0 ; for ( int i = 0 ; i < n ; i ++ ) arraySum += arr2 [ i ] ; float mean = arraySum / n ; int sumOfElements = 0 ; float difference = 0 ; for ( int i = 0 ; i < m ; i ++ ) { difference = arr1 [ i ] - mean ; if ( ( difference < 0 ) && ( k > ( - 1 ) * difference ) ) { sumOfElements += arr1 [ i ] ; } if ( ( difference >= 0 ) && ( k > difference ) ) { sumOfElements += arr1 [ i ] ; } } return sumOfElements ; } public static void main ( String [ ] args ) { int [ ] arr1 = { 1 , 2 , 3 , 4 , 7 , 9 } ; int [ ] arr2 = { 0 , 1 , 2 , 1 , 1 , 4 } ; int k = 2 ; int m = arr1 . length ; int n = arr2 . length ; System . out . println ( findSumofEle ( arr1 , m , arr2 , n , k ) ) ; } }


"Sum of elements in range L | Java program to find the sum between L - R range by creating the array Efficient Approach ; Function to calculate the sum if n is even ; both l and r are to the left of mid ; first and last element ; Total number of terms in the sequence is r - l + 1 ; use of formula derived ; both l and r are to the right of mid ; first and last element ; Use of formula derived ; left is to the left of mid and right is to the right of mid ; Take two sums i . e left and right differently and add ; first and last element ; total terms ; no of terms ; The first even number is 2 ; The last element is given by 2 * ( r - n / 2 ) ; formula applied ; Function to calculate the sum if n is odd ; take ceil value if n is odd ; both l and r are to the left of mid ; first and last element ; number of terms ; formula ; both l and r are to the right of mid ; first and last term , ; no of terms ; formula used ; If l is on left and r on right ; calculate separate sums ; first half ; calculate terms ; second half ; add both halves ; Function to find the sum between L and R ; If n is even ; If n is odd ; Driver Code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static int sumeven ( int n , int l , int r ) { int sum = 0 ; int mid = n / 2 ; if ( r <= mid ) { int first = ( 2 * l - 1 ) ; int last = ( 2 * r - 1 ) ; int no_of_terms = r - l + 1 ; sum = ( ( no_of_terms ) * ( ( first + last ) ) ) / 2 ; } else if ( l >= mid ) { int first = ( 2 * ( l - n / 2 ) ) ; int last = ( 2 * ( r - n / 2 ) ) ; int no_of_terms = r - l + 1 ; sum = ( ( no_of_terms ) * ( ( first + last ) ) ) / 2 ; } else { int sumleft = 0 , sumright = 0 ; int first_term1 = ( 2 * l - 1 ) ; int last_term1 = ( 2 * ( n / 2 ) - 1 ) ; int no_of_terms1 = n / 2 - l + 1 ; sumleft = ( ( no_of_terms1 ) * ( ( first_term1 + last_term1 ) ) ) / 2 ; int first_term2 = 2 ; int last_term2 = ( 2 * ( r - n / 2 ) ) ; int no_of_terms2 = r - mid ; sumright = ( ( no_of_terms2 ) * ( ( first_term2 + last_term2 ) ) ) / 2 ; sum = ( sumleft + sumright ) ; } return sum ; } static int sumodd ( int n , int l , int r ) { int mid = n / 2 + 1 ; int sum = 0 ; if ( r <= mid ) { int first = ( 2 * l - 1 ) ; int last = ( 2 * r - 1 ) ; int no_of_terms = r - l + 1 ; sum = ( ( no_of_terms ) * ( ( first + last ) ) ) / 2 ; } else if ( l > mid ) { int first = ( 2 * ( l - mid ) ) ; int last = ( 2 * ( r - mid ) ) ; int no_of_terms = r - l + 1 ; sum = ( ( no_of_terms ) * ( ( first + last ) ) ) / 2 ; } else { int sumleft = 0 , sumright = 0 ; int first_term1 = ( 2 * l - 1 ) ; int last_term1 = ( 2 * mid - 1 ) ; int no_of_terms1 = mid - l + 1 ; sumleft = ( ( no_of_terms1 ) * ( ( first_term1 + last_term1 ) ) ) / 2 ; int first_term2 = 2 ; int last_term2 = ( 2 * ( r - mid ) ) ; int no_of_terms2 = r - mid ; sumright = ( ( no_of_terms2 ) * ( ( first_term2 + last_term2 ) ) ) / 2 ; sum = ( sumleft + sumright ) ; } return sum ; } static int rangesum ( int n , int l , int r ) { int sum = 0 ; if ( n % 2 == 0 ) return sumeven ( n , l , r ) ; else return sumodd ( n , l , r ) ; } public static void main ( String [ ] args ) { int n = 12 ; int l = 1 , r = 11 ; System . out . println ( rangesum ( n , l , r ) ) ; } }


"Sum of elements in range L | Java program to find the sum between L - R range by creating the array Naive Approach ; Function to find the sum between L and R ; array created ; fill the first half of array ; fill the second half of array ; find the sum between range ; Driver Code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static int rangesum ( int n , int l , int r ) { int [ ] arr = new int [ n ] ; int c = 1 , i = 0 ; while ( c <= n ) { arr [ i ++ ] = c ; c += 2 ; } c = 2 ; while ( c <= n ) { arr [ i ++ ] = c ; c += 2 ; } int sum = 0 ; for ( i = l - 1 ; i < r ; i ++ ) { sum += arr [ i ] ; } return sum ; } public static void main ( String [ ] args ) { int n = 12 ; int l = 1 , r = 11 ; System . out . println ( rangesum ( n , l , r ) ) ; } }


"Sum of elements of a Geometric Progression ( GP ) in a given range | Java program to find the sum of elements of an GP in the given range ; Function to find sum in the given range ; Find the value of k ; Find the common difference ; Find the sum ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int findSum ( int [ ] arr , int n , int left , int right ) { int k = right - left + 1 ; int d = arr [ 1 ] / arr [ 0 ] ; int ans = arr [ left - 1 ] ; if ( d == 1 ) ans = ans * d * k ; else ans = ans * ( ( int ) Math . pow ( d , k ) - 1 / ( d - 1 ) ) ; return ans ; } public static void main ( String args [ ] ) { int [ ] arr = { 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 } ; int queries = 3 ; int [ ] [ ] q = { { 2 , 4 } , { 2 , 6 } , { 5 , 8 } } ; int n = arr . length ; for ( int i = 0 ; i < queries ; i ++ ) System . out . println ( findSum ( arr , n , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) ) ; } }


"Sum of elements of all partitions of number such that no element is less than K | Java implementation of above approach ; Function that returns total number of valid partitions of integer N ; Global declaration of 2D dp array which will be later used for memoization ; initializing 2D dp array with - 1 we will use this 2D array for memoization ; if this subproblem is already previously calculated , then directly return that answer ; if N < K , then no valid partition is possible ; if N is between K to 2 * K then there is only one partition and that is the number N itself ; Initialize answer with 1 as the number N itself is always a valid partition ; for loop to iterate over K to N and find number of possible valid partitions recursively . ; memoization is done by storing this calculated answer ; returning number of valid partitions ; Driver code ; Printing total number of valid partitions"
How can the above be solved in Java?

class GFG { static long countPartitions ( int n , int k ) { long [ ] [ ] dp = new long [ 201 ] [ 201 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) { for ( int j = 0 ; j < n + 1 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } if ( dp [ n ] [ k ] >= 0 ) return dp [ n ] [ k ] ; if ( n < k ) return 0 ; if ( n < 2 * k ) return 1 ; long answer = 1 ; for ( int i = k ; i < n ; i ++ ) answer = answer + countPartitions ( n - i , i ) ; dp [ n ] [ k ] = answer ; return answer ; } public static void main ( String [ ] args ) { int n = 10 , k = 3 ; System . out . println ( " Total ▁ Aggregate ▁ sum ▁ of ▁ " + " all ▁ Valid ▁ Partitions : ▁ " + countPartitions ( n , k ) * n ) ; } }


"Sum of elements of an AP in the given range | Java program to find the sum of elements of an AP in the given range ; Function to find sum in the given range ; Find the value of k ; Find the common difference ; Find the sum ; Driver code"
How can the above be solved in Java?

 class GFG { static int findSum ( int [ ] arr , int n , int left , int right ) { int k = right - left ; int d = arr [ 1 ] - arr [ 0 ] ; int ans = arr [ left - 1 ] * ( k + 1 ) ; ans = ans + ( d * ( k * ( k + 1 ) ) ) / 2 ; return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 } ; int queries = 3 ; int q [ ] [ ] = { { 2 , 4 } , { 2 , 6 } , { 5 , 6 } } ; int n = arr . length ; for ( int i = 0 ; i < queries ; i ++ ) System . out . print ( findSum ( arr , n , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) + "
"); } }


"Sum of every Kâ €™ th prime number in an array | Java implementation of the approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all the entries as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; 0 and 1 are not prime numbers ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; compute the answer ; count of primes ; sum of the primes ; traverse the array ; if the number is a prime ; increase the count ; if it is the K 'th prime ; Driver code ; create the sieve"
How can the above be solved in Java?

public class GFG { static int MAX = 1000000 ; static boolean prime [ ] = new boolean [ MAX + 1 ] ; static void SieveOfEratosthenes ( ) { for ( int i = 0 ; i < prime . length ; i ++ ) { prime [ i ] = true ; } prime [ 1 ] = false ; prime [ 0 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) { prime [ i ] = false ; } } } } static void SumOfKthPrimes ( int arr [ ] , int n , int k ) { int c = 0 ; long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { c ++ ; if ( c % k == 0 ) { sum += arr [ i ] ; c = 0 ; } } } System . out . println ( sum ) ; } public static void main ( String [ ] args ) { SieveOfEratosthenes ( ) ; int arr [ ] = { 2 , 3 , 5 , 7 , 11 } ; int n = arr . length ; int k = 2 ; SumOfKthPrimes ( arr , n , k ) ; } }


"Sum of f ( a [ i ] , a [ j ] ) over all pairs in an array of n integers | Java program to calculate the sum of f ( a [ i ] , aj ] ) ; Function to calculate the sum ; Map to keep a count of occurrences ; Traverse in the list from start to end number of times a [ i ] can be in a pair and to get the difference we subtract pre_sum ; If the ( a [ i ] - 1 ) is present then subtract that value as f ( a [ i ] , a [ i ] - 1 ) = 0 ; If the ( a [ i ] + 1 ) is present then add that value as f ( a [ i ] , a [ i ] - 1 ) = 0 here we add as a [ i ] - ( a [ i ] - 1 ) < 0 which would have been added as negative sum , so we add to remove this pair from the sum value ; keeping a counter for every element ; Driver code"
How can the above be solved in Java?

import java . util . * ; public class GfG { public static int sum ( int a [ ] , int n ) { Map < Integer , Integer > cnt = new HashMap < Integer , Integer > ( ) ; int ans = 0 , pre_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans += ( i * a [ i ] ) - pre_sum ; pre_sum += a [ i ] ; if ( cnt . containsKey ( a [ i ] - 1 ) ) ans -= cnt . get ( a [ i ] - 1 ) ; if ( cnt . containsKey ( a [ i ] + 1 ) ) ans += cnt . get ( a [ i ] + 1 ) ; if ( cnt . containsKey ( a [ i ] ) ) { cnt . put ( a [ i ] , cnt . get ( a [ i ] ) + 1 ) ; } else { cnt . put ( a [ i ] , 1 ) ; } } return ans ; } public static void main ( String args [ ] ) { int a [ ] = { 1 , 2 , 3 , 1 , 3 } ; int n = a . length ; System . out . println ( sum ( a , n ) ) ; } }


"Sum of fifth powers of the first n natural numbers | Java Program to find the sum of fifth power of first n natural numbers ; calculate the sum of fifth power of first n natural numbers ; Driven Program"
How can the above be solved in Java?

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


"Sum of first K numbers which are not divisible by N | Java program to calculate the sum of first K numbers not divisible by N ; Function to find the sum ; Find the last multiple of N ; Find the K - th non - multiple of N ; Calculate the sum of all elements from 1 to val ; Calculate the sum of all multiples of N between 1 to val ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findSum ( int n , int k ) { int val = ( k / ( n - 1 ) ) * n ; int rem = k % ( n - 1 ) ; if ( rem == 0 ) { val = val - 1 ; } else { val = val + rem ; } int sum = ( val * ( val + 1 ) ) / 2 ; int x = k / ( n - 1 ) ; int sum_of_multiples = ( x * ( x + 1 ) * n ) / 2 ; sum -= sum_of_multiples ; return sum ; } public static void main ( String [ ] args ) { int n = 7 , k = 13 ; System . out . println ( findSum ( n , k ) ) ; } }


"Sum of first N Star Numbers | Java program to find the sum of the first N star numbers ; Function to find the sum of the first N star number ; Variable to store the sum ; Driver code"
How can the above be solved in Java?

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


"Sum of first N natural numbers by taking powers of 2 as negative number | Java implementation of above approach ; to store power of 2 ; to store presum of the power of 2 's ; function to find power of 2 ; to store power of 2 ; to store pre sum ; Function to find the sum ; first store sum of first n natural numbers . ; find the first greater number than given number then minus double of this from answer ; Driver code ; function call ; function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int power [ ] = new int [ 31 ] ; static int pre [ ] = new int [ 31 ] ; static void PowerOfTwo ( ) { int x = 1 ; for ( int i = 0 ; i < 31 ; i ++ ) { power [ i ] = x ; x *= 2 ; } pre [ 0 ] = 1 ; for ( int i = 1 ; i < 31 ; i ++ ) pre [ i ] = pre [ i - 1 ] + power [ i ] ; } static int Sum ( int n ) { int ans = n * ( n + 1 ) / 2 ; for ( int i = 0 ; i < 31 ; i ++ ) { if ( power [ i ] > n ) { ans -= 2 * pre [ i - 1 ] ; break ; } } return ans ; } public static void main ( String [ ] args ) { PowerOfTwo ( ) ; int n = 4 ; System . out . println ( Sum ( n ) ) ; } }


"Sum of first N natural numbers which are divisible by 2 and 7 | Java program to find sum of numbers from 1 to N which are divisible by 2 or 7 ; Function to calculate the sum of numbers divisible by 2 or 7 ; Driver code"
How can the above be solved in Java?


"Sum of first N natural numbers which are divisible by X or Y | Java program to find sum of numbers from 1 to N which are divisible by X or Y ; Function to calculate the sum of numbers divisible by X or Y ; Driver code"
How can the above be solved in Java?

public class GFG { static int sum ( int N , int X , int Y ) { int S1 , S2 , S3 ; S1 = ( ( N / X ) ) * ( 2 * X + ( N / X - 1 ) * X ) / 2 ; S2 = ( ( N / Y ) ) * ( 2 * Y + ( N / Y - 1 ) * Y ) / 2 ; S3 = ( ( N / ( X * Y ) ) ) * ( 2 * ( X * Y ) + ( N / ( X * Y ) - 1 ) * ( X * Y ) ) / 2 ; return S1 + S2 - S3 ; } public static void main ( String [ ] args ) { int N = 14 ; int X = 3 , Y = 5 ; System . out . println ( sum ( N , X , Y ) ) ; } }


"Sum of first N natural numbers which are not powers of K | Java program to find the sum of first n natural numbers which are not positive powers of k ; Function to return the sum of first n natural numbers which are not positive powers of k ; sum of first n natural numbers ; subtract all positive powers of k which are less than n ; next power of k ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int find_sum ( int n , int k ) { int total_sum = ( n * ( n + 1 ) ) / 2 ; int power = k ; while ( power <= n ) { total_sum -= power ; power *= k ; } return total_sum ; } public static void main ( String [ ] args ) { int n = 11 , k = 2 ; System . out . println ( find_sum ( n , k ) ) ; } }


"Sum of first N natural numbers with all powers of 2 added twice | Java program to implement the above approach ; Function to raise N to the power P and return the value ; Function to calculate the log base 2 of an integer ; Calculate log2 ( N ) indirectly using log ( ) method ; Function to calculate and return the required sum ; Sum of first N natural numbers ; Sum of all powers of 2 up to N ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . lang . Math ; class GFG { static double power ( int N , int P ) { return Math . pow ( N , P ) ; } public static int log2 ( int N ) { int result = ( int ) ( Math . log ( N ) / Math . log ( 2 ) ) ; return result ; } static double specialSum ( int n ) { double sum = n * ( n + 1 ) / 2 ; int a = log2 ( n ) ; sum = sum + power ( 2 , a + 1 ) - 1 ; return sum ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( specialSum ( n ) ) ; } }


"Sum of first N natural numbers with alternate signs | Java program to implement the above approach ; Function to find the sum of first N natural numbers with alternate signs ; Stores sum of alternate sign of first N natural numbers ; If N is an even number ; Update alternateSum ; If N is an odd number ; Update alternateSum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int alternatingSumOfFirst_N ( int N ) { int alternateSum = 0 ; if ( N % 2 == 0 ) { alternateSum = ( - N ) / 2 ; } else { alternateSum = ( N + 1 ) / 2 ; } return alternateSum ; } public static void main ( String [ ] args ) { int N = 6 ; System . out . print ( alternatingSumOfFirst_N ( N ) ) ; } }


"Sum of first N natural numbers with alternate signs | Java program to implement the above approach ; Function to find the sum of first N natural numbers with alternate signs ; Stores sum of alternate sign of first N natural numbers ; If is an even number ; Update alternateSum ; If i is an odd number ; Update alternateSum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int alternatingSumOfFirst_N ( int N ) { int alternateSum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( i % 2 == 0 ) { alternateSum += - i ; } else { alternateSum += i ; } } return alternateSum ; } public static void main ( String [ ] args ) { int N = 6 ; System . out . print ( alternatingSumOfFirst_N ( N ) ) ; } }


"Sum of first n even numbers | Java implementation to find sum of first n even numbers ; function to find sum of first n even numbers ; required sum ; driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { static int evenSum ( int n ) { return ( n * ( n + 1 ) ) ; } public static void main ( String argc [ ] ) { int n = 20 ; System . out . println ( " Sum ▁ of ▁ first ▁ " + n + " ▁ Even ▁ numbers ▁ is : ▁ " + evenSum ( n ) ) ; } }


"Sum of first n even numbers | Java implementation to find sum of first n even numbers ; function to find sum of first n even numbers ; sum of first n even numbers ; next even number ; required sum ; driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { static int evenSum ( int n ) { int curr = 2 , sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { sum += curr ; curr += 2 ; } return sum ; } public static void main ( String argc [ ] ) { int n = 20 ; System . out . println ( " Sum ▁ of ▁ first ▁ " + n + " ▁ Even ▁ numbers ▁ is : ▁ " + evenSum ( n ) ) ; } }


"Sum of first n natural numbers | Java program to find sum series 1 , 3 , 6 , 10 , 15 , 21. . . and then find its sum ; Function to find the sum of series ; Driver code"
How can the above be solved in Java?

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


"Sum of first n natural numbers | java program to find sum series 1 , 3 , 6 , 10 , 15 , 21. . . and then find its sum ; Function to find the sum of series ; Driver code"
How can the above be solved in Java?

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


"Sum of first n odd numbers in O ( 1 ) Complexity | Java program to find sum of first n odd numbers ; Returns the sum of first n odd numbers ; driver function"
How can the above be solved in Java?

import java . util . * ; class Odd { public static int oddSum ( int n ) { return ( n * n ) ; } public static void main ( String [ ] args ) { int n = 20 ; System . out . println ( " ▁ Sum ▁ of ▁ first ▁ " + n + " ▁ Odd ▁ Numbers ▁ is : ▁ " + oddSum ( n ) ) ; } }


import java . util . * ; class Odd { public static int oddSum ( int n ) { int sum = 0 , curr = 1 ; for ( int i = 0 ; i < n ; i ++ ) { sum += curr ; curr += 2 ; } return sum ; } public static void main ( String [ ] args ) { int n = 20 ; System . out . println ( " ▁ Sum ▁ of ▁ first ▁ " + n + " ▁ Odd ▁ Numbers ▁ is : ▁ " + oddSum ( n ) ) ; } }


"Sum of first n terms of a given series 3 , 6 , 11 , ... . . | Java program to find sum of first n terms ; Function to calculate the sum ; starting number ; Common Ratio ; Common difference ; Driver code ; N th term to be find ; find the Sn"
How can the above be solved in Java?

import java . io . * ; class GFG { static int calculateSum ( int n ) { int a1 = 1 , a2 = 2 ; int r = 2 ; int d = 1 ; return ( n ) * ( 2 * a1 + ( n - 1 ) * d ) / 2 + a2 * ( int ) ( Math . pow ( r , n ) - 1 ) / ( r - 1 ) ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . print ( " Sum ▁ = ▁ " + calculateSum ( n ) ) ; } }


"Sum of fourth power of first n even natural numbers | JAVA Program to find the sum of fourth powers of first n even natural numbers ; calculate the sum of fourth power of first n even natural numbers ; Driven Program"
How can the above be solved in Java?

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


"Sum of fourth power of first n even natural numbers | Java Program to find the sum of fourth powers of first n even natural numbers ; calculate the sum of fourth power of first n even natural numbers ; made even number ; Driven Program"
How can the above be solved in Java?

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


"Sum of fourth powers of first n odd natural numbers | Java Program to find the sum of fourth powers of first n odd natural numbers ; calculate the sum of fourth power of first n odd natural numbers ; Driven Program"
How can the above be solved in Java?

class GFG { static long oddNumSum ( int n ) { return ( n * ( 2 * n + 1 ) * ( 24 * n * n * n - 12 * n * n - 14 * n + 7 ) ) / 15 ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( oddNumSum ( n ) ) ; } }


"Sum of fourth powers of the first n natural numbers | Java Program to find the sum of forth powers of first n natural numbers ; Return the sum of forth power of first n natural numbers ; Driven Program"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static long fourthPowerSum ( int n ) { return ( ( 6 * n * n * n * n * n ) + ( 15 * n * n * n * n ) + ( 10 * n * n * n ) - n ) / 30 ; } public static void main ( String [ ] args ) { int n = 6 ; System . out . println ( fourthPowerSum ( n ) ) ; } }


"Sum of fourth powers of the first n natural numbers | Java Program to find the sum of forth powers of first n natural numbers ; Return the sum of forth power of first n natural numbers ; Driver code"
How can the above be solved in Java?

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


"Sum of frequencies of characters of a string present in another string | Java program for the above approach ; Function to find sum of frequencies of characters of S1 present in S2 ; Insert all characters of string S1 in the set ; Traverse the string S2 ; Check if X is present in bset or not ; Increment count by 1 ; Finally , print the count ; Driver code ; Given strings"
How can the above be solved in Java?

import java . util . HashSet ; class GFG { static void countTotalFrequencies ( String S1 , String S2 ) { HashSet < Character > bset = new HashSet < Character > ( ) ; char [ ] S1arr = S1 . toCharArray ( ) ; char [ ] S2arr = S2 . toCharArray ( ) ; for ( char x : S1arr ) bset . add ( x ) ; int count = 0 ; for ( char x : S2arr ) { if ( bset . contains ( x ) ) count += 1 ; } System . out . print ( count ) ; } public static void main ( String [ ] args ) { String S1 = " geEksFOR " ; String S2 = " GeEksforgeEKS " ; countTotalFrequencies ( S1 , S2 ) ; } }


"Sum of given N fractions in reduced form | Java program for the above approach ; Function to find GCD of a & b using Euclid Lemma ; Base case ; Function to find the LCM of all elements in arr [ ] ; Initialize result ; Iterate arr [ ] to find LCM ; Return the final LCM ; Function to find the sum of N fraction in reduced form ; To store the sum of all final numerators ; Find the LCM of all denominator ; Find the sum of all N numerators & denominators ; Add each fraction one by one ; Find GCD of final numerator and denominator ; Convert into reduced form by dividing from GCD ; Print the final fraction ; Driver code ; Given N ; Given numerator ; Given denominator ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) { return a ; } return gcd ( b , a % b ) ; } static int findlcm ( int arr [ ] , int n ) { int ans = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { ans = ( ( ( arr [ i ] * ans ) ) / ( gcd ( arr [ i ] , ans ) ) ) ; } return ans ; } static void addReduce ( int n , int num [ ] , int den [ ] ) { int final_numerator = 0 ; int final_denominator = findlcm ( den , n ) ; for ( int i = 0 ; i < n ; i ++ ) { final_numerator = final_numerator + ( num [ i ] ) * ( final_denominator / den [ i ] ) ; } int GCD = gcd ( final_numerator , final_denominator ) ; final_numerator /= GCD ; final_denominator /= GCD ; System . out . println ( final_numerator + " / " + final_denominator ) ; } public static void main ( String [ ] args ) { int N = 3 ; int arr1 [ ] = { 1 , 2 , 5 } ; int arr2 [ ] = { 2 , 1 , 6 } ; addReduce ( N , arr1 , arr2 ) ; } }


"Sum of greatest odd divisor of numbers in given range | Function to return sum of first n odd numbers ; Recursive function to return sum of greatest odd divisor of numbers in range [ 1 , n ] ; Odd n ; Even n ; Function to return sum of greatest odd divisor of numbers in range [ a , b ] ; Driver code"
How can the above be solved in Java?

class gfg { static int square ( int n ) { return n * n ; } static int sum ( int n ) { if ( n == 0 ) return 0 ; if ( n % 2 == 1 ) { return square ( ( n + 1 ) / 2 ) + sum ( n / 2 ) ; } else { return square ( n / 2 ) + sum ( n / 2 ) ; } } static int oddDivSum ( int a , int b ) { return sum ( b ) - sum ( a - 1 ) ; } public static void main ( String [ ] args ) { int a = 3 , b = 9 ; System . out . println ( oddDivSum ( a , b ) ) ; } }


"Sum of heights of all individual nodes in a binary tree | Java program to find sum of heights of all nodes in a binary tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Compute the " maxHeight " of a particular Node ; compute the height of each subtree ; use the larger one ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; Function to sum of heights of individual Nodes Uses Inorder traversal ; Driver code"
How can the above be solved in Java?

class GfG { static class Node { int data ; Node left ; Node right ; } static int getHeight ( Node Node ) { if ( Node == null ) return 0 ; else { int lHeight = getHeight ( Node . left ) ; int rHeight = getHeight ( Node . right ) ; if ( lHeight > rHeight ) return ( lHeight + 1 ) ; else return ( rHeight + 1 ) ; } } static Node newNode ( int data ) { Node Node = new Node ( ) ; Node . data = data ; Node . left = null ; Node . right = null ; return ( Node ) ; } static int getTotalHeight ( Node root ) { if ( root == null ) return 0 ; return getTotalHeight ( root . left ) + getHeight ( root ) + getTotalHeight ( root . right ) ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; System . out . println ( " Sum ▁ of ▁ heights ▁ of ▁ all ▁ Nodes ▁ = ▁ " + getTotalHeight ( root ) ) ; } }


"Sum of heights of all individual nodes in a binary tree | Java program to find sum of heights of all nodes in a binary tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new Node with the given data and null left and right pointers . ; Function to sum of heights of individual Nodes Uses Inorder traversal ; Driver code"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node left ; Node right ; } ; static int sum ; static Node newNode ( int data ) { Node Node = new Node ( ) ; Node . data = data ; Node . left = null ; Node . right = null ; return ( Node ) ; } static int getTotalHeightUtil ( Node root ) { if ( root == null ) { return 0 ; } int lh = getTotalHeightUtil ( root . left ) ; int rh = getTotalHeightUtil ( root . right ) ; int h = Math . max ( lh , rh ) + 1 ; sum = sum + h ; return h ; } static int getTotalHeight ( Node root ) { sum = 0 ; getTotalHeightUtil ( root ) ; return sum ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; System . out . printf ( " Sum ▁ of ▁ heights ▁ of ▁ all ▁ Nodes ▁ = ▁ % d " , getTotalHeight ( root ) ) ; } }


"Sum of i * countDigits ( i ) ^ 2 for all i in range [ L , R ] | Java implementation of the approach ; Function to return the required sum ; If range is valid ; Sum of AP ; Driver code"
How can the above be solved in Java?

class GFG { static final int MOD = 1000000007 ; static int rangeSum ( int l , int r ) { int a = 1 , b = 9 , res = 0 ; for ( int i = 1 ; i <= 10 ; i ++ ) { int L = Math . max ( l , a ) ; int R = Math . min ( r , b ) ; if ( L <= R ) { int sum = ( L + R ) * ( R - L + 1 ) / 2 ; res += ( i * i ) * ( sum % MOD ) ; res %= MOD ; } a = a * 10 ; b = b * 10 + 9 ; } return res ; } public static void main ( String args [ ] ) { int l = 98 , r = 102 ; System . out . print ( rangeSum ( l , r ) ) ; } }


"Sum of i * countDigits ( i ) ^ countDigits ( i ) for all i in range [ L , R ] | Java program to find the required sum ; Function to return the required sum ; Iterating for all the number of digits from 1 to 10 ; If the range is valid ; Sum of AP ; Computing the next minimum and maximum numbers by for the ( i + 1 ) - th digit ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int MOD = 1000000007 ; static int rangeSum ( int l , int r ) { int a = 1 , b = 9 , res = 0 ; for ( int i = 1 ; i <= 10 ; i ++ ) { int L = Math . max ( l , a ) ; int R = Math . min ( r , b ) ; if ( L <= R ) { int sum = ( L + R ) * ( R - L + 1 ) / 2 ; res += Math . pow ( i , i ) * ( sum % MOD ) ; res %= MOD ; } a = a * 10 ; b = b * 10 + 9 ; } return res ; } public static void main ( String [ ] args ) { int l = 98 , r = 102 ; System . out . print ( rangeSum ( l , r ) ) ; } }


"Sum of indices of Characters removed to obtain an Empty String based on given conditions | Java program to implement the above approach ; Function to add index of the deleted character ; If index is beyond the range ; Insert the index of the deleted characeter ; Search over the subtrees to find the desired index ; Function to return count of deleted indices which are to the left of the current index ; Function to generate the sum of indices ; Stores the original index of the characters in sorted order of key ; Traverse the map ; Extract smallest index of smallest character ; Delete the character from the map if it has no remaining occurrence ; Stores the original index ; Count of elements removed to the left of current character ; Current index of the current character ; For 1 - based indexing ; Insert the deleted index in the segment tree ; Final answer ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void add_seg ( int seg [ ] , int start , int end , int current , int index ) { if ( index > end index < start ) return ; if ( start == end ) { seg [ current ] = 1 ; return ; } int mid = ( start + end ) / 2 ; add_seg ( seg , start , mid , 2 * current + 1 , index ) ; add_seg ( seg , mid + 1 , end , 2 * current + 2 , index ) ; seg [ current ] = seg [ 2 * current + 1 ] + seg [ 2 * current + 2 ] ; } static int deleted ( int seg [ ] , int l , int r , int start , int end , int current ) { if ( end < l start > r ) return 0 ; if ( start >= l && end <= r ) return seg [ current ] ; int mid = ( start + end ) / 2 ; return deleted ( seg , l , r , start , mid , 2 * current + 1 ) + deleted ( seg , l , r , mid + 1 , end , 2 * current + 2 ) ; } static void sumOfIndices ( String s ) { int N = s . length ( ) ; int x = ( int ) ( Math . ceil ( Math . log ( N ) / Math . log ( 2 ) ) ) ; int seg_size = 2 * ( int ) Math . pow ( 2 , x ) - 1 ; int segment [ ] = new int [ seg_size ] ; int count = 0 ; TreeMap < Integer , ArrayDeque < Integer > > fre = new TreeMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int key = ( int ) ( s . charAt ( i ) ) ; ArrayDeque < Integer > que = fre . getOrDefault ( key , new ArrayDeque < > ( ) ) ; que . addLast ( i ) ; fre . put ( key , que ) ; } while ( ! fre . isEmpty ( ) ) { int it = fre . firstKey ( ) ; if ( fre . get ( it ) . size ( ) == 0 ) fre . remove ( it ) ; else { ArrayDeque < Integer > que = fre . get ( it ) ; int original_index = que . getFirst ( ) ; int curr_index = deleted ( segment , 0 , original_index - 1 , 0 , N - 1 , 0 ) ; int new_index = original_index - curr_index ; count += new_index + 1 ; add_seg ( segment , 0 , N - 1 , 0 , original_index ) ; que . removeFirst ( ) ; fre . put ( it , que ) ; } } System . out . println ( count ) ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; sumOfIndices ( s ) ; } }


"Sum of integers upto N with given unit digit ( Set 2 ) | Java implementation of the approach ; Function to return the required sum ; Decrement N ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static long getSum ( long n , int d ) { if ( n < d ) return 0 ; while ( n % 10 != d ) n -- ; long k = n / 10 ; return ( k + 1 ) * d + ( k * 10 + 10 * k * k ) / 2 ; } public static void main ( String [ ] args ) { long n = 30 ; int d = 3 ; System . out . println ( getSum ( n , d ) ) ; } }


"Sum of integers upto N with given unit digit | Java implementation of the approach ; Function to return the required sum ; Driver code"
How can the above be solved in Java?

class Solution { static long getSum ( int n , int d ) { long sum = 0 ; while ( d <= n ) { sum += d ; d += 10 ; } return sum ; } public static void main ( String args [ ] ) { int n = 30 , d = 3 ; System . out . print ( getSum ( n , d ) ) ; } }


"Sum of integers upto N with given unit digit | Java implementation of the approach ; Function to return the required sum ; If the unit digit is d ; Driver code"
How can the above be solved in Java?

import java . util . * ; class solution { static long getSum ( int n , int d ) { long sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i % 10 == d ) sum += i ; } return sum ; } public static void main ( String args [ ] ) { int n = 30 , d = 3 ; System . out . println ( getSum ( n , d ) ) ; } }


"Sum of internal angles of a Polygon | Java implementation of the approach ; Function to return the sum of internal angles of an n - sided polygon ; Driver code"
How can the above be solved in Java?

class GFG { static int sumOfInternalAngles ( int n ) { if ( n < 3 ) return 0 ; return ( ( n - 2 ) * 180 ) ; } public static void main ( String args [ ] ) { int n = 5 ; System . out . print ( sumOfInternalAngles ( n ) ) ; } }


"Sum of k smallest elements in BST | Java program to find Sum Of All Elements smaller than or equal t Kth Smallest Element In BST ; Binary tree Node ; utility function new Node of BST ; A utility function to insert a new Node with given key in BST and also maintain lcount , Sum ; If the tree is empty , return a new Node ; Otherwise , recur down the tree ; increment lCount of current Node ; increment current Node sum by adding key into it ; return the ( unchanged ) Node pointer ; function return sum of all element smaller than and equal to Kth smallest element ; if we fount k smallest element then break the function ; store sum of all element smaller than current root ; ; decremented k and call right sub - tree ; call left sub - tree ; Wrapper over ksmallestElementSumRec ( ) ; Driver program to test above functions ; 20 / \ 8 22 / \ 4 12 / \ 10 14"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int data ; int lCount ; int Sum ; Node left ; Node right ; } ; static Node createNode ( int data ) { Node new_Node = new Node ( ) ; new_Node . left = null ; new_Node . right = null ; new_Node . data = data ; new_Node . lCount = 0 ; new_Node . Sum = 0 ; return new_Node ; } static Node insert ( Node root , int key ) { if ( root == null ) return createNode ( key ) ; if ( root . data > key ) { root . lCount ++ ; root . Sum += key ; root . left = insert ( root . left , key ) ; } else if ( root . data < key ) root . right = insert ( root . right , key ) ; return root ; } static int temp_sum ; static void ksmallestElementSumRec ( Node root , int k ) { if ( root == null ) return ; if ( ( root . lCount + 1 ) == k ) { temp_sum += root . data + root . Sum ; return ; } else if ( k > root . lCount ) { temp_sum += root . data + root . Sum ; k = k - ( root . lCount + 1 ) ; ksmallestElementSumRec ( root . right , k ) ; } else ksmallestElementSumRec ( root . left , k ) ; } static void ksmallestElementSum ( Node root , int k ) { temp_sum = 0 ; ksmallestElementSumRec ( root , k ) ; } public static void main ( String [ ] args ) { Node root = null ; root = insert ( root , 20 ) ; root = insert ( root , 8 ) ; root = insert ( root , 4 ) ; root = insert ( root , 12 ) ; root = insert ( root , 10 ) ; root = insert ( root , 14 ) ; root = insert ( root , 22 ) ; int k = 3 ; ksmallestElementSum ( root , k ) ; System . out . println ( temp_sum ) ; } }


"Sum of k smallest elements in BST | Java program to find Sum Of All Elements smaller than or equal to Kth Smallest Element In BST ; Binary tree Node ; utility function new Node of BST ; A utility function to insert a new Node with given key in BST and also maintain lcount , Sum ; If the tree is empty , return a new Node ; Otherwise , recur down the tree ; return the ( unchanged ) Node pointer ; function return sum of all element smaller than and equal to Kth smallest element ; Base cases ; Compute sum of elements in left subtree ; Add root 's data ; Add current Node ; If count is less than k , return right subtree Nodes ; Wrapper over ksmallestElementSumRec ( ) ; Driver program to test above functions ; 20 / \ 8 22 / \ 4 12 / \ 10 14"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static Node createNode ( int data ) { Node new_Node = new Node ( ) ; new_Node . left = null ; new_Node . right = null ; new_Node . data = data ; return new_Node ; } static Node insert ( Node root , int key ) { if ( root == null ) return createNode ( key ) ; if ( root . data > key ) root . left = insert ( root . left , key ) ; else if ( root . data < key ) root . right = insert ( root . right , key ) ; return root ; } static int count = 0 ; static int ksmallestElementSumRec ( Node root , int k ) { if ( root == null ) return 0 ; if ( count > k ) return 0 ; int res = ksmallestElementSumRec ( root . left , k ) ; if ( count >= k ) return res ; res += root . data ; count ++ ; if ( count >= k ) return res ; return res + ksmallestElementSumRec ( root . right , k ) ; } static int ksmallestElementSum ( Node root , int k ) { int res = ksmallestElementSumRec ( root , k ) ; return res ; } public static void main ( String [ ] args ) { Node root = null ; root = insert ( root , 20 ) ; root = insert ( root , 8 ) ; root = insert ( root , 4 ) ; root = insert ( root , 12 ) ; root = insert ( root , 10 ) ; root = insert ( root , 14 ) ; root = insert ( root , 22 ) ; int k = 3 ; int count = ksmallestElementSum ( root , k ) ; System . out . println ( count ) ; } }


"Sum of kth powers of first n natural numbers | Java program to find sum pf k - th powers of first n natural numbers . ; A global array to store factorials ; Function to calculate the factorials of all the numbers upto k ; Function to return the binomial coefficient ; nCr = ( n ! * ( n - r ) ! ) / r ! ; Function to return the sum of kth powers of n natural numbers ; When j is unity ; Calculating sum ( n ^ 1 ) of unity powers of n ; storing sum ( n ^ 1 ) for sum ( n ^ 2 ) ; If k = 1 then temp is the result ; For finding sum ( n ^ k ) removing 1 and n * kCk from ( n + 1 ) ^ k ; Removing all kC2 * sum ( n ^ ( k - 2 ) ) + ... + kCk - 1 * ( sum ( n ^ ( k - ( k - 1 ) ) ; Storing the result for next sum of next powers of k ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int MAX_K = 15 ; static int fac [ ] = new int [ MAX_K ] ; static void factorial ( int k ) { fac [ 0 ] = 1 ; for ( int i = 1 ; i <= k + 1 ; i ++ ) { fac [ i ] = ( i * fac [ i - 1 ] ) ; } } static int bin ( int a , int b ) { int ans = ( ( fac [ a ] ) / ( fac [ a - b ] * fac [ b ] ) ) ; return ans ; } static int sumofn ( int n , int k ) { int p = 0 ; int num1 , temp ; int arr [ ] = new int [ 1000 ] ; for ( int j = 1 ; j <= k ; j ++ ) { if ( j == 1 ) { num1 = ( n * ( n + 1 ) ) / 2 ; arr [ p ++ ] = num1 ; temp = num1 ; } else { temp = ( ( int ) Math . pow ( n + 1 , j + 1 ) - 1 - n ) ; for ( int s = 1 ; s < j ; s ++ ) { temp = temp - ( arr [ j - s - 1 ] * bin ( j + 1 , s + 1 ) ) ; } temp = temp / ( j + 1 ) ; arr [ p ++ ] = temp ; } } temp = arr [ p - 1 ] ; return temp ; } public static void main ( String [ ] args ) { int n = 5 , k = 2 ; factorial ( k ) ; System . out . println ( sumofn ( n , k ) ) ; } }


"Sum of last digit of all integers from 1 to N divisible by M | Java implementation of the approach ; Function to return the required sum ; Number of element between 1 to n divisible by m ; Array to store the last digit of elements in a cycle ; Storing and adding last digit of cycle ; Number of elements present in last cycle ; Sum of k / 10 cycle ; Adding value of digits of last cycle to the answer ; Driver Code ; input n and m"
How can the above be solved in Java?

import java . io . * ; class GFG { static long sumOfLastDig ( long n , long m ) { long sum = 0 , k ; k = n / m ; long [ ] arr = new long [ 10 ] ; for ( int i = 0 ; i < 10 ; i ++ ) { arr [ i ] = m * ( i + 1 ) % 10 ; sum += arr [ i ] ; } long rem = k % 10 ; long ans = ( k / 10 ) * sum ; for ( int i = 0 ; i < rem ; i ++ ) { ans += arr [ i ] ; } return ans ; } public static void main ( String [ ] args ) { long n = 100 , m = 3 ; System . out . println ( sumOfLastDig ( n , m ) ) ; } }


"Sum of leaf nodes at minimum level | Java implementation to find the sum of leaf nodes at minimum level ; structure of a node of binary tree ; function to get a new node ; allocate space ; put in the data ; function to find the sum of leaf nodes at minimum level ; if tree is empty ; if there is only one node ; queue used for level order traversal ; push root node in the queue ' q ' ; count number of nodes in the current level ; traverse the current level nodes ; get front element from ' q ' ; if it is a leaf node ; accumulate data to ' sum ' ; set flag ' f ' to 1 , to signify minimum level for leaf nodes has been encountered ; if top ' s ▁ left ▁ and ▁ right ▁ child ▁ ▁ ▁ exists , ▁ then ▁ push ▁ them ▁ to ▁ ' q ' ; required sum ; Driver Code ; binary tree creation"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static Node getNode ( int data ) { Node newNode = new Node ( ) ; newNode . data = data ; newNode . left = newNode . right = null ; return newNode ; } static int sumOfLeafNodesAtMinLevel ( Node root ) { if ( root == null ) return 0 ; if ( root . left == null && root . right == null ) return root . data ; Queue < Node > q = new LinkedList < > ( ) ; int sum = 0 ; boolean f = false ; q . add ( root ) ; while ( f == false ) { int nc = q . size ( ) ; while ( nc -- > 0 ) { Node top = q . peek ( ) ; q . remove ( ) ; if ( top . left == null && top . right == null ) { sum += top . data ; f = true ; } else { if ( top . left != null ) q . add ( top . left ) ; if ( top . right != null ) q . add ( top . right ) ; } } } return sum ; } public static void main ( String [ ] args ) { Node root = getNode ( 1 ) ; root . left = getNode ( 2 ) ; root . right = getNode ( 3 ) ; root . left . left = getNode ( 4 ) ; root . left . right = getNode ( 5 ) ; root . right . left = getNode ( 6 ) ; root . right . right = getNode ( 7 ) ; root . left . right . left = getNode ( 8 ) ; root . right . left . right = getNode ( 9 ) ; System . out . println ( " Sum ▁ = ▁ " + sumOfLeafNodesAtMinLevel ( root ) ) ; } }


"Sum of length of two smallest subsets possible from a given array with sum at least K | Java program for the above approach ; Function to calculate sum of lengths of two smallest subsets with sum >= K ; Sort the array in ascending order ; Stores suffix sum of the array ; Update the suffix sum array ; Stores all dp - states ; Initialize all dp - states with a maximum possible value ; Base Case ; Traverse the array arr [ ] ; Iterate over the range [ 0 , K ] ; If A [ i ] is equal to at least the required sum j for the current state ; If the next possible state doesn 't exist ; Otherwise , update the current state to the minimum of the next state and state including the current element A [ i ] ; Traverse the suffix sum array ; If suffix [ i ] - dp [ i ] [ K ] >= K ; Sum of lengths of the two smallest subsets is obtained ; Return - 1 , if there doesn 't  exist any subset of sum >= K ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int MAX = ( int ) ( 1e9 ) ; static int MinimumLength ( int A [ ] , int N , int K ) { Arrays . sort ( A ) ; int suffix [ ] = new int [ N + 1 ] ; for ( int i = N - 1 ; i >= 0 ; i -- ) suffix [ i ] = suffix [ i + 1 ] + A [ i ] ; int dp [ ] [ ] = new int [ N + 1 ] [ K + 1 ] ; for ( int i = 0 ; i <= N ; i ++ ) for ( int j = 0 ; j <= K ; j ++ ) dp [ i ] [ j ] = MAX ; dp [ N ] [ 0 ] = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { for ( int j = K ; j >= 0 ; j -- ) { if ( j <= A [ i ] ) { dp [ i ] [ j ] = A [ i ] ; continue ; } if ( dp [ i + 1 ] [ j - A [ i ] ] == MAX ) dp [ i ] [ j ] = MAX ; else dp [ i ] [ j ] = Math . min ( dp [ i + 1 ] [ j ] , dp [ i + 1 ] [ j - A [ i ] ] + A [ i ] ) ; } } for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( suffix [ i ] - dp [ i ] [ K ] >= K ) { return N - i ; } } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 4 , 5 , 6 , 8 } ; int K = 13 ; int N = arr . length ; System . out . println ( MinimumLength ( arr , N , K ) ) ; } }


"Sum of lengths of all 12 edges of any rectangular parallelepiped | Java program to illustrate the above problem ; function to find the sum of all the edges of parallelepiped ; to calculate the length of one edge ; sum of all the edges of one side ; net sum will be equal to the summation of edges of all the sides ; Driver code ; initialize the area of three faces which has a common vertex"
How can the above be solved in Java?

import java . io . * ; class GFG { static double findEdges ( double s1 , double s2 , double s3 ) { double a = Math . sqrt ( s1 * s2 / s3 ) ; double b = Math . sqrt ( s3 * s1 / s2 ) ; double c = Math . sqrt ( s3 * s2 / s1 ) ; double sum = a + b + c ; return 4 * sum ; } public static void main ( String [ ] args ) { double s1 , s2 , s3 ; s1 = 65 ; s2 = 156 ; s3 = 60 ; System . out . print ( findEdges ( s1 , s2 , s3 ) ) ; } }


"Sum of lengths of all paths possible in a given tree | Java implementation of the approach ; Number of vertices ; Adjacency list representation of the tree ; Array that stores the subtree size ; Array to mark all the vertices which are visited ; Utility function to create an edge between two vertices ; Add a to b 's list ; Add b to a 's list ; Function to calculate the subtree size ; Mark visited ; For every adjacent node ; If not already visited ; Recursive call for the child ; Function to calculate the contribution of each edge ; Mark current node as visited ; For every adjacent node ; If it is not already visisted ; Function to return the required sum ; First pass of the dfs ; Second pass ; Driver code"
How can the above be solved in Java?

import java . util . * ; @ SuppressWarnings ( " unchecked " ) class GFG { static int sz = 100005 ; static int n ; static ArrayList [ ] tree = new ArrayList [ sz ] ; static int [ ] subtree_size = new int [ sz ] ; static int [ ] vis = new int [ sz ] ; static void AddEdge ( int a , int b ) { tree [ a ] . add ( b ) ; tree [ b ] . add ( a ) ; } static int dfs ( int node ) { vis [ node ] = 1 ; subtree_size [ node ] = 1 ; for ( int child : ( ArrayList < Integer > ) tree [ node ] ) { if ( vis [ child ] == 0 ) { subtree_size [ node ] += dfs ( child ) ; } } return subtree_size [ node ] ; } static int contribution ( int node , int ans ) { vis [ node ] = 1 ; for ( int child : ( ArrayList < Integer > ) tree [ node ] ) { if ( vis [ child ] == 0 ) { ans += ( subtree_size [ child ] * ( n - subtree_size [ child ] ) ) ; ans = contribution ( child , ans ) ; } } return ans ; } static int getSum ( ) { Arrays . fill ( vis , 0 ) ; dfs ( 0 ) ; int ans = 0 ; Arrays . fill ( vis , 0 ) ; ans = contribution ( 0 , ans ) ; return ans ; } public static void main ( String [ ] args ) { n = 5 ; for ( int i = 0 ; i < sz ; i ++ ) { tree [ i ] = new ArrayList ( ) ; } AddEdge ( 0 , 1 ) ; AddEdge ( 0 , 2 ) ; AddEdge ( 1 , 3 ) ; AddEdge ( 1 , 4 ) ; System . out . println ( getSum ( ) ) ; } }


"Sum of matrix element where each elements is integer division of row and column | java program to find sum of matrix element where each element is integer division of row and column . ; Return sum of matrix element where each element is division of its corresponding row and column . ; For each column . ; count the number of elements of each column . Initialize to i - 1 because number of zeroes are i - 1. ; For multiply ; Driven Program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findSum ( int n ) { int ans = 0 , temp = 0 , num ; for ( int i = 1 ; i <= n && temp < n ; i ++ ) { temp = i - 1 ; num = 1 ; while ( temp < n ) { if ( temp + i <= n ) ans += ( i * num ) ; else ans += ( ( n - temp ) * num ) ; temp += i ; num ++ ; } } return ans ; } public static void main ( String [ ] args ) { int N = 2 ; System . out . println ( findSum ( N ) ) ; } }


"Sum of matrix in which each element is absolute difference of its row and column numbers | Java program to find sum of matrix in which each element is absolute difference of its corresponding row and column number row . ; Retuen the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; Driver Code"
How can the above be solved in Java?

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


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


"Sum of matrix in which each element is absolute difference of its row and column numbers | Java program to find sum of matrix in which each element is absolute difference of its corresponding row and column number row . ; Retuen the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; Generate matrix ; Compute sum ; Driver Code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static int findSum ( int n ) { int [ ] [ ] arr = new int [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) arr [ i ] [ j ] = Math . abs ( i - j ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) sum += arr [ i ] [ j ] ; return sum ; } static public void main ( String [ ] args ) { int n = 3 ; System . out . println ( findSum ( n ) ) ; } }


"Sum of maximum of all subarrays by adding even frequent maximum twice | Java program for the above approach ; Function to calculate sum of maximum of all subarrays ; Stores the sum of maximums ; Traverse the array ; Store the frequency of the maximum element in subarray ; Finding maximum ; Increment frequency by 1 ; If new maximum is obtained ; If frequency of maximum is even , then add 2 * maxNumber . Otherwise , add maxNumber ; Print the sum obtained ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void findSum ( int a [ ] ) { int ans = 0 ; for ( int low = 0 ; low < a . length ; low ++ ) { for ( int high = low ; high < a . length ; high ++ ) { int count = 0 ; int maxNumber = 0 ; for ( int i = low ; i <= high ; i ++ ) { if ( a [ i ] == maxNumber ) count ++ ; else if ( a [ i ] > maxNumber ) { maxNumber = a [ i ] ; count = 1 ; } } ans += maxNumber * ( ( count % 2 == 0 ) ? 2 : 1 ) ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 1 , 4 , 4 , 2 } ; findSum ( arr ) ; } }


"Sum of maximum of all subarrays | Divide and Conquer | Java implementation of the above approach ; Array to store segment tree . In first we will store the maximum of a range In second , we will store index of that range ; Size of array declared global to maintain simplicity in code ; Function to build segment tree ; Base case ; Finding the maximum among left and right child ; Returning the maximum to parent ; Function to perform range - max query in segment tree ; Base cases ; Finding the maximum among left and right child ; Function to find maximum sum subarray ; base case ; range - max query to determine largest in the range . ; divide the array in two parts ; Driver Code ; Input array ; Size of array ; Builind the segment - tree"
How can the above be solved in Java?

class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static final int seg_max = 51 ; static pair [ ] seg_tree = new pair [ seg_max ] ; static int n ; static pair buildMaxTree ( int l , int r , int i , int arr [ ] ) { if ( l == r ) { seg_tree [ i ] = new pair ( arr [ l ] , l ) ; return seg_tree [ i ] ; } seg_tree [ i ] = max ( buildMaxTree ( l , ( l + r ) / 2 , 2 * i + 1 , arr ) , buildMaxTree ( ( l + r ) / 2 + 1 , r , 2 * i + 2 , arr ) ) ; return seg_tree [ i ] ; } static pair rangeMax ( int l , int r , int arr [ ] , int i , int sl , int sr ) { if ( sr < l sl > r ) return new pair ( Integer . MIN_VALUE , - 1 ) ; if ( sl >= l && sr <= r ) return seg_tree [ i ] ; return max ( rangeMax ( l , r , arr , 2 * i + 1 , sl , ( sl + sr ) / 2 ) , rangeMax ( l , r , arr , 2 * i + 2 , ( sl + sr ) / 2 + 1 , sr ) ) ; } static pair max ( pair f , pair s ) { if ( f . first > s . first ) return f ; else return s ; } static int maxSumSubarray ( int arr [ ] , int l , int r ) { if ( l > r ) return 0 ; pair a = rangeMax ( l , r , arr , 0 , 0 , n - 1 ) ; return a . first * ( r - a . second + 1 ) * ( a . second - l + 1 ) + maxSumSubarray ( arr , l , a . second - 1 ) + maxSumSubarray ( arr , a . second + 1 , r ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 1 , 7 } ; n = arr . length ; buildMaxTree ( 0 , n - 1 , 0 , arr ) ; System . out . print ( maxSumSubarray ( arr , 0 , n - 1 ) ) ; } }


"Sum of middle row and column in Matrix | java program to find sum of middle row and column in matrix ; loop for sum of row ; loop for sum of column ; Driver function"
How can the above be solved in Java?

import java . io . * ; class GFG { static int MAX = 100 ; static void middlesum ( int mat [ ] [ ] , int n ) { int row_sum = 0 , col_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) row_sum += mat [ n / 2 ] [ i ] ; System . out . println ( " Sum ▁ of ▁ middle ▁ row ▁ = ▁ " + row_sum ) ; for ( int i = 0 ; i < n ; i ++ ) col_sum += mat [ i ] [ n / 2 ] ; System . out . println ( " Sum ▁ of ▁ middle ▁ column ▁ = ▁ " + col_sum ) ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 2 , 5 , 7 } , { 3 , 7 , 2 } , { 5 , 6 , 9 } } ; middlesum ( mat , 3 ) ; } }


"Sum of minimum absolute difference of each array element | java implementation to find the sum of minimum absolute difference of each array element ; function to find the sum of minimum absolute difference ; sort the given array ; initialize sum ; min absolute difference for the 1 st array element ; min absolute difference for the last array element ; find min absolute difference for rest of the array elements and add them to sum ; required sum ; Driver code"
How can the above be solved in Java?

import java . * ; import java . util . Arrays ; public class GFG { static int sumOfMinAbsDifferences ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int sum = 0 ; sum += Math . abs ( arr [ 0 ] - arr [ 1 ] ) ; sum += Math . abs ( arr [ n - 1 ] - arr [ n - 2 ] ) ; for ( int i = 1 ; i < n - 1 ; i ++ ) sum += Math . min ( Math . abs ( arr [ i ] - arr [ i - 1 ] ) , Math . abs ( arr [ i ] - arr [ i + 1 ] ) ) ; return sum ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 10 , 1 , 4 , 8 , 7 } ; int n = arr . length ; System . out . println ( " Sum ▁ = ▁ " + sumOfMinAbsDifferences ( arr , n ) ) ; } }


"Sum of minimum and maximum elements of all subarrays of size k . | Java program to find sum of all minimum and maximum elements Of Sub - array Size k . ; Returns sum of min and max element of all subarrays of size k ; Initialize result ; The queue will store indexes of useful elements in every window In deque ' G ' we maintain decreasing order of values from front to rear In deque ' S ' we maintain increasing order of values from front to rear ; Process first window of size K ; Remove all previous greater elements that are useless . ; Remove from rear ; Remove all previous smaller that are elements are useless . ; Remove from rear ; Add current element at rear of both deque ; Process rest of the Array elements ; Element at the front of the deque ' G ' & ' S ' is the largest and smallest element of previous window respectively ; Remove all elements which are out of this window ; remove all previous greater element that are useless ; Remove from rear ; remove all previous smaller that are elements are useless ; Remove from rear ; Add current element at rear of both deque ; Sum of minimum and maximum element of last window ; Driver program to test above functions"
How can the above be solved in Java?

import java . util . Deque ; import java . util . LinkedList ; public class Geeks { public static int SumOfKsubArray ( int arr [ ] , int k ) { int sum = 0 ; Deque < Integer > S = new LinkedList < > ( ) , G = new LinkedList < > ( ) ; int i = 0 ; for ( i = 0 ; i < k ; i ++ ) { while ( ! S . isEmpty ( ) && arr [ S . peekLast ( ) ] >= arr [ i ] ) S . removeLast ( ) ; while ( ! G . isEmpty ( ) && arr [ G . peekLast ( ) ] <= arr [ i ] ) G . removeLast ( ) ; G . addLast ( i ) ; S . addLast ( i ) ; } for ( ; i < arr . length ; i ++ ) { sum += arr [ S . peekFirst ( ) ] + arr [ G . peekFirst ( ) ] ; while ( ! S . isEmpty ( ) && S . peekFirst ( ) <= i - k ) S . removeFirst ( ) ; while ( ! G . isEmpty ( ) && G . peekFirst ( ) <= i - k ) G . removeFirst ( ) ; while ( ! S . isEmpty ( ) && arr [ S . peekLast ( ) ] >= arr [ i ] ) S . removeLast ( ) ; while ( ! G . isEmpty ( ) && arr [ G . peekLast ( ) ] <= arr [ i ] ) G . removeLast ( ) ; G . addLast ( i ) ; S . addLast ( i ) ; } sum += arr [ S . peekFirst ( ) ] + arr [ G . peekFirst ( ) ] ; return sum ; } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 5 , - 1 , 7 , - 3 , - 1 , - 2 } ; int k = 3 ; System . out . println ( SumOfKsubArray ( arr , k ) ) ; } }


"Sum of minimum and the maximum difference between two given Strings | Java program to find the sum of the minimum and the maximum difference between two given Strings ; Function to find the sum of the minimum and the maximum difference between two given Strings ; Variables to store the minimum difference and the maximum difference ; Iterate through the length of the String as both the given Strings are of the same length ; For the maximum difference , we can replace " + " in both the Strings with different char ; For the minimum difference , we can replace " + " in both the Strings with the same char ; Driver code"
How can the above be solved in Java?

 class GFG { static void solve ( char [ ] a , char [ ] b ) { int l = a . length ; int min = 0 , max = 0 ; for ( int i = 0 ; i < l ; i ++ ) { if ( a [ i ] == ' + ' b [ i ] == ' + ' a [ i ] != b [ i ] ) max ++ ; if ( a [ i ] != ' + ' && b [ i ] != ' + ' && a [ i ] != b [ i ] ) min ++ ; } System . out . print ( min + max + "
"); } public static void main ( String [ ] args ) { String s1 = " a + c " , s2 = " + + b " ; solve ( s1 . toCharArray ( ) , s2 . toCharArray ( ) ) ; } }


"Sum of minimum difference between consecutive elements of an array | Java program for finding the minimum sum of difference between consecutive elements ; function to find minimum sum of difference of consecutive element ; ul to store upper limit ll to store lower limit ; storethe lower range in ll and upper range in ul ; initialize the answer with 0 ; iterate for all ranges ; case 1 , in this case the difference will be 0 ; change upper limit and lower limit ; case 2 ; store the difference ; case 3 ; store the difference ; Driver code ; array of range"
How can the above be solved in Java?

import java . io . * ; class GFG { static int solve ( int [ ] [ ] v , int n ) { int ans , ul , ll ; int first = 0 ; int second = 1 ; ll = v [ 0 ] [ first ] ; ul = v [ 0 ] [ second ] ; ans = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( ( v [ i ] [ first ] <= ul && v [ i ] [ first ] >= ll ) || ( v [ i ] [ second ] >= ll && v [ i ] [ second ] <= ul ) ) { if ( v [ i ] [ first ] > ll ) { ll = v [ i ] [ first ] ; } if ( v [ i ] [ second ] < ul ) { ul = v [ i ] [ second ] ; } } else if ( v [ i ] [ first ] > ul ) { ans += Math . abs ( ul - v [ i ] [ first ] ) ; ul = v [ i ] [ first ] ; ll = v [ i ] [ first ] ; } else if ( v [ i ] [ second ] < ll ) { ans += Math . abs ( ll - v [ i ] [ second ] ) ; ul = v [ i ] [ second ] ; ll = v [ i ] [ second ] ; } } return ans ; } public static void main ( String [ ] args ) { int [ ] [ ] v = { { 1 , 3 } , { 2 , 5 } , { 6 , 8 } , { 1 , 2 } , { 2 , 3 } } ; int n = 5 ; System . out . println ( solve ( v , n ) ) ; } }


"Sum of minimum element of all sub | Java implementation of the above approach ; Function to find the sum of minimum of all subsequence ; Driver code"
How can the above be solved in Java?

class GfG { static int findMinSum ( int arr [ ] , int n ) { int occ = n - 1 , sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] * ( int ) Math . pow ( 2 , occ ) ; occ -- ; } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 5 } ; int n = arr . length ; System . out . println ( findMinSum ( arr , n ) ) ; } }


"Sum of minimum element of all subarrays of a sorted array | Java implementation of the above approach ; Function to find the sum of minimum of all subarrays ; Driver code"
How can the above be solved in Java?

class GfG { static int findMinSum ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] * ( n - i ) ; return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 5 , 7 , 8 } ; int n = arr . length ; System . out . println ( findMinSum ( arr , n ) ) ; } }


"Sum of minimum elements of all subarrays | Java implementation of above approach ;  ; Function to return required minimum sum ; getting number of element strictly larger than A [ i ] on Left . ; get elements from stack until element greater than A [ i ] found ; getting number of element larger than A [ i ] on Right . ; get elements from stack until element greater or equal to A [ i ] found ; calculating required resultult ; Driver Code ; function call to get required result"
How can the above be solved in Java?

import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int sumSubarrayMins ( int A [ ] , int n ) { int [ ] left = new int [ n ] ; int [ ] right = new int [ n ] ; Stack < pair > s1 = new Stack < pair > ( ) ; Stack < pair > s2 = new Stack < pair > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { int cnt = 1 ; while ( ! s1 . isEmpty ( ) && ( s1 . peek ( ) . first ) > A [ i ] ) { cnt += s1 . peek ( ) . second ; s1 . pop ( ) ; } s1 . push ( new pair ( A [ i ] , cnt ) ) ; left [ i ] = cnt ; } for ( int i = n - 1 ; i >= 0 ; -- i ) { int cnt = 1 ; while ( ! s2 . isEmpty ( ) && ( s2 . peek ( ) . first ) >= A [ i ] ) { cnt += s2 . peek ( ) . second ; s2 . pop ( ) ; } s2 . push ( new pair ( A [ i ] , cnt ) ) ; right [ i ] = cnt ; } int result = 0 ; for ( int i = 0 ; i < n ; ++ i ) result = ( result + A [ i ] * left [ i ] * right [ i ] ) ; return result ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 1 , 2 , 4 } ; int n = A . length ; System . out . println ( sumSubarrayMins ( A , n ) ) ; } }


"Sum of minimum value of x and y satisfying the equation ax + by = c | Java program for the above approach ; x and y store solution of equation ax + by = g ; Euclidean Algorithm ; store_gcd returns the gcd of a and b ; Function to find any possible solution ; Condition if solution does not exists ; Adjusting the sign of x0 and y0 ; Function to shift solution ; Shifting to obtain another solution ; Function to find minimum value of x and y ; g is the gcd of a and b ; Store sign of a and b ; If x is less than 0 , then shift solution ; If y is less than 0 , then shift solution ; Find intersection such that both x and y are positive ; miny is value of y corresponding to minx ; Returns minimum value of x + y ; Driver Code ; Given a , b , and c ; Function call"
How can the above be solved in Java?

import java . lang . * ; class GFG { public static int x = 0 , y = 0 , x1 = 0 , y1 = 0 ; public static int x0 = 0 , y0 = 0 , g = 0 ; public static int gcd ( int a , int b ) { if ( b == 0 ) { x = 1 ; y = 0 ; return a ; } int store_gcd = gcd ( b , a % b ) ; x = y1 ; y = x1 - y1 * ( a / b ) ; return store_gcd ; } public static int possible_solution ( int a , int b , int c ) { g = gcd ( Math . abs ( a ) , Math . abs ( b ) ) ; if ( c % g != 0 ) { return 0 ; } x0 *= c / g ; y0 *= c / g ; if ( a < 0 ) x0 *= - 1 ; if ( b < 0 ) y0 *= - 1 ; return 1 ; } public static void shift_solution ( int a , int b , int shift_var ) { x += shift_var * b ; y -= shift_var * a ; } public static int find_min_sum ( int a , int b , int c ) { int x = 0 , y = 0 , g = 0 ; if ( possible_solution ( a , b , c ) == 0 ) return - 1 ; if ( g != 0 ) { a /= g ; b /= g ; } int sign_a = a > 0 ? + 1 : - 1 ; int sign_b = b > 0 ? + 1 : - 1 ; shift_solution ( a , b , - x / b ) ; if ( x < 0 ) shift_solution ( a , b , sign_b ) ; int minx1 = x ; shift_solution ( a , b , y / a ) ; if ( y < 0 ) shift_solution ( a , b , - sign_a ) ; int minx2 = x ; if ( minx2 > x ) { int temp = minx2 ; minx2 = x ; x = temp ; } int minx = Math . max ( minx1 , minx2 ) ; if ( minx > x ) return - 1 ; int miny = ( c - a * x ) / b ; return ( miny + minx ) ; } public static void main ( String [ ] args ) { int a = 2 , b = 2 , c = 0 ; System . out . println ( find_min_sum ( a , b , c ) ) ; } }


"Sum of multiples of A and B less than N | Java program to find the sum of all multiples of A and B below N ; Function to find sum of AP series ; Number of terms ; Function to find the sum of all multiples of A and B below N ; Since , we need the sum of multiples less than N ; common factors of A and B ; Driver code"
How can the above be solved in Java?

class GFG { static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } static int sumAP ( int n , int d ) { n /= d ; return ( n ) * ( 1 + n ) * d / 2 ; } static int sumMultiples ( int A , int B , int n ) { n -- ; int common = ( A * B ) / __gcd ( A , B ) ; return sumAP ( n , A ) + sumAP ( n , B ) - sumAP ( n , common ) ; } public static void main ( String [ ] args ) { int n = 100 , A = 5 , B = 10 ; System . out . println ( " Sum ▁ = ▁ " + sumMultiples ( A , B , n ) ) ; } }


"Sum of multiples of Array elements within a given range [ L , R ] | Java program for the above approach ; Function to find the sum of all multiples of N up to K ; Calculate the sum ; Return the sum ; Function to find the total sum ; If L is divisible by a [ i ] ; Otherwise ; Return the final sum ; Driver Code ; Given array arr [ ] ; Given range ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int calcSum ( int k , int n ) { int value = ( k * n * ( n + 1 ) ) / 2 ; return value ; } static int findSum ( int [ ] a , int n , int L , int R ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( L % a [ i ] == 0 && L != 0 ) { sum += calcSum ( a [ i ] , R / a [ i ] ) - calcSum ( a [ i ] , ( L - 1 ) / a [ i ] ) ; } else { sum += calcSum ( a [ i ] , R / a [ i ] ) - calcSum ( a [ i ] , L / a [ i ] ) ; } } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 7 , 3 , 8 } ; int N = arr . length ; int L = 7 ; int R = 20 ; System . out . println ( findSum ( arr , N , L , R ) ) ; } }


"Sum of multiplication of triplet of divisors of a number | Java implementation of the approach ; Global array declaration ; Function to find the sum of multiplication of every triplet in the divisors of a number ; sum1 [ x ] represents the sum of all the divisors of x ; Adding i to sum1 [ j ] because i is a divisor of j ; sum2 [ x ] represents the sum of all the divisors of x ; Here i is divisor of j and sum1 [ j ] - i represents sum of all divisors of j which do not include i so we add i * ( sum1 [ j ] - i ) to sum2 [ j ] ; In the above implementation we have considered every pair two times so we have to divide every sum2 array element by 2 ; Here i is the divisor of j and we are trying to add the sum of multiplication of all triplets of divisors of j such that one of the divisors is i ; In the above implementation we have considered every triplet three times so we have to divide every sum3 array element by 3 ; Print the results ; Driver code ; Precomputing"
How can the above be solved in Java?

class GFGq { static int max_Element = ( int ) ( 1e6 + 5 ) ; static int sum1 [ ] = new int [ max_Element ] , sum2 [ ] = new int [ max_Element ] , sum3 [ ] = new int [ max_Element ] ; static void precomputation ( int arr [ ] , int n ) { for ( int i = 1 ; i < max_Element ; i ++ ) for ( int j = i ; j < max_Element ; j += i ) sum1 [ j ] += i ; for ( int i = 1 ; i < max_Element ; i ++ ) for ( int j = i ; j < max_Element ; j += i ) sum2 [ j ] += ( sum1 [ j ] - i ) * i ; for ( int i = 1 ; i < max_Element ; i ++ ) sum2 [ i ] /= 2 ; for ( int i = 1 ; i < max_Element ; i ++ ) for ( int j = i ; j < max_Element ; j += i ) sum3 [ j ] += i * ( sum2 [ j ] - i * ( sum1 [ j ] - i ) ) ; for ( int i = 1 ; i < max_Element ; i ++ ) sum3 [ i ] /= 3 ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( sum3 [ arr [ i ] ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 9 , 5 , 6 } ; int n = arr . length ; precomputation ( arr , n ) ; } }


"Sum of n digit numbers divisible by a given number | Efficient Java program to find the sum divisible numbers . ; find the Sum of having n digit and divisible by the number ; compute the first and last term ; first number which is divisible by given number ; last number which is divisible by given number ; total divisible number ; return the total sum ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int totalSumDivisibleByNum ( int digit , int number ) { int firstnum = ( int ) Math . pow ( 10 , digit - 1 ) ; int lastnum = ( int ) Math . pow ( 10 , digit ) ; firstnum = ( firstnum - firstnum % number ) + number ; lastnum = ( lastnum - lastnum % number ) ; int count = ( ( lastnum - firstnum ) / number + 1 ) ; return ( ( lastnum + firstnum ) * count ) / 2 ; } public static void main ( String [ ] args ) { int n = 3 , number = 7 ; System . out . println ( totalSumDivisibleByNum ( n , number ) ) ; } }


"Sum of n digit numbers divisible by a given number | Simple Java program to sum of n digit divisible numbers . ; Returns sum of n digit numbers divisible by ' number ' ; compute the first and last term ; sum of number which having n digit and divisible by number ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int totalSumDivisibleByNum ( int n , int number ) { int firstnum = ( int ) Math . pow ( 10 , n - 1 ) ; int lastnum = ( int ) Math . pow ( 10 , n ) ; int sum = 0 ; for ( int i = firstnum ; i < lastnum ; i ++ ) if ( i % number == 0 ) sum += i ; return sum ; } public static void main ( String [ ] args ) { int n = 3 , num = 7 ; System . out . println ( totalSumDivisibleByNum ( n , num ) ) ; } }


"Sum of nodes at maximum depth of a Binary Tree | Java code for sum of nodes at maximum depth ; Constructor ; function to find the sum of nodes at maximum depth arguments are node and max , where max is to match the depth of node at every call to node , if max will be equal to 1 , means we are at deepest node . ; base case ; max == 1 to track the node at deepest level ; recursive call to left and right nodes ; maxDepth function to find the max depth of the tree ; base case ; either leftDepth of rightDepth is greater add 1 to include height of node at which call is ; call to function to calculate max depth ; Driver code ; Constructing tree ; call to calculate required sum"
How can the above be solved in Java?

import java . util . * ; class Node { int data ; Node left , right ; public Node ( int data ) { this . data = data ; this . left = null ; this . right = null ; } } class GfG { public static int sumMaxLevelRec ( Node node , int max ) { if ( node == null ) return 0 ; if ( max == 1 ) return node . data ; return sumMaxLevelRec ( node . left , max - 1 ) + sumMaxLevelRec ( node . right , max - 1 ) ; } public static int maxDepth ( Node node ) { if ( node == null ) return 0 ; return 1 + Math . max ( maxDepth ( node . left ) , maxDepth ( node . right ) ) ; } public static int sumMaxLevel ( Node root ) { int MaxDepth = maxDepth ( root ) ; return sumMaxLevelRec ( root , MaxDepth ) ; } public static void main ( String [ ] args ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . right . left = new Node ( 6 ) ; root . right . right = new Node ( 7 ) ; System . out . println ( sumMaxLevel ( root ) ) ; } }


"Sum of nodes at maximum depth of a Binary Tree | Java code to find the sum of the nodes which are present at the maximum depth . ; Function to return a new node ; Function to find the sum of the node which are present at the maximum depth . While traversing the nodes compare the level of the node with max_level ( Maximum level till the current node ) . If the current level exceeds the maximum level , update the max_level as current level . If the max level and current level are same , add the root data to current sum . ; Driver Code"
How can the above be solved in Java?

class GFG { static int sum = 0 , max_level = Integer . MIN_VALUE ; static class Node { int d ; Node l ; Node r ; } ; static Node createNode ( int d ) { Node node ; node = new Node ( ) ; node . d = d ; node . l = null ; node . r = null ; return node ; } static void sumOfNodesAtMaxDepth ( Node ro , int level ) { if ( ro == null ) return ; if ( level > max_level ) { sum = ro . d ; max_level = level ; } else if ( level == max_level ) { sum = sum + ro . d ; } sumOfNodesAtMaxDepth ( ro . l , level + 1 ) ; sumOfNodesAtMaxDepth ( ro . r , level + 1 ) ; } public static void main ( String [ ] args ) { Node root ; root = createNode ( 1 ) ; root . l = createNode ( 2 ) ; root . r = createNode ( 3 ) ; root . l . l = createNode ( 4 ) ; root . l . r = createNode ( 5 ) ; root . r . l = createNode ( 6 ) ; root . r . r = createNode ( 7 ) ; sumOfNodesAtMaxDepth ( root , 0 ) ; System . out . println ( sum ) ; } }


"Sum of nodes in a Binary Search Tree with values from a given range | Java program for the above approach ; Class for node of the Tree ; Function to create a new BST node ; Return the newly created node ; Stores the sum of all nodes lying in the range [ L , R ] ; Function to perform level order traversal on the Tree and calculate the required sum ; Base Case ; Stores the nodes while performing level order traversal ; Push the root node into the queue ; Iterate until queue is empty ; Stores the front node of the queue ; If the value of the node lies in the given range ; Add it to sum ; If the left child is not null and exceeds low ; Insert into queue ; If the right child is not null and exceeds low ; Insert into queue ; Return the resultant sum ; Function to insert a new node into the Binary Search Tree ; Base Case ; If the data is less than the value of the current node ; Recur for left subtree ; Otherwise ; Recur for the right subtree ; Return the node ; Driver Code ; Let us create following BST 10 / \ 5 15 / \ \ 3 7 18"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int val ; Node left , right ; } ; static Node newNode ( int item ) { Node temp = new Node ( ) ; temp . val = item ; temp . left = temp . right = null ; return temp ; } static int sum = 0 ; static int rangeSumBST ( Node root , int low , int high ) { if ( root == null ) return 0 ; Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; while ( q . isEmpty ( ) == false ) { Node curr = q . peek ( ) ; q . remove ( ) ; if ( curr . val >= low && curr . val <= high ) { sum += curr . val ; } if ( curr . left != null && curr . val > low ) q . add ( curr . left ) ; if ( curr . right != null && curr . val < high ) q . add ( curr . right ) ; } return sum ; } static Node insert ( Node node , int data ) { if ( node == null ) return newNode ( data ) ; if ( data <= node . val ) node . left = insert ( node . left , data ) ; else node . right = insert ( node . right , data ) ; return node ; } public static void main ( String [ ] args ) { Node root = null ; root = insert ( root , 10 ) ; insert ( root , 5 ) ; insert ( root , 15 ) ; insert ( root , 3 ) ; insert ( root , 7 ) ; insert ( root , 18 ) ; int L = 7 , R = 15 ; System . out . print ( rangeSumBST ( root , L , R ) ) ; } }


"Sum of nodes in the path from root to N | Java program for the above approach ; Function to find sum of aint nodes from root to N ; If N is equal to 1 ; If N is equal to 2 or 3 ; Stores the number of nodes at ( i + 1 ) - th level ; Stores the number of nodes ; Stores if the current level is even or odd ; If level is odd ; If level is even ; If level with node N is reached ; Push into vector ; Compute prefix sums of count of nodes in each level ; Stores the level in which node N s present ; Stores the required sum ; Add temp to the sum ; Driver Code ; Function Call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int sumOfPathNodes ( int N ) { if ( N == 1 ) { return 1 ; } else if ( N == 2 N == 3 ) { return N + 1 ; } Vector < Integer > arr = new Vector < > ( ) ; arr . add ( 1 ) ; int k = 1 ; boolean flag = true ; while ( k < N ) { if ( flag == true ) { k *= 2 ; flag = false ; } else { k *= 4 ; flag = true ; } if ( k > N ) { break ; } arr . add ( k ) ; } int len = arr . size ( ) ; int [ ] prefix = new int [ len ] ; prefix [ 0 ] = 1 ; for ( int i = 1 ; i < len ; ++ i ) { prefix [ i ] = arr . get ( i ) + prefix [ i - 1 ] ; } int it = lowerBound ( prefix , 0 , len , N ) + 1 ; int ind = it - prefix [ 0 ] ; int final_ans = 0 ; int temp = N ; while ( ind > 1 ) { int val = temp - prefix [ ind - 1 ] ; if ( ind % 2 != 0 ) { temp = prefix [ ind - 2 ] + ( val + 1 ) / 2 ; } else { temp = prefix [ ind - 2 ] + ( val + 3 ) / 4 ; } -- ind ; final_ans += temp ; } final_ans += ( N + 1 ) ; return final_ans ; } static int lowerBound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) low = middle + 1 ; else high = middle ; } return low ; } public static void main ( String [ ] args ) { int N = 13 ; System . out . print ( sumOfPathNodes ( N ) + "
"); } }


"Sum of nodes on the longest path from root to leaf node | Java implementation to find the sum of nodes on the longest path from root to leaf node ; Node of a binary tree ; function to find the sum of nodes on the longest path from root to leaf node ; if true , then we have traversed a root to leaf path ; update maximum length and maximum sum according to the given conditions ; recur for left subtree ; recur for right subtree ; utility function to find the sum of nodes on the longest path from root to leaf node ; if tree is NULL , then sum is 0 ; finding the maximum sum ' maxSum ' for the maximum length root to leaf path ; required maximum sum ; Driver program to test above ; binary tree formation ; 4 ; / \ ; 2 5 ; / \ / \ ; 7 1 2 3 ; 6"
How can the above be solved in Java?

public class GFG { static class Node { int data ; Node left , right ; Node ( int data ) { this . data = data ; left = null ; right = null ; } } static int maxLen ; static int maxSum ; static void sumOfLongRootToLeafPath ( Node root , int sum , int len ) { if ( root == null ) { if ( maxLen < len ) { maxLen = len ; maxSum = sum ; } else if ( maxLen == len && maxSum < sum ) maxSum = sum ; return ; } sumOfLongRootToLeafPath ( root . left , sum + root . data , len + 1 ) ; sumOfLongRootToLeafPath ( root . right , sum + root . data , len + 1 ) ; } static int sumOfLongRootToLeafPathUtil ( Node root ) { if ( root == null ) return 0 ; maxSum = Integer . MIN_VALUE ; maxLen = 0 ; sumOfLongRootToLeafPath ( root , 0 , 0 ) ; return maxSum ; } public static void main ( String args [ ] ) { Node root = new Node ( 4 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 5 ) ; root . left . left = new Node ( 7 ) ; root . left . right = new Node ( 1 ) ; root . right . left = new Node ( 2 ) ; root . right . right = new Node ( 3 ) ; root . left . right . left = new Node ( 6 ) ; System . out . println ( " Sum ▁ = ▁ " + sumOfLongRootToLeafPathUtil ( root ) ) ; } }


"Sum of non | Java implementation of the above approach ; Function to return a vector which consists the sum of four portions of the matrix ; Iterating through the matrix ; Condition for selecting all values before the second diagonal of metrics ; Top portion of the matrix ; Left portion of the matrix ; Bottom portion of the matrix ; Right portion of the matrix ; Adding all the four portions into a vector ; Driver code"
How can the above be solved in Java?

class GFG { static int sumOfParts ( int [ ] [ ] arr , int N ) { int sum_part1 = 0 , sum_part2 = 0 , sum_part3 = 0 , sum_part4 = 0 ; int totalsum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i + j < N - 1 ) { if ( i < j && i != j && i + j > 0 ) sum_part1 += arr [ i ] [ j ] ; else if ( i != j ) sum_part2 += arr [ i ] [ j ] ; } else { if ( i > j && i + j != N - 1 ) sum_part3 += arr [ i ] [ j ] ; else { if ( i + j != N - 1 && i != j ) sum_part4 += arr [ i ] [ j ] ; } } } } totalsum = sum_part1 + sum_part2 + sum_part3 + sum_part4 ; return totalsum ; } public static void main ( String [ ] args ) { int N = 4 ; int arr [ ] [ ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; System . out . print ( sumOfParts ( arr , N ) ) ; } }


"Sum of nth terms of Modified Fibonacci series made by every pair of two arrays | Java program to find sum of n - th terms of a Fibonacci like series formed using first two terms of two arrays . ; if sum of first term is required ; if sum of second term is required ; fibonacci series used to find the nth term of every series ; as every b [ i ] term appears m times and every a [ i ] term also appears m times ; Driver code ; m is the size of the array"
How can the above be solved in Java?

public class GFG { static int sumNth ( int A [ ] , int B [ ] , int m , int n ) { int res = 0 ; if ( n == 1 ) { for ( int i = 0 ; i < m ; i ++ ) res = res + A [ i ] ; } else if ( n == 2 ) { for ( int i = 0 ; i < m ; i ++ ) res = res + B [ i ] * m ; } else { int f [ ] = new int [ n ] ; f [ 0 ] = 0 ; f [ 1 ] = 1 ; for ( int i = 2 ; i < n ; i ++ ) f [ i ] = f [ i - 1 ] + f [ i - 2 ] ; for ( int i = 0 ; i < m ; i ++ ) { res = res + ( m * ( B [ i ] * f [ n - 1 ] ) ) + ( m * ( A [ i ] * f [ n - 2 ] ) ) ; } } return res ; } public static void main ( String args [ ] ) { int A [ ] = { 1 , 2 , 3 } ; int B [ ] = { 4 , 5 , 6 } ; int n = 3 ; int m = A . length ; System . out . println ( sumNth ( A , B , m , n ) ) ; } }


"Sum of numbers formed by consecutive digits present in a given string | Java program to implement the above approach ; Function to calculate the sum of numbers formed by consecutive sequences of digits present in the string ; Stores consecutive digits present in the string ; Stores the sum ; Iterate over characters of the input string ; If current character is a digit ; Append current digit to curr ; Add curr to sum ; Reset curr ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int sumOfDigits ( String s ) { int curr = 0 ; int ret = 0 ; for ( char ch : s . toCharArray ( ) ) { if ( ch >= 48 && ch <= 57 ) { curr = curr * 10 + ch - '0' ; } else { ret += curr ; curr = 0 ; } } ret += curr ; return ret ; } public static void main ( String [ ] args ) { String S = "11aa32bbb5" ; System . out . print ( sumOfDigits ( S ) ) ; } }


"Sum of numbers from 1 to N which are in Lucas Sequence | java program to find sum of numbers from 1 to N which are in Lucas Sequence ; Function to return the required sum ; Generate lucas number and keep on adding them ; Driver code"
How can the above be solved in Java?

class GFG { static int LucasSum ( int N ) { int sum = 0 ; int a = 2 , b = 1 , c ; sum += a ; while ( b <= N ) { sum += b ; c = a + b ; a = b ; b = c ; } return sum ; } public static void main ( String [ ] args ) { int N = 20 ; System . out . println ( LucasSum ( N ) ) ; } }


"Sum of numbers in a range [ L , R ] whose count of divisors is prime | Java implementation of above approach ; prime [ i ] stores 1 if i is prime ; divi [ i ] stores the count of divisors of i ; sum [ i ] will store the sum of all the integers from 0 to i whose count of divisors is prime ; Function for Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be 0 if i is Not a prime , else true . ; 0 and 1 is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to count the divisors ; For each number i we will go to each of the multiple of i and update the count of divisor of its multiple j as i is one of the factor of j ; Function for pre - computation ; If count of divisors of i is prime ; taking prefix sum ; Driver code ; Find all the prime numbers till N ; Update the count of divisors of all the numbers till N ; Precomputation for the prefix sum array ; Perform query"
How can the above be solved in Java?

import java . util . * ; class GFG { static int N = 100000 ; static int prime [ ] = new int [ N ] ; static int divi [ ] = new int [ N ] ; static int sum [ ] = new int [ N ] ; static void SieveOfEratosthenes ( ) { for ( int i = 0 ; i < N ; i ++ ) prime [ i ] = 1 ; prime [ 0 ] = prime [ 1 ] = 0 ; for ( int p = 2 ; p * p < N ; p ++ ) { if ( prime [ p ] == 1 ) { for ( int i = p * p ; i < N ; i += p ) prime [ i ] = 0 ; } } } static void DivisorCount ( ) { for ( int i = 1 ; i < N ; i ++ ) { for ( int j = i ; j < N ; j += i ) { divi [ j ] ++ ; } } } static void pre ( ) { for ( int i = 1 ; i < N ; i ++ ) { if ( prime [ divi [ i ] ] == 1 ) { sum [ i ] = i ; } } for ( int i = 1 ; i < N ; i ++ ) sum [ i ] += sum [ i - 1 ] ; } public static void main ( String args [ ] ) { int l = 5 , r = 8 ; SieveOfEratosthenes ( ) ; DivisorCount ( ) ; pre ( ) ; System . out . println ( sum [ r ] - sum [ l - 1 ] ) ; } }


"Sum of numbers in the Kth level of a Fibonacci triangle | Java implementation to find the Sum of numbers in the Kth level of a Fibonacci triangle ; Function to return the nth Fibonacci number ; Function to return the required sum of the array ; Using our deduced result ; Function to return the sum of fibonacci in the Kth array ; Count of fibonacci which are in the arrays from 1 to k - 1 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int fib ( int n ) { double phi = ( 1 + Math . sqrt ( 5 ) ) / 2 ; return ( int ) Math . round ( Math . pow ( phi , n ) / Math . sqrt ( 5 ) ) ; } static int calculateSum ( int l , int r ) { int sum = fib ( r + 2 ) - fib ( l + 1 ) ; return sum ; } static int sumFibonacci ( int k ) { int l = ( k * ( k - 1 ) ) / 2 ; int r = l + k ; int sum = calculateSum ( l , r - 1 ) ; return sum ; } public static void main ( String args [ ] ) { int k = 3 ; System . out . println ( sumFibonacci ( k ) ) ; } }


"Sum of numbers obtained by the count of set and non | Java program for the above approach ; Functino to find the number after processing the diagonal elements ; Store the required number ; Checking for each position ; Store the number of set bits & non - set bits at position i ; Traverse the diagonal elements ; Update count of S if current element is set at position i ; Else update NS ; If number of set bits is > number of non - set bits , add set bits value to the ans ; Return the answer ; Function to find the sum of the numbers generated after processing both the diagonals of the matrix ; Store the primary diagonal elements ; Store the secondary diagonal elements ; Function Call to get the required numbers and return their sum ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int processDiagonal ( ArrayList < Integer > arr ) { int ans = 0 ; int getBit = 1 ; for ( int i = 0 ; i < 32 ; i ++ ) { int S = 0 ; int NS = 0 ; for ( int j : arr ) { if ( ( getBit & j ) != 0 ) S += 1 ; else NS += 1 ; } if ( S > NS ) ans += Math . pow ( 2 , i ) ; getBit <<= 1 ; } return ans ; } static int findSum ( int [ ] [ ] mat ) { int i = 0 ; int j = 0 ; ArrayList < Integer > priDiag = new ArrayList < Integer > ( ) ; while ( i < mat . length ) { priDiag . add ( mat [ i ] [ j ] ) ; i += 1 ; j += 1 ; } i = 0 ; j = mat . length - 1 ; ArrayList < Integer > secDiag = new ArrayList < Integer > ( ) ; while ( i < mat . length ) { secDiag . add ( mat [ i ] [ j ] ) ; i += 1 ; j -= 1 ; } return ( processDiagonal ( priDiag ) + processDiagonal ( secDiag ) ) ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; System . out . print ( findSum ( mat ) ) ; } }