"Sum of all N | Java program for the above approach ; Function to find a ^ b efficiently ; Base Case ; To store the value of a ^ b ; Multiply temp by a until b is not 0 ; Return the final ans a ^ b ; Function to find sum of all N - digit palindromic number divisible by 9 ; Base Case ; If N is even , decrease ways by 1 ; Find the total number of ways ; Iterate over [ 1 , N ] and find the sum at each index ; Print the final Sum ; Driver Code"
How can the above be solved in Java?

 class GFG { static int MOD = 1000000007 ; static int power ( int a , int b ) { if ( b == 0 ) return 1 ; int temp = power ( a , b / 2 ) ; temp = ( temp * temp ) % MOD ; if ( b % 2 != 0 ) { temp = ( temp * a ) % MOD ; } return temp ; } static void palindromicSum ( int N ) { int sum = 0 , res , ways ; if ( N == 1 ) { System . out . print ( "9" + "
"); return ; } if ( N == 2 ) { System . out . print ( "99" + "
"); return ; } ways = N / 2 ; if ( N % 2 == 0 ) ways -- ; res = power ( 9 , ways - 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { sum = sum * 10 + 45 * res ; sum %= MOD ; } System . out . print ( sum + "
"); } public static void main ( String [ ] args ) { int N = 3 ; palindromicSum ( N ) ; } }


"Sum of all Non | Java implementation to find the sum of all non - fibonacci numbers in a range from L to R ; Array to precompute the sum of non - fibonacci numbers ; Function to find if a number is a perfect square ; Function that returns N if N is non - fibonacci number ; N is Fibinacci if one of 5 * n * n + 4 or 5 * n * n - 4 or both are perferct square ; Function to precompute sum of non - fibonacci Numbers ; Function to find the sum of all non - fibonacci numbers in a range ; Driver Code ; Pre - computation ; Loop to find the sum for each query"
How can the above be solved in Java?

import java . util . * ; class GFG { static long pref [ ] = new long [ 100010 ] ; static boolean isPerfectSquare ( int x ) { int s = ( int ) Math . sqrt ( x ) ; return ( s * s == x ) ; } static int isNonFibonacci ( int n ) { if ( isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ) return 0 ; else return n ; } static void compute ( ) { for ( int i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + isNonFibonacci ( i ) ; } } static void printSum ( int L , int R ) { int sum = ( int ) ( pref [ R ] - pref [ L - 1 ] ) ; System . out . print ( sum + " ▁ " ) ; } public static void main ( String [ ] args ) { compute ( ) ; int Q = 2 ; int arr [ ] [ ] = { { 1 , 5 } , { 6 , 10 } } ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } }


"Sum of all Perfect Cubes lying in the range [ L , R ] for Q queries | Java program to find the sum of all perfect cubes in the given range ; Array to precompute the sum of cubes from 1 to 100010 so that for every query , the answer can be returned in O ( 1 ) . ; Function to check if a number is a perfect Cube or not ; Find floating point value of cube root of x . ; If cube root of x is cr return the x , else 0 ; Function to precompute the perfect Cubes upto 100000. ; Function to print the sum for each query ; Driver code ; To calculate the precompute function ; Calling the printSum function for every query"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { public static int [ ] pref = new int [ 100010 ] ; static int isPerfectCube ( int x ) { double cr = Math . round ( Math . cbrt ( x ) ) ; if ( cr * cr * cr == ( double ) x ) return x ; return 0 ; } static void compute ( ) { for ( int i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + isPerfectCube ( i ) ; } } static void printSum ( int L , int R ) { long sum = pref [ R ] - pref [ L - 1 ] ; System . out . print ( sum + " ▁ " ) ; } public static void main ( String [ ] args ) { compute ( ) ; int Q = 4 ; int [ ] [ ] arr = { { 1 , 10 } , { 1 , 100 } , { 2 , 25 } , { 4 , 50 } } ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } }


"Sum of all Perfect Squares lying in the range [ L , R ] for Q queries | Java program to find the sum of all perfect squares in the given range ; Array to precompute the sum of squares from 1 to 100010 so that for every query , the answer can be returned in O ( 1 ) . ; Function to check if a number is a perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; Function to precompute the perfect squares upto 100000. ; Function to print the sum for each query ; Driver code ; To calculate the precompute function ; Calling the printSum function for every query"
How can the above be solved in Java?

class GFG { static int [ ] pref = new int [ 100010 ] ; static int isPerfectSquare ( int x ) { double sr = Math . sqrt ( x ) ; return ( ( sr - Math . floor ( sr ) ) == 0 ) ? x : 0 ; } static void compute ( ) { for ( int i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + isPerfectSquare ( i ) ; } } static void printSum ( int L , int R ) { int sum = pref [ R ] - pref [ L - 1 ] ; System . out . print ( sum + " ▁ " ) ; } public static void main ( String [ ] args ) { compute ( ) ; int Q = 4 ; int arr [ ] [ ] = { { 1 , 10 } , { 1 , 100 } , { 2 , 25 } , { 4 , 50 } } ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } }


"Sum of all Perfect numbers lying in the range [ L , R ] | Java implementation to find the sum of all perfect numbers lying in the range [ L , R ] ; Array to store the sum ; Function to check if a number is a perfect number or not ; Iterating till the square root of the number and checking if the sum of divisors is equal to the number or not ; If it is a perfect number , then return the number ; Else , return 0 ; Function to precompute the sum of perfect squares and store then in an array"
How can the above be solved in Java?

class GFG { static int pref [ ] = new int [ 10000 ] ; static int isPerfect ( int n ) { int sum = 1 ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { if ( i * i != n ) sum = sum + i + n / i ; else sum = sum + i ; } } if ( sum == n && n != 1 ) return n ; return 0 ; } static void precomputation ( ) { for ( int i = 1 ; i < 10000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + isPerfect ( i ) ; } } public static void main ( String [ ] args ) { int L = 6 , R = 28 ; precomputation ( ) ; System . out . println ( pref [ R ] - pref [ L - 1 ] ) ; } }


"Sum of all Primes in a given range using Sieve of Eratosthenes | Java program to find sum of primes in range L to R ; prefix [ i ] is going to store sum of primes till i ( including i ) . ; Function to build the prefix sum array ; Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Build prefix array ; Function to return sum of prime in range ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static final int MAX = 10000 ; static int prefix [ ] = new int [ MAX + 1 ] ; static void buildPrefix ( ) { boolean prime [ ] = new boolean [ MAX + 1 ] ; for ( int i = 0 ; i < MAX + 1 ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } prefix [ 0 ] = prefix [ 1 ] = 0 ; for ( int p = 2 ; p <= MAX ; p ++ ) { prefix [ p ] = prefix [ p - 1 ] ; if ( prime [ p ] == true ) prefix [ p ] += p ; } } static int sumPrimeRange ( int L , int R ) { buildPrefix ( ) ; return prefix [ R ] - prefix [ L - 1 ] ; } public static void main ( String args [ ] ) { int L = 10 , R = 20 ; System . out . println ( sumPrimeRange ( L , R ) ) ; } }


"Sum of all Submatrices of a Given Matrix | Java program to find the sum of all possible submatrices of a given Matrix ; Function to find the sum of all possible submatrices of a given Matrix ; Varialbe to store the required sum ; Nested loop to find the number of submatrices , each number belongs to ; Number of ways to choose from top - left elements ; Number of ways to choose from bottom - right elements ; Driver Code"
How can the above be solved in Java?

class GFG { static final int n = 3 ; static int matrixSum ( int arr [ ] [ ] ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { int top_left = ( i + 1 ) * ( j + 1 ) ; int bottom_right = ( n - i ) * ( n - j ) ; sum += ( top_left * bottom_right * arr [ i ] [ j ] ) ; } } return sum ; } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 1 , 1 , 1 } , { 1 , 1 , 1 } , { 1 , 1 , 1 } } ; System . out . println ( matrixSum ( arr ) ) ; } }


"Sum of all armstrong numbers lying in the range [ L , R ] for Q queries | Java program to find the sum of all armstrong numbers in the given range ; pref [ ] array to precompute the sum of all armstrong number ; Function that return number num if num is armstrong else return 0 ; Function to precompute the sum of all armstrong numbers upto 100000 ; checkarmstrong ( ) return the number i if i is armstrong else return 0 ; Function to print the sum for each query ; Function to prsum of all armstrong numbers between [ L , R ] ; Function that pre computes the sum of all armstrong numbers ; Iterate over all Queries to print the sum ; Driver code ; Queries ; Function that print the the sum of all armstrong number in Range [ L , R ]"
How can the above be solved in Java?

class GFG { static int [ ] pref = new int [ 100001 ] ; static int checkArmstrong ( int x ) { int n = String . valueOf ( x ) . length ( ) ; int sum1 = 0 ; int temp = x ; while ( temp > 0 ) { int digit = temp % 10 ; sum1 += Math . pow ( digit , n ) ; temp /= 10 ; } if ( sum1 == x ) return x ; return 0 ; } static void preCompute ( ) { for ( int i = 1 ; i < 100001 ; i ++ ) { pref [ i ] = pref [ i - 1 ] + checkArmstrong ( i ) ; } } static void printSum ( int L , int R ) { System . out . println ( pref [ R ] - pref [ L - 1 ] ) ; } static void printSumarmstrong ( int [ ] [ ] arr , int Q ) { preCompute ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } public static void main ( String [ ] args ) { int Q = 2 ; int [ ] [ ] arr = { { 1 , 13 } , { 121 , 211 } } ; printSumarmstrong ( arr , Q ) ; } }


"Sum of all composite numbers lying in the range [ L , R ] for Q queries | Java implementation to find the sum of all Composite numbers in the given range ; Prefix array to precompute the sum of all Composite number ; Function that return number num if num is Composite else return 0 ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to precompute the sum of all Composite numbers upto 100000 ; checkComposite ( ) return the number i if i is Composite else return 0 ; Function to print the sum for each query ; Function to print sum of all Composite numbers between [ L , R ] ; Function that pre computes the sum of all Composite numbers ; Iterate over all Queries to print the sum ; Driver code ; Queries ; Function that print the the sum of all Composite number in Range [ L , R ]"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int [ ] pref = new int [ 100001 ] ; static int isComposite ( int n ) { if ( n <= 1 ) return 0 ; if ( n <= 3 ) return 0 ; if ( n % 2 == 0 n % 3 == 0 ) return n ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return n ; return 0 ; } static void preCompute ( ) { for ( int i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + isComposite ( i ) ; } } static void printSum ( int L , int R ) { System . out . print ( pref [ R ] - pref [ L - 1 ] + "
"); } static void printSumComposite ( int arr [ ] [ ] , int Q ) { preCompute ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } public static void main ( String [ ] args ) { int Q = 2 ; int arr [ ] [ ] = { { 10 , 13 } , { 12 , 21 } } ; printSumComposite ( arr , Q ) ; } }


"Sum of all differences between Maximum and Minimum of increasing Subarrays | Java program to find the sum of differences of maximum and minimum of strictly increasing subarrays ; Function to calculate and return the sum of differences of maximum and minimum of strictly increasing subarrays ; Stores the sum ; Traverse the array ; If last element of the increasing sub - array is found ; Update sum ; If the last element of the array is reached ; Update sum ; Return the sum ; Driver Code"
How can the above be solved in Java?

class GFG { static int sum_of_differences ( int arr [ ] , int N ) { int sum = 0 ; int i , j , flag ; for ( i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] < arr [ i + 1 ] ) { flag = 0 ; for ( j = i + 1 ; j < N - 1 ; j ++ ) { if ( arr [ j ] >= arr [ j + 1 ] ) { sum += ( arr [ j ] - arr [ i ] ) ; i = j ; flag = 1 ; break ; } } if ( flag == 0 && arr [ i ] < arr [ N - 1 ] ) { sum += ( arr [ N - 1 ] - arr [ i ] ) ; break ; } } } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 1 , 2 , 5 , 3 , 4 } ; int N = arr . length ; System . out . print ( sum_of_differences ( arr , N ) ) ; } }


"Sum of all distances between occurrences of same characters in a given string | Java program for the above approach ; Function to calculate the sum of distances between occurrences of same characters in a String ; If similar characters are found ; Add the difference of their positions ; Return the answer ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int findSum ( String s ) { int sum = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { for ( int j = i + 1 ; j < s . length ( ) ; j ++ ) { if ( s . charAt ( i ) == s . charAt ( j ) ) { sum += ( j - i ) ; } } } return sum ; } public static void main ( String [ ] args ) { String s = " ttt " ; System . out . print ( findSum ( s ) + "
"); } }


"Sum of all divisors from 1 to n |  ; int t1 = i * ( num / i - i + 1 ) ; adding i every time it appears with numbers greater than or equal to itself int t2 = ( ( ( num / i ) * ( num / i + 1 ) ) / 2 ) - ( ( i * ( i + 1 ) ) / 2 ) ; adding numbers that appear with i and are greater than i ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int sum_all_divisors ( int num ) { int sum = 0 ; for ( int i = 1 ; i <= Math . sqrt ( num ) ; i ++ ) { sum += t1 + t2 ; } return sum ; } public static void main ( String [ ] args ) { int n = 1 ; int sum = sum_all_divisors ( n ) ; System . out . println ( sum ) ; } }


"Sum of all divisors from 1 to n | JAVA program to find sum of all divisor of number up to ' n ' ; Utility function to find sum of all divisor of number up to ' n ' ; Find all divisors of i and add them ; Driver code"
How can the above be solved in Java?

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


"Sum of all divisors from 1 to n | Java program to find sum of all divisor of number up to ' n ' ; Utility function to find sum of all divisor of number up to ' n ' ; Driver code"
How can the above be solved in Java?

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


"Sum of all elements between k1 ' th ▁ and ▁ k2' th smallest elements | Java implementation of above approach ; Driver code ; decreasing value by 1 because we want min heapifying k times and it starts from 0 so we have to decrease it 1 time ; Step 1 : Do extract minimum k1 times ( This step takes O ( K1 Log n ) time ) ; Step 2 : Do extract minimum k2 k1 1 times and sum all extracted elements . ( This step takes O ( ( K2 k1 ) * Log n ) time )"
How can the above be solved in Java?

class GFG { static int n = 7 ; static void minheapify ( int [ ] a , int index ) { int small = index ; int l = 2 * index + 1 ; int r = 2 * index + 2 ; if ( l < n && a [ l ] < a [ small ] ) small = l ; if ( r < n && a [ r ] < a [ small ] ) small = r ; if ( small != index ) { int t = a [ small ] ; a [ small ] = a [ index ] ; a [ index ] = t ; minheapify ( a , small ) ; } } public static void main ( String [ ] args ) { int i = 0 ; int k1 = 3 ; int k2 = 6 ; int [ ] a = { 20 , 8 , 22 , 4 , 12 , 10 , 14 } ; int ans = 0 ; for ( i = ( n / 2 ) - 1 ; i >= 0 ; i -- ) { minheapify ( a , i ) ; } k1 -- ; k2 -- ; for ( i = 0 ; i <= k1 ; i ++ ) { a [ 0 ] = a [ n - 1 ] ; n -- ; minheapify ( a , 0 ) ; } for ( i = k1 + 1 ; i < k2 ; i ++ ) { ans += a [ 0 ] ; a [ 0 ] = a [ n - 1 ] ; n -- ; minheapify ( a , 0 ) ; } System . out . println ( ans ) ; } }


"Sum of all elements between k1 ' th ▁ and ▁ k2' th smallest elements | Java program to find sum of all element between to K1 ' th ▁ and ▁ k2' th smallest elements in array ; Returns sum between two kth smallest element of array ; Sort the given array ; Below code is equivalent to ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int sumBetweenTwoKth ( int arr [ ] , int k1 , int k2 ) { Arrays . sort ( arr ) ; int result = 0 ; for ( int i = k1 ; i < k2 - 1 ; i ++ ) result += arr [ i ] ; return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 20 , 8 , 22 , 4 , 12 , 10 , 14 } ; int k1 = 3 , k2 = 6 ; int n = arr . length ; System . out . print ( sumBetweenTwoKth ( arr , k1 , k2 ) ) ; } }


"Sum of all elements in an array between zeros | Java program for the above approach ; Function to find the sum between two zeros in the given array arr [ ] ; To store the sum of element between two zeros ; To store the sum ; Find first index of 0 ; Traverse the given array arr [ ] ; If 0 occurs then add it to A [ ] ; Else add element to the sum ; Print all the sum stored in A ; If there is no such element print - 1 ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void sumBetweenZero ( int arr [ ] , int N ) { int i = 0 ; Vector < Integer > A = new Vector < Integer > ( ) ; int sum = 0 ; for ( i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) { i ++ ; break ; } } for ( ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) { A . add ( sum ) ; sum = 0 ; } else { sum += arr [ i ] ; } } for ( int j = 0 ; j < A . size ( ) ; j ++ ) { System . out . print ( A . get ( j ) + " ▁ " ) ; } if ( A . size ( ) == 0 ) System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 0 , 3 , 4 , 0 , 4 , 4 , 0 , 2 , 1 , 4 , 0 , 3 } ; int N = arr . length ; sumBetweenZero ( arr , N ) ; } }


"Sum of all elements up to Nth row in a Pascal triangle | Java program to find sum of all elements upto nth row in Pascal triangle . ; Function to find sum of all elements upto nth row . ; Initialize sum with 0 ; Calculate 2 ^ n ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static long calculateSum ( int n ) { long sum = 0 ; sum = 1 << n ; return ( sum - 1 ) ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( " Sum ▁ of ▁ all ▁ elements : " + calculateSum ( n ) ) ; } }


"Sum of all elements up to Nth row in a Pascal triangle | Java program to find sum of all elements upto nth row in Pascal triangle . ; Function to find sum of all elements upto nth row . ; Initialize sum with 0 ; Loop to calculate power of 2 upto n and add them ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static long calculateSum ( int n ) { long sum = 0 ; for ( int row = 0 ; row < n ; row ++ ) { sum = sum + ( 1 << row ) ; } return sum ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( " Sum ▁ of ▁ all ▁ elements : " + calculateSum ( n ) ) ; } }


"Sum of all even factors of numbers in the range [ l , r ] | Java implementation of the approach ; Function to calculate the prefix sum of all the even factors ; Add i to all the multiples of i ; Update the prefix sum ; Function to return the sum of all the even factors of the numbers in the given range ; Driver code"
How can the above be solved in Java?

class GFG { static final int MAX = 100000 ; static long prefix [ ] = new long [ MAX ] ; static void sieve_modified ( ) { for ( int i = 2 ; i < MAX ; i += 2 ) { for ( int j = i ; j < MAX ; j += i ) prefix [ j ] += i ; } for ( int i = 1 ; i < MAX ; i ++ ) prefix [ i ] += prefix [ i - 1 ] ; } static long sumEvenFactors ( int L , int R ) { return ( prefix [ R ] - prefix [ L - 1 ] ) ; } public static void main ( String args [ ] ) { sieve_modified ( ) ; int l = 6 , r = 10 ; System . out . print ( sumEvenFactors ( l , r ) ) ; } }


"Sum of all even numbers in range L and R | Java program to print the sum of all even numbers in range L and R ; Function to return the sum of all natural numbers ; Function to return sum of even numbers in range L and R ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int sumNatural ( int n ) { int sum = ( n * ( n + 1 ) ) ; return sum ; } static int sumEven ( int l , int r ) { return sumNatural ( r / 2 ) - sumNatural ( ( l - 1 ) / 2 ) ; } public static void main ( String [ ] args ) { int l = 2 , r = 5 ; System . out . println ( " Sum ▁ of ▁ Natural ▁ numbers ▁ from ▁ L ▁ to ▁ R ▁ is ▁ " + sumEven ( l , r ) ) ; } }


"Sum of all i such that ( 2 ^ i + 1 ) % 3 = 0 where i is in range [ 1 , n ] | Java implementation of the approach ; Function to return the required sum ; Total odd numbers from 1 to n ; Sum of first n odd numbers ; Driver code"
How can the above be solved in Java?

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


"Sum of all leaf nodes of binary tree | Java program to find sum of all leaf nodes of binary tree ; user define class node ; constructor ; utility function which calculates sum of all leaf nodes ; add root data to sum if root is a leaf node ; propagate recursively in left and right subtree ; driver program ; construct binary tree ; variable to store sum of leaf nodes"
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 sum ; static void leafSum ( Node root ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) sum += root . data ; leafSum ( root . left ) ; leafSum ( root . right ) ; } public static void main ( String args [ ] ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . right = new Node ( 3 ) ; root . right . right = new Node ( 7 ) ; root . right . left = new Node ( 6 ) ; root . right . left . right = new Node ( 8 ) ; sum = 0 ; leafSum ( root ) ; System . out . println ( sum ) ; } }


"Sum of all mersenne numbers present in an array | Java implementation of the approach ; Function that returns true if n is a Mersenne number ; Function to return the sum of all the Mersenne numbers from the given array ; To store the required sum ; If current element is a Mersenne number ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isMersenne ( int n ) { while ( n != 0 ) { int r = n % 2 ; if ( r == 0 ) return false ; n /= 2 ; } return true ; } static int sumOfMersenne ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 && isMersenne ( arr [ i ] ) ) { sum += arr [ i ] ; } } return sum ; } public static void main ( String [ ] args ) { int [ ] arr = { 17 , 6 , 7 , 63 , 3 } ; int n = arr . length ; System . out . print ( sumOfMersenne ( arr , n ) ) ; } }


"Sum of all natural numbers from L to R ( for large values of L and R ) | Java implementation of the approach ; Value of inverse modulo 2 with 10 ^ 9 + 7 ; Function to return num % 1000000007 where num is a large number ; Initialize result ; One by one process all the digits of string ' num ' ; Function to return the sum of the longegers from the given range modulo 1000000007 ; a stores the value of L modulo 10 ^ 9 + 7 ; b stores the value of R modulo 10 ^ 9 + 7 ; l stores the sum of natural numbers from 1 to ( a - 1 ) ; r stores the sum of natural numbers from 1 to b ; If the result is negative ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static long mod = 1000000007 ; static long inv2 = 500000004 ; static long modulo ( String num ) { long res = 0 ; for ( int i = 0 ; i < num . length ( ) ; i ++ ) res = ( res * 10 + ( long ) num . charAt ( i ) - '0' ) % mod ; return res ; } static long findSum ( String L , String R ) { long a , b , l , r , ret ; a = modulo ( L ) ; b = modulo ( R ) ; l = ( ( a * ( a - 1 ) ) % mod * inv2 ) % mod ; r = ( ( b * ( b + 1 ) ) % mod * inv2 ) % mod ; ret = ( r % mod - l % mod ) ; if ( ret < 0 ) ret = ret + mod ; else ret = ret % mod ; return ret ; } public static void main ( String [ ] args ) { String L = "88949273204" ; String R = "98429729474298592" ; System . out . println ( findSum ( L , R ) ) ; } }


"Sum of all natural numbers in range L to R | Java program to print the sum of all numbers in range L and R ; Function to return the sum of all natural numbers ; Function to return the sum of all numbers in range L and R ; Driver Code"
How can the above be solved in Java?

class GFG { static int sumNatural ( int n ) { int sum = ( n * ( n + 1 ) ) / 2 ; return sum ; } static int suminRange ( int l , int r ) { return sumNatural ( r ) - sumNatural ( l - 1 ) ; } public static void main ( String [ ] args ) { int l = 2 , r = 5 ; System . out . println ( " Sum ▁ of ▁ Natural ▁ numbers ▁ from ▁ L ▁ to ▁ R ▁ is ▁ " + suminRange ( l , r ) ) ; } }


"Sum of all nodes in a binary tree | Java Program to print sum of all the elements of a binary tree ; utility that allocates a new Node with the given key ; Function to find sum of all the elements ; Driver Code"
How can the above be solved in Java?

class GFG { static class Node { int key ; Node left , right ; } static Node newNode ( int key ) { Node node = new Node ( ) ; node . key = key ; node . left = node . right = null ; return ( node ) ; } static int addBT ( Node root ) { if ( root == null ) return 0 ; return ( root . key + addBT ( root . left ) + addBT ( 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 ) ; root . right . left = newNode ( 6 ) ; root . right . right = newNode ( 7 ) ; root . right . left . right = newNode ( 8 ) ; int sum = addBT ( root ) ; System . out . println ( " Sum ▁ of ▁ all ▁ the ▁ elements ▁ is : ▁ " + sum ) ; } }


"Sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times | Java program to find sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times ; exactsum [ i ] [ j ] [ k ] stores the sum of all the numbers having exact i 4 ' s , ▁ j ▁ 5' s and k 6 's ; exactnum [ i ] [ j ] [ k ] stores numbers of numbers having exact i 4 ' s , ▁ j ▁ 5' s and k 6 's ; Utility function to calculate the sum for x 4 ' s , ▁ y ▁ 5' s and z 6 's ; Computing exactsum [ i ] [ j ] [ k ] as explained above ; Driver code"
How can the above be solved in Java?

class GFG { static int N = 101 ; static int mod = ( int ) 1e9 + 7 ; static int exactsum [ ] [ ] [ ] = new int [ N ] [ N ] [ N ] ; static int exactnum [ ] [ ] [ ] = new int [ N ] [ N ] [ N ] ; static int getSum ( int x , int y , int z ) { int ans = 0 ; exactnum [ 0 ] [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i <= x ; ++ i ) { for ( int j = 0 ; j <= y ; ++ j ) { for ( int k = 0 ; k <= z ; ++ k ) { if ( i > 0 ) { exactsum [ i ] [ j ] [ k ] += ( exactsum [ i - 1 ] [ j ] [ k ] * 10 + 4 * exactnum [ i - 1 ] [ j ] [ k ] ) % mod ; exactnum [ i ] [ j ] [ k ] += exactnum [ i - 1 ] [ j ] [ k ] % mod ; } if ( j > 0 ) { exactsum [ i ] [ j ] [ k ] += ( exactsum [ i ] [ j - 1 ] [ k ] * 10 + 5 * exactnum [ i ] [ j - 1 ] [ k ] ) % mod ; exactnum [ i ] [ j ] [ k ] += exactnum [ i ] [ j - 1 ] [ k ] % mod ; } if ( k > 0 ) { exactsum [ i ] [ j ] [ k ] += ( exactsum [ i ] [ j ] [ k - 1 ] * 10 + 6 * exactnum [ i ] [ j ] [ k - 1 ] ) % mod ; exactnum [ i ] [ j ] [ k ] += exactnum [ i ] [ j ] [ k - 1 ] % mod ; } ans += exactsum [ i ] [ j ] [ k ] % mod ; ans %= mod ; } } } return ans ; } public static void main ( String [ ] args ) { int x = 1 , y = 1 , z = 1 ; System . out . println ( getSum ( x , y , z ) % mod ) ; } }


"Sum of all numbers in the given range which are divisible by M | Java program to find the sum of numbers divisible by M in the given range ; Function to find the largest number smaller than or equal to N that is divisible by K ; Finding the remainder when N is divided by K ; If the remainder is 0 , then the number itself is divisible by K ; Else , then the difference between N and remainder is the largest number which is divisible by K ; Function to find the smallest number greater than or equal to N that is divisible by K ; Finding the remainder when N is divided by K ; If the remainder is 0 , then the number itself is divisible by K ; Else , then the difference between N and remainder is the largest number which is divisible by K ; Function to find the sum of numbers divisible by M in the given range ; Variable to store the sum ; To bring the smallest and largest numbers in the range [ A , B ] ; To count the number of terms in the AP ; Sum of n terms of an AP ; Driver code ; A and B define the range , M is the dividend ; Printing the result"
How can the above be solved in Java?

class GFG { static int findSmallNum ( int N , int K ) { int rem = N % K ; if ( rem == 0 ) return N ; else return N - rem ; } static int findLargeNum ( int N , int K ) { int rem = ( N + K ) % K ; if ( rem == 0 ) return N ; else return N + K - rem ; } static int sumDivisibles ( int A , int B , int M ) { int first = findSmallNum ( A , M ) ; int last = findLargeNum ( B , M ) ; if ( first < A ) first += M ; if ( last > B ) first -= M ; int n = ( B / M ) - ( A - 1 ) / M ; return n * ( first + last ) / 2 ; } public static void main ( String [ ] args ) { int A = 6 , B = 15 , M = 3 ; System . out . print ( sumDivisibles ( A , B , M ) ) ; } }


"Sum of all numbers in the given range which are divisible by M | Java program to find the sum of numbers divisible by M in the given range ; Function to find the sum of numbers divisible by M in the given range ; Variable to store the sum ; Running a loop from A to B and check if a number is divisible by i . ; If the number is divisible , then add it to sum ; Return the sum ; Driver code ; A and B define the range M is the dividend ; Printing the result"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int sumDivisibles ( int A , int B , int M ) { int sum = 0 ; for ( int i = A ; i <= B ; i ++ ) if ( i % M == 0 ) sum += i ; return sum ; } public static void main ( String [ ] args ) { int A = 6 , B = 15 , M = 3 ; System . out . print ( sumDivisibles ( A , B , M ) + "
"); } }


"Sum of all numbers up to N that are co | Java program for the above approach ; Function to return gcd of a and b ; Base Case ; Recursive GCD ; Function to calculate the sum of all numbers till N that are coprime with N ; Stores the resultant sum ; Iterate over [ 1 , N ] ; If gcd is 1 ; Update sum ; Return the final sum ; Driver Code ; Given N ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int findSum ( int N ) { int sum = 0 ; for ( int i = 1 ; i < N ; i ++ ) { if ( gcd ( i , N ) == 1 ) { sum += i ; } } return sum ; } public static void main ( String [ ] args ) { int N = 5 ; System . out . print ( findSum ( N ) ) ; } }


"Sum of all odd factors of numbers in the range [ l , r ] | Java implementation of the approach ; Function to calculate the prefix sum of all the odd factors ; Add i to all the multiples of i ; Update the prefix sum ; Function to return the sum of all the odd factors of the numbers in the given range ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int MAX = 100001 ; static int prefix [ ] = new int [ MAX ] ; static void sieve_modified ( ) { for ( int i = 1 ; i < MAX ; i += 2 ) { for ( int j = i ; j < MAX ; j += i ) prefix [ j ] += i ; } for ( int i = 1 ; i < MAX ; i ++ ) prefix [ i ] += prefix [ i - 1 ] ; } static int sumOddFactors ( int L , int R ) { return ( prefix [ R ] - prefix [ L - 1 ] ) ; } public static void main ( String [ ] args ) { sieve_modified ( ) ; int l = 6 , r = 10 ; System . out . println ( sumOddFactors ( l , r ) ) ; } }


"Sum of all odd length subarrays | Java program for the above approach ; Function that finds the sum of all the element of subarrays of odd length ; Stores the sum ; Size of array ; Traverse the given array arr [ ] ; Add to the sum for each contribution of the arr [ i ] ; Return the final sum ; Driver Code ; Given array arr [ ] ; Function call"
How can the above be solved in Java?

class GFG { static int OddLengthSum ( int [ ] arr ) { int sum = 0 ; int l = arr . length ; for ( int i = 0 ; i < l ; i ++ ) { sum += ( ( ( i + 1 ) * ( l - i ) + 1 ) / 2 ) * arr [ i ] ; } return sum ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 5 , 3 , 1 , 2 } ; System . out . print ( OddLengthSum ( arr ) ) ; } }


"Sum of all odd length subarrays | Java program for the above approach ; Function to calculate the sum of all odd length subarrays ; Stores the sum ; Size of array ; Traverse the array ; Generate all subarray of odd length ; Add the element to sum ; Return the final sum ; Driver Code ; Given array arr [ ] ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static int OddLengthSum ( int [ ] arr ) { int sum = 0 ; int l = arr . length ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = i ; j < l ; j += 2 ) { for ( int k = i ; k <= j ; k ++ ) { sum += arr [ k ] ; } } } return sum ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 5 , 3 , 1 , 2 } ; System . out . print ( OddLengthSum ( arr ) ) ; } }


"Sum of all odd natural numbers in range L and R | Java program to print the sum of all numbers in range L and R ; Function to return the sum of all odd natural numbers ; Function to return the sum of all odd numbers in range L and R ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int sumOdd ( int n ) { int terms = ( n + 1 ) / 2 ; int sum = terms * terms ; return sum ; } static int suminRange ( int l , int r ) { return sumOdd ( r ) - sumOdd ( l - 1 ) ; } public static void main ( String [ ] args ) { int l = 2 , r = 5 ; System . out . print ( " Sum ▁ of ▁ odd ▁ natural ▁ numbers ▁ from ▁ L ▁ to ▁ R ▁ is ▁ " + suminRange ( l , r ) ) ; } }


"Sum of all odd nodes in the path connecting two given nodes | Java program to find sum of all odd nodes in the path connecting two given nodes ; Binary Tree node ; Utitlity function to create a new Binary Tree node ; Function to check if there is a path from root to the given node . It also populates ' arr ' with the given path ; if root is null there is no path ; push the node ' s ▁ value ▁ in ▁ ' arr ' ; if it is the required node return true ; else check whether the required node lies in the left subtree or right subtree of the current node ; required node does not lie either in the left or right subtree of the current node Thus , remove current node ' s ▁ value ▁ from ▁ ▁ ' arr 'and then return false ; Function to get the sum of odd nodes in the path between any two nodes in a binary tree ; vector to store the path of first node n1 from root ; vector to store the path of second node n2 from root ; Get intersection point ; Keep moving forward until no intersection is found ; calculate sum of ODD nodes from the path ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class solution { static class Node { int data ; Node left ; Node right ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = null ; node . right = null ; return node ; } static boolean getPath ( Node root , Vector < Integer > arr , int x ) { if ( root == null ) return false ; arr . add ( root . data ) ; if ( root . data == x ) return true ; if ( getPath ( root . left , arr , x ) || getPath ( root . right , arr , x ) ) return true ; arr . remove ( arr . size ( ) - 1 ) ; return false ; } static int sumOddNodes ( Node root , int n1 , int n2 ) { Vector < Integer > path1 = new Vector < Integer > ( ) ; Vector < Integer > path2 = new Vector < Integer > ( ) ; getPath ( root , path1 , n1 ) ; getPath ( root , path2 , n2 ) ; int intersection = - 1 ; int i = 0 , j = 0 ; while ( i != path1 . size ( ) || j != path2 . size ( ) ) { if ( i == j && path1 . get ( i ) == path2 . get ( j ) ) { i ++ ; j ++ ; } else { intersection = j - 1 ; break ; } } int sum = 0 ; for ( i = path1 . size ( ) - 1 ; i > intersection ; i -- ) if ( path1 . get ( i ) % 2 != 0 ) sum += path1 . get ( i ) ; for ( i = intersection ; i < path2 . size ( ) ; i ++ ) if ( path2 . get ( i ) % 2 != 0 ) sum += path2 . get ( i ) ; 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 ) ; root . right . right = newNode ( 6 ) ; int node1 = 5 ; int node2 = 6 ; System . out . print ( sumOddNodes ( root , node1 , node2 ) ) ; } }


"Sum of all ordered pair | Java program to implement the above approach ; Function to calculate the sum of all pair - products ; Stores sum of array ; Update sum of the array ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int sumOfProd ( int arr [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; } return sum * sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 1 , 5 , 4 } ; int N = arr . length ; System . out . print ( sumOfProd ( arr , N ) ) ; } }


"Sum of all pair shortest paths in a Tree | Java program for the above approach ; Function that performs the Floyd Warshall to find all shortest paths ; Initialize the distance matrix ; Pick all vertices as source one by one ; Pick all vertices as destination for the above picked source ; If vertex k is on the shortest path from i to j then update dist [ i ] [ j ] ; Sum the upper diagonal of the shortest distance matrix ; Traverse the given dist [ ] [ ] ; Add the distance ; Return the final sum ; Function to generate the tree ; Add edges ; Get source and destination with weight ; Add the edges ; Perform Floyd Warshal Algorithm ; Driver code ; Number of Vertices ; Number of Edges ; Given Edges with weight ; Function Call"
How can the above be solved in Java?

class GFG { static final int INF = 99999 ; static int floyd_warshall ( int [ ] [ ] graph , int V ) { int [ ] [ ] dist = new int [ V ] [ V ] ; int i , j , k ; for ( i = 0 ; i < V ; i ++ ) { for ( j = 0 ; j < V ; j ++ ) { dist [ i ] [ j ] = graph [ i ] [ j ] ; } } for ( k = 0 ; k < V ; k ++ ) { for ( i = 0 ; i < V ; i ++ ) { for ( j = 0 ; j < V ; j ++ ) { if ( dist [ i ] [ k ] + dist [ k ] [ j ] < dist [ i ] [ j ] ) { dist [ i ] [ j ] = dist [ i ] [ k ] + dist [ k ] [ j ] ; } } } } int sum = 0 ; for ( i = 0 ; i < V ; i ++ ) { for ( j = i + 1 ; j < V ; j ++ ) { sum += dist [ i ] [ j ] ; } } return sum ; } static int sumOfshortestPath ( int N , int E , int edges [ ] [ ] ) { int [ ] [ ] g = new int [ N ] [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { g [ i ] [ j ] = INF ; } } for ( int i = 0 ; i < E ; i ++ ) { int u = edges [ i ] [ 0 ] ; int v = edges [ i ] [ 1 ] ; int w = edges [ i ] [ 2 ] ; g [ u ] [ v ] = w ; g [ v ] [ u ] = w ; } return floyd_warshall ( g , N ) ; } public static void main ( String [ ] args ) { int N = 4 ; int E = 3 ; int Edges [ ] [ ] = { { 0 , 1 , 1 } , { 1 , 2 , 2 } , { 2 , 3 , 3 } } ; System . out . print ( sumOfshortestPath ( N , E , Edges ) ) ; } }


"Sum of all palindrome numbers present in an Array | Java program to calculate the sum of all palindromic numbers in array ; Function to reverse a number n ; Function to check if a number n is palindrome ; If n is equal to the reverse of n it is a palindrome ; Function to calculate sum of all array elements which are palindrome ; summation of all palindrome numbers present in array ; Driver Code"
How can the above be solved in Java?

class GFG { static int reverse ( int n ) { int d = 0 , s = 0 ; while ( n > 0 ) { d = n % 10 ; s = s * 10 + d ; n = n / 10 ; } return s ; } static boolean isPalin ( int n ) { return n == reverse ( n ) ; } static int sumOfArray ( int [ ] arr , int n ) { int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] > 10 ) && isPalin ( arr [ i ] ) ) { s += arr [ i ] ; } } return s ; } public static void main ( String [ ] args ) { int n = 6 ; int [ ] arr = { 12 , 313 , 11 , 44 , 9 , 1 } ; System . out . println ( sumOfArray ( arr , n ) ) ; } }


"Sum of all palindromic numbers lying in the range [ L , R ] for Q queries | Java program to find the sum of all palindrome numbers in the given range ; pref [ ] array to precompute the sum of all palindromic number ; Function that return number num if num is palindromic else return 0 ; Convert num to String ; Function to precompute the sum of all palindrome numbers upto 100000 ; checkPalindrome ( ) return the number i if i is palindromic else return 0 ; Function to print the sum for each query ; Function to print sum of all palindromic numbers between [ L , R ] ; Function that pre computes the sum of all palindromic numbers ; Iterate over all Queries to print the sum ; Driver code ; Queries ; Function that print the the sum of all palindromic number in Range [ L , R ]"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int [ ] pref = new int [ 100001 ] ; static int checkPalindrome ( int num ) { String str = String . valueOf ( num ) ; int l = 0 , r = str . length ( ) - 1 ; while ( l < r ) { if ( str . charAt ( l ) != str . charAt ( r ) ) { return 0 ; } l ++ ; r -- ; } return num ; } static void preCompute ( ) { for ( int i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + checkPalindrome ( i ) ; } } static void printSum ( int L , int R ) { System . out . print ( pref [ R ] - pref [ L - 1 ] + "
"); } static void printSumPalindromic ( int arr [ ] [ ] , int Q ) { preCompute ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } public static void main ( String [ ] args ) { int Q = 2 ; int arr [ ] [ ] = { { 10 , 13 } , { 12 , 21 } } ; printSumPalindromic ( arr , Q ) ; } }


"Sum of all perfect numbers present in an array | Java implementation of the above approach ; Function to return the sum of all the proper factors of n ; f is the factor of n ; Function to return the required sum ; To store the sum ; If current element is non - zero and equal to the sum of proper factors of itself ; Driver code"
How can the above be solved in Java?

class GFG { static int sumOfFactors ( int n ) { int sum = 0 ; for ( int f = 1 ; f <= n / 2 ; f ++ ) { if ( n % f == 0 ) { sum += f ; } } return sum ; } static int getSum ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 && arr [ i ] == sumOfFactors ( arr [ i ] ) ) { sum += arr [ i ] ; } } return sum ; } public static void main ( String [ ] args ) { int [ ] arr = { 17 , 6 , 10 , 6 , 4 } ; int n = arr . length ; System . out . print ( getSum ( arr , n ) ) ; } }


"Sum of all perfect square divisors of numbers from 1 to N | Java program to find the sum of all perfect square divisors of numbers from 1 to N ; Function for finding inverse of a number iteratively Here we will find the inverse of 6 , since it appears as denominator in the formula of sum of squares from 1 to N ; Store the value of the inverse of 6 once as we don 't need to call the function again and again ; Formula for finding the sum of first n squares ; No perfect square exists which is less than 4 ; Starting from 2 , present value of start is denoted here as curStart ; Finding end of the segment for which the contribution will be same ; Using the above mentioned formula to find ans % MOD ; Now for mthe next iteration start will become end + 1 ; Finally returning the answer ; Driver Code ; Here we are adding x because we have not counted 1 as perfect squares so if u want to add it you can just add that number to the ans"
How can the above be solved in Java?

 import java . util . * ; class GFG { static final int MOD = 7 ; static int inv ( int a ) { int o = 1 ; for ( int p = MOD - 2 ; p > 0 ; p >>= 1 ) { if ( ( p & 1 ) == 1 ) o = ( o * a ) % MOD ; a = ( a * a ) % MOD ; } return o ; } static int inv6 = inv ( 6 ) ; static int sumOfSquares ( int n ) { n %= MOD ; return ( ( ( n * ( n + 1 ) ) % MOD * ( 2 * n + 1 ) ) % MOD * inv6 ) % MOD ; } static int sums ( int n ) { if ( n < 4 ) return 0 ; int curStart = 2 , ans = 0 ; int sqrtN = ( int ) Math . sqrt ( n ) ; while ( curStart <= n / curStart ) { int V = n / ( curStart * curStart ) ; int end = ( int ) Math . sqrt ( n / V ) ; ans += ( n / ( curStart * curStart ) % MOD * ( sumOfSquares ( end ) + MOD - sumOfSquares ( curStart - 1 ) ) ) % MOD ; if ( ans >= MOD ) ans -= MOD ; curStart = end + 1 ; } return ans ; } public static void main ( String [ ] args ) { int input [ ] = { 5 } ; for ( int x : input ) { System . out . print ( " sum ▁ of ▁ all ▁ perfect ▁ " + " square ▁ divisors ▁ from ▁ " + "1 ▁ to ▁ " + x + " ▁ is : ▁ " ) ; System . out . print ( x + sums ( x ) + "
"); } } }


"Sum of all possible strings obtained by removal of non | Java program for the above approach ; Function to convert a character to its equivalent digit ; Function to precompute powers of 10 ; Function to precompute prefix sum of numerical Strings ; Function to return the i - th term of Triangular Number ; Function to return the sum of all resulting Strings ; Precompute powers of 10 ; Precompute prefix sum ; Initialize result ; Apply the above general formula for every i ; Return the answer ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int N = 10 ; static int [ ] pref = new int [ N ] ; static int [ ] power = new int [ N ] ; static int toDigit ( char ch ) { return ( ch - '0' ) ; } static void powerOf10 ( ) { power [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) power [ i ] = power [ i - 1 ] * 10 ; } static void precomputePrefix ( char [ ] str , int n ) { pref [ 0 ] = str [ 0 ] - '0' ; for ( int i = 1 ; i < n ; i ++ ) pref [ i ] = pref [ i - 1 ] + toDigit ( str [ i ] ) ; } static int triangularNumber ( int i ) { int res = i * ( i + 1 ) / 2 ; return res ; } static int sumOfSubStrings ( String str ) { int n = str . length ( ) ; powerOf10 ( ) ; precomputePrefix ( str . toCharArray ( ) , n ) ; int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { ans += ( pref [ n - i - 2 ] * ( i + 1 ) + toDigit ( str . charAt ( n - i - 1 ) ) * triangularNumber ( n - i - 1 ) ) * power [ i ] ; } return ans ; } public static void main ( String [ ] args ) { String str = "1234" ; System . out . print ( sumOfSubStrings ( str ) ) ; } }


"Sum of all possible triplet products from given ranges | Java implementation to implement the above approach ; Function to find the value of power ( X , N ) % M ; Stores the value of ( X ^ N ) % M ; Calculate the value of power ( x , N ) % M ; If N is odd ; Update res ; Update x ; Update N ; Function to find modulo multiplicative inverse of X under modulo M ; Function to find the sum of all possible triplet products ( i * j * k ) ; Stores modulo multiplicative inverse of 8 ; Stores the sum of all possible values of ( i * j * k ) ; Update res ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int M = 1000000007 ; static long power ( long x , long N ) { long res = 1 ; while ( N > 0 ) { if ( N % 2 == 1 ) { res = ( res * x ) % M ; } x = ( x * x ) % M ; N = N >> 1 ; } return res ; } static long modinv ( long X ) { return power ( X , M - 2 ) ; } static long findTripleSum ( long A , long B , long C ) { long MMI = modinv ( 8 ) ; long res = 0 ; res = ( ( ( ( A % M * ( A + 1 ) % M ) % M * ( B % M * ( B + 1 ) % M ) % M ) % M * ( C % M * ( C + 1 ) % M ) % M ) % M * MMI ) % M ; return res ; } public static void main ( String [ ] args ) { long A = 10 ; long B = 100 ; long C = 1000 ; System . out . print ( findTripleSum ( A , B , C ) ) ; } }


"Sum of all possible triplet products from given ranges | Java program to implement the above approach ; Function to find the sum of all possible triplet products ( i * j * k ) ; Stores sum required sum ; Iterate over all possible values of i ; Iterate over all possible values of j ; Iterate over all possible values of k ; Stores the product of ( i * j * k ) ; Update sum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int M = 1000000007 ; static int findTripleSum ( int A , int B , int C ) { int sum = 0 ; for ( int i = 1 ; i <= A ; i ++ ) { for ( int j = 1 ; j <= B ; j ++ ) { for ( int k = 1 ; k <= C ; k ++ ) { int prod = ( ( ( i % M ) * ( j % M ) ) % M * ( k % M ) ) % M ; sum = ( sum + prod ) % M ; } } } return sum ; } public static void main ( String args [ ] ) { int A = 10 ; int B = 100 ; int C = 1000 ; System . out . println ( findTripleSum ( A , B , C ) ) ; } }


"Sum of all proper divisors from 1 to N | Java implementation to find sum of all proper divisor of number up to N ; Utility function to find sum of all proper divisor of number up to N ; Loop to iterate over all the numbers from 1 to N ; Find all divisors of i and add them ; Subtracting ' i ' so that the number itself is not included ; Driver Code"
How can the above be solved in Java?

class GFG { static int properDivisorSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; ++ i ) { for ( int j = 1 ; j * j <= i ; ++ j ) { if ( i % j == 0 ) { if ( i / j == j ) sum += j ; else sum += j + i / j ; } } sum = sum - i ; } return sum ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( properDivisorSum ( n ) ) ; n = 5 ; System . out . println ( properDivisorSum ( n ) ) ; } }


"Sum of all proper divisors from 1 to N | Utility function to find sum of all proper divisor of number up to N ; Loop to find the proper divisor of every number from 1 to N ; Driver Code"
How can the above be solved in Java?

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


"Sum of all proper divisors of natural numbers in an array | Java program to find sum of proper divisors for every element in an array . ; To store prime factors and their powers ; Fills factors such that factors [ i ] is a vector of pairs containing prime factors ( of i ) and their powers . Also sets values in isPrime [ ] ; To check if a number is prime ; If i is prime , then update its powers in all multiples of it . ; Returns sum of proper divisors of num using factors [ ] ; Applying above discussed formula for every array element ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int MAX = 100001 ; static class pair { int F , S ; public pair ( int f , int s ) { F = f ; S = s ; } } static Vector < pair > [ ] factors = new Vector [ MAX ] ; static void sieveOfEratothenese ( ) { boolean [ ] isPrime = new boolean [ MAX ] ; Arrays . fill ( isPrime , true ) ; isPrime [ 0 ] = isPrime [ 1 ] = false ; for ( int i = 2 ; i < MAX ; i ++ ) { if ( isPrime [ i ] ) { for ( int j = i ; j < MAX ; j += i ) { int k , l ; isPrime [ j ] = false ; for ( k = j , l = 0 ; k % i == 0 ; l ++ , k /= i ) ; factors [ j ] . add ( new pair ( i , l ) ) ; } } } } static int sumOfProperDivisors ( int num ) { int mul = 1 ; for ( int i = 0 ; i < factors [ num ] . size ( ) ; i ++ ) mul *= ( ( Math . pow ( factors [ num ] . get ( i ) . F , factors [ num ] . get ( i ) . S + 1 ) - 1 ) / ( factors [ num ] . get ( i ) . F - 1 ) ) ; return mul - num ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < MAX ; i ++ ) factors [ i ] = new Vector < pair > ( ) ; sieveOfEratothenese ( ) ; int arr [ ] = { 8 , 13 , 24 , 36 , 59 , 75 , 91 } ; for ( int i = 0 ; i < arr . length ; i ++ ) System . out . print ( sumOfProperDivisors ( arr [ i ] ) + " ▁ " ) ; System . out . println ( ) ; } }


"Sum of all second largest divisors after splitting a number into one or more parts | Java program to Sum of all second largest divisors after splitting a number into one or more parts ; Function to find a number is prime or not ; If there is any divisor ; Function to find the sum of all second largest divisor after splitting a number into one or more parts ; If number is prime ; If n is even ; If the number is odd ; If N - 2 is prime ; There exists 3 primes x1 , x2 , x3 such that x1 + x2 + x3 = n ; Driver code ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean prime ( int n ) { if ( n == 1 ) return false ; for ( int i = 2 ; i * i <= n ; ++ i ) if ( n % i == 0 ) return false ; return true ; } static int Min_Sum ( int n ) { if ( prime ( n ) ) return 1 ; if ( n % 2 == 0 ) return 2 ; else { if ( prime ( n - 2 ) ) return 2 ; else return 3 ; } } public static void main ( String [ ] args ) { int n = 27 ; System . out . println ( Min_Sum ( n ) ) ; } }


"Sum of all subarrays of size K | Java implementation to find the sum of all subarrays of size K ; Function to find the sum of all subarrays of size K ; Initialize sum = 0 ; Consider first subarray of size k Store the sum of elements ; Print the current sum ; Consider every subarray of size k Remove first element and add current element to the window ; Add the element which enters into the window and subtract the element which pops out from the window of the size K ; Print the sum of subarray ; Drivers Code ; Function Call"
How can the above be solved in Java?

class GFG { static void calcSum ( int arr [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < k ; i ++ ) sum += arr [ i ] ; System . out . print ( sum + " ▁ " ) ; for ( int i = k ; i < n ; i ++ ) { sum = ( sum - arr [ i - k ] ) + arr [ i ] ; System . out . print ( sum + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = arr . length ; int k = 3 ; calcSum ( arr , n , k ) ; } }


"Sum of all subarrays of size K | Java implementation to find the sum of all subarrays of size K ; Function to find the sum of all subarrays of size K ; Loop to consider every subarray of size K ; Initialize sum = 0 ; Calculate sum of all elements of current subarray ; Print sum of each subarray ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static void calcSum ( int arr [ ] , int n , int k ) { for ( int i = 0 ; i <= n - k ; i ++ ) { int sum = 0 ; for ( int j = i ; j < k + i ; j ++ ) sum += arr [ j ] ; System . out . print ( sum + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = arr . length ; int k = 3 ; calcSum ( arr , n , k ) ; } }


"Sum of all subsequences of length K | Java implementation to find sum of all subsequences of length K ; Function to find nCr ; Function that returns factorial of n ; Function for finding sum of all K length subsequences ; Calculate the sum of array ; Calculate nCk ; Return the final result ; Driver code"
How can the above be solved in Java?

class GFG { static int nCr ( int n , int r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } static int fact ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } static int sumSubsequences ( int arr [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } int kLengthSubSequence ; kLengthSubSequence = nCr ( n , k ) ; int ans = sum * ( ( k * kLengthSubSequence ) / n ) ; return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 8 , 9 , 2 } ; int K = 2 ; int n = arr . length ; System . out . print ( sumSubsequences ( arr , n , K ) ) ; } }


"Sum of all subsets of a given size ( = K ) | package whatever do not write package name here ; Function to find the sum of all sub - sets of size K ; Frequency of each array element in summation equation . ; calculate factorial of n - 1 ; calculate factorial of k - 1 ; calculate factorial of n - k ; Calculate sum of array . ; Sum of all subsets of size k . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findSumOfAllSubsets ( int [ ] arr , int n , int k ) { int factorial_N = 1 , factorial_d = 1 , factorial_D = 1 ; for ( int i = 1 ; i <= n - 1 ; i ++ ) factorial_N *= i ; for ( int i = 1 ; i <= k - 1 ; i ++ ) factorial_d *= i ; for ( int i = 1 ; i <= n - k ; i ++ ) factorial_D *= i ; int freq = factorial_N / ( factorial_d * factorial_D ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; sum = sum * freq ; System . out . println ( " Sum ▁ of ▁ all ▁ subsets ▁ of ▁ size ▁ = ▁ " + k + " ▁ is ▁ = > ▁ " + sum ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 5 } ; int n = 4 , k = 2 ; findSumOfAllSubsets ( arr , n , k ) ; } }


"Sum of all subsets of a set formed by first n natural numbers | Java program to find sum of all subsets of a set . ; sum of subsets is ( n * ( n + 1 ) / 2 ) * pow ( 2 , n - 1 ) ; Driver code"
How can the above be solved in Java?

class GFG { static long findSumSubsets ( int n ) { return ( n * ( n + 1 ) / 2 ) * ( 1 << ( n - 1 ) ) ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . print ( findSumSubsets ( n ) ) ; } }


"Sum of all subsets whose sum is a Perfect Number from a given array | Java program for the above approach ; Function to check is a given number is a perfect number or not ; Stores sum of divisors ; Add all divisors of x to sum_div ; If the sum of divisors is equal to the given number , return true ; Otherwise , return false ; Function to find the sum of all the subsets from an array whose sum is a perfect number ; Stores the total number of subsets , i . e . 2 ^ n ; Consider all numbers from 0 to 2 ^ n - 1 ; Consider array elements from positions of set bits in the binary representation of n ; If sum of chosen elements is a perfect number ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int isPerfect ( int x ) { int sum_div = 1 ; for ( int i = 2 ; i <= x / 2 ; ++ i ) { if ( x % i == 0 ) { sum_div += i ; } } if ( sum_div == x ) { return 1 ; } else return 0 ; } static void subsetSum ( int arr [ ] , int n ) { long total = 1 << n ; for ( long i = 0 ; i < total ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j < n ; j ++ ) if ( ( i & ( 1 << j ) ) != 0 ) sum += arr [ j ] ; if ( isPerfect ( sum ) != 0 ) { System . out . print ( sum + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 4 , 6 } ; int N = arr . length ; subsetSum ( arr , N ) ; } }


"Sum of all subsets whose sum is a Perfect Number from a given array | Java program for the above approach ; Function to check is a given number is a perfect number or not ; Stores the sum of its divisors ; Add all divisors of x to sum_div ; If the sum of divisors is equal to the given number , return true ; Otherwise , return false ; Function to find sum of all subsets from an array whose sum is a perfect number ; Print the current subset sum if it is a perfect number ; Check if sum is a perfect number or not ; Calculate sum of the subset including arr [ l ] ; Calculate sum of the subset excluding arr [ l ] ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int isPerfect ( int x ) { int sum_div = 1 ; for ( int i = 2 ; i <= x / 2 ; ++ i ) { if ( x % i == 0 ) { sum_div += i ; } } if ( sum_div == x ) { return 1 ; } else return 0 ; } static void subsetSum ( int [ ] arr , int l , int r , int sum ) { if ( l > r ) { if ( isPerfect ( sum ) != 0 ) { System . out . print ( sum + " ▁ " ) ; } return ; } subsetSum ( arr , l + 1 , r , sum + arr [ l ] ) ; subsetSum ( arr , l + 1 , r , sum ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 4 , 6 } ; int N = arr . length ; subsetSum ( arr , 0 , N - 1 , 0 ) ; } }


"Sum of all substrings of a string representing a number | Set 1 | Java program to print sum of all subString of a number represented as a String ; Utility method to convert character digit to integer digit ; Returns sum of all subString of num ; Storing prev value ; SubStrings sum upto current index loop over all digits of String ; Update each sumofdigit from previous value ; Add current value to the result ; Update previous ; Driver code to test above methods"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int toDigit ( char ch ) { return ( ch - '0' ) ; } static int sumOfSubStrings ( String num ) { int n = num . length ( ) ; int prev = toDigit ( num . charAt ( 0 ) ) ; int res = prev ; int current = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int numi = toDigit ( num . charAt ( i ) ) ; current = ( i + 1 ) * numi + 10 * prev ; res += current ; prev = current ; } return res ; } public static void main ( String [ ] args ) { String num = "1234" ; System . out . print ( sumOfSubStrings ( num ) + "
"); } }


"Sum of all substrings of a string representing a number | Set 1 | Java program to print sum of all substring of a number represented as a string ; Returns sum of all substring of num ; allocate memory equal to length of string ; initialize first value with first digit ; loop over all digits of string ; update each sumofdigit from previous value ; add current value to the result ; Driver code to test above methods"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { public static int sumOfSubstrings ( String num ) { int n = num . length ( ) ; int sumofdigit [ ] = new int [ n ] ; sumofdigit [ 0 ] = num . charAt ( 0 ) - '0' ; int res = sumofdigit [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { int numi = num . charAt ( i ) - '0' ; sumofdigit [ i ] = ( i + 1 ) * numi + 10 * sumofdigit [ i - 1 ] ; res += sumofdigit [ i ] ; } return res ; } public static void main ( String [ ] args ) { String num = "1234" ; System . out . println ( sumOfSubstrings ( num ) ) ; } }


"Sum of all substrings of a string representing a number | Set 2 ( Constant Extra Space ) | Java program to print sum of all substring of a number represented as a string ; Returns sum of all substring of num ; Initialize result ; Here traversing the array in reverse order . Initializing loop from last element . mf is multiplying factor . ; Each time sum is added to its previous sum . Multiplying the three factors as explained above . s [ i ] - '0' is done to convert char to int . ; Making new multiplying factor as explained above . ; Driver code to test above methods"
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { public static long sumOfSubstrings ( String num ) { long sum = 0 ; long mf = 1 ; for ( int i = num . length ( ) - 1 ; i >= 0 ; i -- ) { sum += ( num . charAt ( i ) - '0' ) * ( i + 1 ) * mf ; mf = mf * 10 + 1 ; } return sum ; } public static void main ( String [ ] args ) { String num = "6759" ; System . out . println ( sumOfSubstrings ( num ) ) ; } }


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

import java . util . * ; class solution { static long sumAP ( long n , long d ) { n /= d ; return ( n ) * ( 1 + n ) * d / 2 ; } static long sumMultiples ( long n ) { n -- ; return sumAP ( n , 3 ) + sumAP ( n , 7 ) - sumAP ( n , 21 ) ; } public static void main ( String args [ ] ) { long n = 24 ; System . out . println ( sumMultiples ( n ) ) ; } }


"Sum of all the numbers in the Nth parenthesis | Java implementation of the approach ; Function to return the sum of the numbers in the nth parenthesis ; Driver code"
How can the above be solved in Java?

class GFG { static int findSum ( int n ) { return ( int ) Math . pow ( n , 3 ) ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( findSum ( n ) ) ; } }


"Sum of all the numbers in the Nth row of the given triangle | Java implementation of the approach ; Function to return the sum of the nth row elements of the given triangle ; Driver code"
How can the above be solved in Java?

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


"Sum of all the numbers present at given level in Modified Pascal ’ s triangle | Java program to calculate sum of all the numbers present at given level in an Modified Pascal 's triangle ; Function to calculate sum ; Driver Code"
How can the above be solved in Java?

class GFG { static void ans ( int n ) { if ( n == 1 ) System . out . println ( "1" ) ; else System . out . println ( "0" ) ; } public static void main ( String [ ] args ) { int n = 2 ; ans ( n ) ; } }


"Sum of all the numbers present at given level in Pascal 's triangle | Java implementation of the approach ; Function to find sum of numbers at Lth level in Pascals Triangle ; Driver Code"
How can the above be solved in Java?

class GFG { static int sum ( int h ) { return ( int ) Math . pow ( 2 , h - 1 ) ; } public static void main ( String [ ] args ) { int L = 3 ; System . out . println ( sum ( L ) ) ; } }


"Sum of all the numbers that are formed from root to leaf paths | Java program to find sum of all numbers that are formed from root to leaf paths A binary tree node ; Returns sum of all root to leaf paths . The first parameter is root of current subtree , the second parameter is value of the number formed by nodes from root to this node ; Base case ; Update val ; if current node is leaf , return the current value of val ; recur sum of values for left and right subtree ; A wrapper function over treePathsSumUtil ( ) ; Pass the initial value as 0 as there is nothing above root ; Driver program to test above functions"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; int treePathsSumUtil ( Node node , int val ) { if ( node == null ) return 0 ; val = ( val * 10 + node . data ) ; if ( node . left == null && node . right == null ) return val ; return treePathsSumUtil ( node . left , val ) + treePathsSumUtil ( node . right , val ) ; } int treePathsSum ( Node node ) { return treePathsSumUtil ( node , 0 ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 6 ) ; tree . root . left = new Node ( 3 ) ; tree . root . right = new Node ( 5 ) ; tree . root . right . right = new Node ( 4 ) ; tree . root . left . left = new Node ( 2 ) ; tree . root . left . right = new Node ( 5 ) ; tree . root . left . right . right = new Node ( 4 ) ; tree . root . left . right . left = new Node ( 7 ) ; System . out . print ( " Sum ▁ of ▁ all ▁ paths ▁ is ▁ " + tree . treePathsSum ( tree . root ) ) ; } }


"Sum of all the parent nodes having child node x | Java implementation to find the sum of all the parent nodes having child node x ; sum ; Node of a binary tree ; function to get a new node ; allocate memory for the node ; put in the data ; function to find the sum of all the parent nodes having child node x ; if root == NULL ; if left or right child of root is ' x ' , then add the root ' s ▁ data ▁ to ▁ ' sum '  ; recursively find the required parent nodes in the left and right subtree ; utility function to find the sum of all the parent nodes having child node x ; required sum of parent nodes ; Driver Code ; binary tree formation 4 ; / \ ; 2 5 ; / \ / \ ; 7 2 2 3"
How can the above be solved in Java?

class GFG { static int sum = 0 ; 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 void sumOfParentOfX ( Node root , int x ) { if ( root == null ) return ; if ( ( root . left != null && root . left . data == x ) || ( root . right != null && root . right . data == x ) ) sum += root . data ; sumOfParentOfX ( root . left , x ) ; sumOfParentOfX ( root . right , x ) ; } static int sumOfParentOfXUtil ( Node root , int x ) { sum = 0 ; sumOfParentOfX ( root , x ) ; return sum ; } public static void main ( String args [ ] ) { Node root = getNode ( 4 ) ; root . left = getNode ( 2 ) ; root . right = getNode ( 5 ) ; root . left . left = getNode ( 7 ) ; root . left . right = getNode ( 2 ) ; root . right . left = getNode ( 2 ) ; root . right . right = getNode ( 3 ) ; int x = 2 ; System . out . println ( " Sum ▁ = ▁ " + sumOfParentOfXUtil ( root , x ) ) ; } }


"Sum of all the prime divisors of a number | Set 2 | Java program for the above approach ; Function to find sum of prime divisors of the given number N ; Add the number 2 if it divides N ; Traverse the loop from [ 3 , sqrt ( N ) ] ; If i divides N , add i and divide N ; This condition is to handle the case when N is a prime number greater than 2 ; Driver code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int SumOfPrimeDivisors ( int n ) { int sum = 0 ; if ( n % 2 == 0 ) { sum = sum + 2 ; } while ( n % 2 == 0 ) { n = n / 2 ; } for ( int i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { sum = sum + i ; } while ( n % i == 0 ) { n = n / i ; } } if ( n > 2 ) { sum = sum + n ; } return sum ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( SumOfPrimeDivisors ( n ) ) ; } }


"Sum of all the prime numbers in a given range | Java Program to compute sum of prime number in a given range ; Suppose the constraint is N <= 1000 ; Declare an array for dynamic approach ; Method to compute the array ; Declare an extra array as arr ; Iterate the loop till sqrt ( n ) Time Complexity is O ( log ( n ) X sqrt ( n ) ) ; if ith element of arr is 0 i . e . marked as prime ; mark all of it 's multiples till N as non-prime  by setting the locations to 1 ; Update the array ' dp ' with the running sum of prime numbers within the range [ 1 , N ] Time Complexity is O ( n ) ; Here , dp [ i ] is the sum of all the prime numbers within the range [ 1 , i ] ; Driver code ; Compute dp"
How can the above be solved in Java?

public class GFG { static int N = 1000 ; static long dp [ ] = new long [ N + 1 ] ; static void sieve ( ) { int arr [ ] = new int [ N + 1 ] ; arr [ 0 ] = 1 ; arr [ 1 ] = 1 ; for ( int i = 2 ; i <= Math . sqrt ( N ) ; i ++ ) if ( arr [ i ] == 0 ) for ( int j = i * i ; j <= N ; j += i ) arr [ j ] = 1 ; long runningPrimeSum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( arr [ i ] == 0 ) runningPrimeSum += i ; dp [ i ] = runningPrimeSum ; } } public static void main ( String [ ] args ) { int l = 4 , r = 13 ; sieve ( ) ; System . out . println ( dp [ r ] - dp [ l - 1 ] ) ; } }


"Sum of all the prime numbers with the maximum position of set bit â ‰¤ D | Java implementation of the approach ; Function for Sieve of Eratosthenes ; Function to return the sum of the required prime numbers ; Maximum number of the required range ; Sieve of Eratosthenes ; To store the required sum ; If current element is prime ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void sieve ( boolean prime [ ] , int n ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } } static int sumPrime ( int d ) { int maxVal = ( int ) ( Math . pow ( 2 , d ) - 1 ) ; boolean [ ] prime = new boolean [ maxVal + 1 ] ; Arrays . fill ( prime , true ) ; sieve ( prime , maxVal ) ; int sum = 0 ; for ( int i = 2 ; i <= maxVal ; i ++ ) { if ( prime [ i ] ) { sum += i ; } } return sum ; } public static void main ( String [ ] args ) { int d = 8 ; System . out . println ( sumPrime ( d ) ) ; } }


"Sum of alternating sign Squares of first N natural numbers | Java program to find Sum of alternating sign Squares of first N natural numbers ; Function to calculate the alternating sign sum ; Variable to store the absolute sum ; Variable to store the sign ; Variable to store the resultant sum ; Driver code"
How can the above be solved in Java?

class GFG { static int summation ( int n ) { int abs_sum = n * ( n + 1 ) / 2 ; int sign = n + 1 % 2 == 0 ? 1 : - 1 ; int result_sum = sign * abs_sum ; return result_sum ; } public static void main ( String [ ] args ) { int N = 2 ; System . out . println ( summation ( N ) ) ; } }


"Sum of alternating sign Squares of first N natural numbers | Java program to find Sum of alternating sign Squares of first N natural numbers ; Function to calculate the alternating sign sum ; Variable to store the sum ; Loop to iterate each number from 1 to N ; The alternating sign is put by checking if the number is even or odd ; Add the square with the sign ; Add the square with the sign ; Driver code"
How can the above be solved in Java?

class GFG { static int summation ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i % 2 == 1 ) sum += ( i * i ) ; else sum -= ( i * i ) ; } return sum ; } public static void main ( String [ ] args ) { int N = 2 ; System . out . println ( summation ( N ) ) ; } }


"Sum of alternating sign cubes of first N Natural numbers | Java implementation to compute the sum of cubes with alternating sign ; Function to compute sum of the cubes with alternating sign ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int summation ( int N ) { int co = ( N + 1 ) / 2 ; int ce = ( N ) / 2 ; int se = 2 * ( ( ce * ( ce + 1 ) ) * ( ce * ( ce + 1 ) ) ) ; int so = ( co * co ) * ( 2 * ( ( co * co ) ) - 1 ) ; return so - se ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( summation ( n ) ) ; } }


"Sum of an Infinite Geometric Progression ( GP ) | Java program for the above approach ; Function to calculate the sum of an infinite Geometric Progression ; Case for Infinite Sum ; Store the sum of GP Series ; Print the value of sum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findSumOfGP ( double a , double r ) { if ( Math . abs ( r ) >= 1 ) { System . out . print ( " Infinite " ) ; return ; } double sum = a / ( 1 - r ) ; System . out . print ( sum ) ; } public static void main ( String [ ] args ) { double A = 1 , R = 0.5 ; findSumOfGP ( A , R ) ; } }


"Sum of an array of large numbers | Java program for the above approach ; Function to print the result of the summation of numbers having K - digit ; Reverse the array to obtain the result ; Print every digit of the answer ; Function to calculate the total sum ; Stores the array of large numbers in integer format ; Convert each element from character to integer ; Stores the carry ; Stores the result of summation ; Initialize the sum ; Calculate sum ; Update the sum by adding existing carry ; Store the number of digits ; Increase count of digits ; If the number exceeds 9 , Store the unit digit in carry ; Store the rest of the sum ; Append digit by digit into result array ; Append result until carry is 0 ; Print the result ; Driver Code ; Given N array of large numbers"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static void printResult ( ArrayList < Integer > result ) { Collections . reverse ( result ) ; int i = 0 ; while ( i < result . size ( ) ) { System . out . print ( result . get ( i ) ) ; i ++ ; } } static void sumOfLargeNumbers ( String v [ ] , int k , int N ) { ArrayList < ArrayList < Integer > > x = new ArrayList < > ( 1000 ) ; for ( int i = 0 ; i < k ; i ++ ) x . add ( new ArrayList < Integer > ( ) ) ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { x . get ( i ) . add ( v [ i ] . charAt ( j ) - '0' ) ; } } int carry = 0 ; ArrayList < Integer > result = new ArrayList < > ( ) ; for ( int i = N - 1 ; i >= 0 ; i -- ) { int sum = 0 ; for ( int j = 0 ; j < k ; j ++ ) sum += x . get ( j ) . get ( i ) ; sum += carry ; int temp = sum ; int count = 0 ; while ( temp > 9 ) { temp = temp % 10 ; count ++ ; } long l = ( long ) Math . pow ( 10 , count ) ; if ( l != 1 ) carry = ( int ) ( sum / l ) ; sum = sum % 10 ; result . add ( sum ) ; } while ( carry != 0 ) { int a = carry % 10 ; result . add ( a ) ; carry = carry / 10 ; } printResult ( result ) ; } public static void main ( String [ ] args ) { int K = 10 ; int N = 5 ; String arr [ ] = { "1111111111" , "1111111111" , "1111111111" , "1111111111" , "1111111111" } ; sumOfLargeNumbers ( arr , N , K ) ; } }


"Sum of array elements possible by appending arr [ i ] / K to the end of the array K times for array elements divisible by K | Java program for the above approach ; Function to calculate sum of array elements after adding arr [ i ] / K to the end of the array if arr [ i ] is divisible by K ; Stores the sum of the array ; Stores the array elements ; Traverse the array ; Stores if the operation should be formed or not ; Traverse the vector V ; If flag is false and if v [ i ] is divisible by K ; Otherwise , set flag as true ; Increment the sum by v [ i % N ] ; Return the resultant sum ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int sum ( int arr [ ] , int N , int K ) { int sum = 0 ; ArrayList < Integer > v = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { v . add ( arr [ i ] ) ; } boolean flag = false ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( ! flag && v . get ( i ) % K == 0 ) v . add ( v . get ( i ) / K ) ; else { flag = true ; } sum = sum + v . get ( i % N ) ; } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 6 , 8 , 2 } ; int K = 2 ; int N = arr . length ; System . out . println ( sum ( arr , N , K ) ) ; } }


"Sum of array elements possible by appending arr [ i ] / K to the end of the array K times for array elements divisible by K | Java program for the above approach ; Function to calculate sum of array elements after adding arr [ i ] / K to the end of the array if arr [ i ] is divisible by K ; Stores the sum of the array ; Traverse the array arr [ ] ; Traverse the vector ; If v [ i ] is divisible by K ; Iterate over the range [ 0 , K ] ; Update v ; Otherwise ; Traverse the vector v ; Return the sum of the updated array ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int sum ( int arr [ ] , int N , int K ) { int sum = 0 ; ArrayList < Integer > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { v . add ( arr [ i ] ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( v . get ( i ) % K == 0 ) { int x = v . get ( i ) / K ; for ( int j = 0 ; j < K ; j ++ ) { v . add ( x ) ; } } else break ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) sum = sum + v . get ( i ) ; return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 6 , 8 , 2 } ; int K = 2 ; int N = arr . length ; System . out . println ( sum ( arr , N , K ) ) ; } }


"Sum of array elements that is first continuously increasing then decreasing | JAVA Code for Sum of array elements that is first continuously increasing then decreasing ; Driver program to test above function"
How can the above be solved in Java?

class GFG { public static int arraySum ( int arr [ ] , int n ) { int x = ( n + 1 ) / 2 ; return ( arr [ 0 ] - 1 ) * n + x * x ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 11 , 12 , 13 , 12 , 11 , 10 } ; int n = arr . length ; System . out . print ( arraySum ( arr , n ) ) ; } }


"Sum of array elements which are multiples of a given number | Java program for the above approach ; Function to find the sum of array elements which are multiples of N ; Stores the sum ; Traverse the given array ; If current element is a multiple of N ; Print total sum ; Driver Code ; Given arr [ ]"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void mulsum ( int arr [ ] , int n , int N ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % N == 0 ) { sum = sum + arr [ i ] ; } } System . out . println ( sum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 5 , 6 } ; int n = arr . length ; int N = 3 ; mulsum ( arr , n , N ) ; } }


"Sum of array elements which are prime factors of a given number | Java program for the above approach ; Function to check if a number is prime or not ; Corner cases ; Check if n is a multiple of 2 or 3 ; Above condition allows to check only for every 6 th number , starting from 5 ; If n is a multiple of i and i + 2 ; Function to find the sum of array elements which are prime factors of K ; Stores the required sum ; Traverse the given array ; If current element is a prime factor of k , add it to the sum ; Print the result ; Driver code ; Given arr [ ] ; Store the size of the array"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } static void primeFactorSum ( int arr [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( k % arr [ i ] == 0 && isPrime ( arr [ i ] ) ) { sum = sum + arr [ i ] ; } } System . out . println ( sum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 5 , 6 , 7 , 15 } ; int N = arr . length ; int K = 35 ; primeFactorSum ( arr , N , K ) ; } }


"Sum of array elements whose count of set bits are unique | Java program for the approach ; Function to count the number of set bits in an integer N ; Stores the count of set bits ; Iterate until N is non - zero ; Stores the resultant count ; Function to calculate sum of all array elements whose count of set bits are unique ; Stores frequency of all possible count of set bits ; Stores the sum of array elements ; Traverse the array ; Count the number of set bits ; Traverse the array And Update the value of ans ; If frequency is 1 ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int setBitCount ( int n ) { int ans = 0 ; while ( n != 0 ) { ans += n & 1 ; n >>= 1 ; } return ans ; } static void getSum ( int [ ] arr , int n ) { Map < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int key = setBitCount ( arr [ i ] ) ; if ( mp . containsKey ( key ) ) mp . put ( key , mp . get ( key ) + 1 ) ; else mp . put ( key , 1 ) ; } for ( int i = 0 ; i < n ; i ++ ) { int key = setBitCount ( arr [ i ] ) ; if ( mp . containsKey ( key ) && mp . get ( key ) == 1 ) ans += arr [ i ] ; } System . out . print ( ans ) ; } public static void main ( String args [ ] ) { int [ ] arr = { 8 , 3 , 7 , 5 , 3 } ; int n = arr . length ; getSum ( arr , n ) ; } }


"Sum of average of all subsets | java program to get sum of average of all subsets ; Returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; method returns sum of average of all subsets ; Initialize result ; Find sum of elements ; looping once for all subset of same size ; each element occurs nCr ( N - 1 , n - 1 ) times while considering subset of size n ; Driver code to test above methods"
How can the above be solved in Java?

import java . io . * ; class GFG { static int nCr ( int n , int k ) { int C [ ] [ ] = new int [ n + 1 ] [ k + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= Math . min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } static double resultOfAllSubsets ( int arr [ ] , int N ) { double result = 0.0 ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; for ( int n = 1 ; n <= N ; n ++ ) result += ( double ) ( sum * ( nCr ( N - 1 , n - 1 ) ) ) / n ; return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 5 , 7 } ; int N = arr . length ; System . out . println ( resultOfAllSubsets ( arr , N ) ) ; } }


"Sum of bit differences among all pairs | Java program to compute sum of pairwise bit differences ; traverse over all bits ; count number of elements with i 'th bit set ; Add " count ▁ * ▁ ( n ▁ - ▁ count ) ▁ * ▁ 2" to the answer ... ( n - count = unset bit count ) ; Driver prorgram"
How can the above be solved in Java?

import java . io . * ; class GFG { static int sumBitDifferences ( int arr [ ] , int n ) { for ( int i = 0 ; i < 32 ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) if ( ( arr [ j ] & ( 1 << i ) ) != 0 ) count ++ ; ans += ( count * ( n - count ) * 2 ) ; } return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 5 } ; int n = arr . length ; System . out . println ( sumBitDifferences ( arr , n ) ) ; } }


"Sum of bit differences among all pairs | package whatever do not write package name here ; int diff = 0 ; hold the ans ; XOR toggles the bits and will form a number that will have set bits at the places where the numbers bits differ eg : 010 ^ 111 = 101. . . diff of bits = count of 1 's = 2 ; when i == j ( same numbers ) the xor would be 0 , thus our ans will remain unaffected as ( 2 * 0 = 0 ) ; Kernighan algo ; int count = 0 ; ` count ` stores the total bits set in ` n ` ; n = n & ( n - 1 ) ; clear the least significant bit set"
How can the above be solved in Java?

import java . io . * ; class GFG { static int sumBitDiff ( int [ ] arr ) { for ( int i = 0 ; i < arr . length ; i ++ ) { for ( int j = i ; j < arr . length ; j ++ ) { int xor = arr [ i ] ^ arr [ j ] ; diff += 2 * count ; } } return diff ; } static int countSetBits ( int n ) { while ( n != 0 ) { count ++ ; } return count ; } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 10 } ; int ans = sumBitDiff ( arr ) ; System . out . println ( ans ) ; } }


"Sum of bit differences for numbers from 0 to N | Set 2 | Java program to find the sum of bit differences between consecutive numbers from 0 to N using recursion ; Recursive function to find sum of different bits between consecutive numbers from 0 to N ; Base case ; Calculate the Nth term ; Driver Code ; Given number ; Function call"
How can the above be solved in Java?

class GFG { static int totalCountDifference ( int n ) { if ( n == 1 ) return 1 ; return n + totalCountDifference ( n / 2 ) ; } public static void main ( String [ ] args ) { int N = 5 ; System . out . println ( totalCountDifference ( N ) ) ; } }


"Sum of bitwise AND of all possible subsets of given set | Java program to calculate sum of Bit - wise and sum of all subsets of an array ; assuming representation of each element is in 32 bit ; iterating array element ; Counting the set bit of array in ith position ; counting subset which produce sum when particular bit position is set . ; multiplying every position subset with 2 ^ i to count the sum . ; Drivers code"
How can the above be solved in Java?

class GFG { static final int BITS = 32 ; static int andSum ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < BITS ; i ++ ) { int countSetBits = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) != 0 ) countSetBits ++ ; } int subset = ( 1 << countSetBits ) - 1 ; subset = ( subset * ( 1 << i ) ) ; ans += subset ; } return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 } ; int size = 3 ; System . out . println ( andSum ( arr , size ) ) ; } }


"Sum of bitwise AND of all subarrays | Java program to find sum of bitwise AND of all subarrays ; Function to find the sum of bitwise AND of all subarrays ; variable to store the final sum ; multiplier ; variable to check if counting is on ; variable to store the length of the subarrays ; loop to find the contiguous segments ; updating the multiplier ; returning the sum ; Driver Code"
How can the above be solved in Java?

class GFG { static int findAndSum ( int [ ] arr , int n ) { int sum = 0 ; int mul = 1 ; for ( int i = 0 ; i < 30 ; i ++ ) { boolean count_on = false ; int l = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) if ( count_on ) l ++ ; else { count_on = true ; l ++ ; } else if ( count_on ) { sum += ( ( mul * l * ( l + 1 ) ) / 2 ) ; count_on = false ; l = 0 ; } } if ( count_on ) { sum += ( ( mul * l * ( l + 1 ) ) / 2 ) ; count_on = false ; l = 0 ; } mul *= 2 ; } return sum ; } public static void main ( String [ ] args ) { int [ ] arr = { 7 , 1 , 1 , 5 } ; int n = arr . length ; System . out . println ( findAndSum ( arr , n ) ) ; } }


"Sum of both diagonals of a spiral odd | Java program to find sum of diagonals of spiral matrix ; function returns sum of diagonals ; as order should be only odd we should pass only odd - integers ; Driver program to test"
How can the above be solved in Java?

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


"Sum of common divisors of two numbers A and B | Java implementation of above approach ; Function to calculate gcd of two numbers ; Function to calculate all common divisors of two given numbers a , b -- > input integer numbers ; find gcd of a , b ; Find the sum of divisors of n . ; if ' i ' is factor of n ; check if divisors are equal ; Driver program to run the case"
How can the above be solved in Java?

import java . io . * ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int sumcommDiv ( int a , int b ) { int n = gcd ( a , b ) ; int sum = 0 ; for ( int i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) sum += i ; else sum += ( n / i ) + i ; } } return sum ; } public static void main ( String [ ] args ) { int a = 10 , b = 15 ; System . out . println ( " Sum ▁ = ▁ " + sumcommDiv ( a , b ) ) ; } }


"Sum of common divisors of two numbers A and B | Java implementation of above approach ; print the sum of common factors ; sum of common factors ; iterate from 1 to minimum of a and b ; if i is the common factor of both the numbers ; Driver code ; print the sum of common factors"
How can the above be solved in Java?

import java . io . * ; class GFG { static int sum ( int a , int b ) { int sum = 0 ; for ( int i = 1 ; i <= Math . min ( a , b ) ; i ++ ) if ( a % i == 0 && b % i == 0 ) sum += i ; return sum ; } public static void main ( String [ ] args ) { int A = 10 , B = 15 ; System . out . print ( " Sum ▁ = ▁ " + sum ( A , B ) ) ; } }


"Sum of consecutive bit differences of first N non | Java program for the above problem ; Recursive function to count the sum of bit differences of numbers from 1 to pow ( 2 , ( i + 1 ) ) - 1 ; base cases ; Recursion call if the sum of bit difference of numbers around i are not calculated ; return the sum of bit differences if already calculated ; Function to calculate the sum of bit differences up to N ; nearest smaller power of 2 ; remaining numbers ; calculate the count of bit diff ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int a [ ] = new int [ 65 ] ; static int Count ( int i ) { if ( i == 0 ) return 1 ; else if ( i < 0 ) return 0 ; if ( a [ i ] == 0 ) { a [ i ] = ( i + 1 ) + 2 * Count ( i - 1 ) ; return a [ i ] ; } else return a [ i ] ; } static int solve ( int n ) { int i , sum = 0 ; while ( n > 0 ) { i = ( int ) ( Math . log ( n ) / Math . log ( 2 ) ) ; n = n - ( int ) Math . pow ( 2 , i ) ; sum = sum + ( i + 1 ) + Count ( i - 1 ) ; } return sum ; } public static void main ( String [ ] args ) { int n = 7 ; System . out . println ( solve ( n ) ) ; } }


"Sum of cost of all paths to reach a given cell in a Matrix | Java implementation to find the sum of cost of all paths to reach ( M , N ) ; Function for computing combination ; Function to find the factorial of N ; Loop to find the factorial of a given number ; Function for coumputing the sum of all path cost ; Loop to find the contribution of each ( i , j ) in the all possible ways ; Count number of times ( i , j ) visited ; Add the contribution of grid [ i ] [ j ] in the result ; Driver code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int Col = 3 ; static int nCr ( int n , int r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } static int fact ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } static int sumPathCost ( int grid [ ] [ ] , int m , int n ) { int sum = 0 , count ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { count = nCr ( i + j , i ) * nCr ( m + n - i - j , m - i ) ; sum += count * grid [ i ] [ j ] ; } } return sum ; } public static void main ( String [ ] args ) { int m = 2 ; int n = 2 ; int grid [ ] [ ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; System . out . println ( sumPathCost ( grid , m , n ) ) ; } }


"Sum of decimal equivalents of binary node values in each level of a Binary Tree | Java program for the above approach ; Structure of a Tree Node ; Function to convert binary number to its equivalent decimal value ; Function to calculate sum of decimal equivalent of binary numbers of node values present at each level ; Push root node into queue ; Connect nodes at the same level to form a binary number ; Append the value of the current node to eachLvl ; Insert the Left child to queue , if its not NULL ; Insert the Right child to queue , if its not NULL ; Decrement length by one ; Stores the front element of the queue ; Add decimal equivalent of the binary number formed on the current level to ans ; Finally print ans ; Driver Code ; Given Tree ; Function Call"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . LinkedList ; import java . util . Queue ; class GFG { static class TreeNode { int val ; TreeNode left , right ; public TreeNode ( int key ) { val = key ; left = right = null ; } } static int convertBinaryToDecimal ( ArrayList < Integer > arr ) { int ans = 0 ; for ( int i : arr ) ans = ( ans << 1 ) | i ; return ans ; } static void decimalEquilvalentAtEachLevel ( TreeNode root ) { int ans = 0 ; Queue < TreeNode > que = new LinkedList < > ( ) ; que . add ( root ) ; while ( true ) { int length = que . size ( ) ; if ( length == 0 ) break ; ArrayList < Integer > eachLvl = new ArrayList < > ( ) ; while ( length > 0 ) { TreeNode temp = que . poll ( ) ; eachLvl . add ( temp . val ) ; if ( temp . left != null ) que . add ( temp . left ) ; if ( temp . right != null ) que . add ( temp . right ) ; length -= 1 ; } ans += convertBinaryToDecimal ( eachLvl ) ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { TreeNode root = new TreeNode ( 0 ) ; root . left = new TreeNode ( 1 ) ; root . right = new TreeNode ( 0 ) ; root . left . left = new TreeNode ( 0 ) ; root . left . right = new TreeNode ( 1 ) ; root . right . left = new TreeNode ( 1 ) ; root . right . right = new TreeNode ( 1 ) ; decimalEquilvalentAtEachLevel ( root ) ; } }


"Sum of decomposition values of all suffixes of an Array | Java implementation to find the sum of Decomposition values of all suffixes of an array ; Function to find the decomposition values of the array ; Stack ; Variable to maintain min value in stack ; Loop to iterate over the array ; Condition to check if the stack is empty ; Condition to check if the top of the stack is greater than the current element ; Loop to pop the element out ; The size of the stack is the max no of subarrays for suffix till index i from the right ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int decompose ( Vector < Integer > S ) { Stack < Integer > s = new Stack < Integer > ( ) ; int N = S . size ( ) ; int ans = 0 ; int nix = Integer . MAX_VALUE ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( s . isEmpty ( ) ) { s . add ( S . get ( i ) ) ; nix = S . get ( i ) ; } else { if ( S . get ( i ) < s . peek ( ) ) { s . add ( S . get ( i ) ) ; nix = Math . min ( nix , S . get ( i ) ) ; } else { int val = S . get ( i ) ; while ( ! s . isEmpty ( ) && val >= s . peek ( ) ) { s . pop ( ) ; } nix = Math . min ( nix , S . get ( i ) ) ; s . add ( nix ) ; } } ans += s . size ( ) ; } return ans ; } public static void main ( String args [ ] ) { Vector < Integer > S = new Vector < Integer > ( ) ; S . add ( 9 ) ; S . add ( 6 ) ; S . add ( 9 ) ; S . add ( 35 ) ; System . out . println ( decompose ( S ) ) ; } }


"Sum of dependencies in a graph | Java program to find the sum of dependencies ; To add an edge ; find the sum of all dependencies ; just find the size at each vector 's index ; Driver method"
How can the above be solved in Java?

import java . util . Vector ; class Test { static void addEdge ( Vector < Integer > adj [ ] , int u , int v ) { adj [ u ] . addElement ( ( v ) ) ; } static int findSum ( Vector < Integer > adj [ ] , int V ) { int sum = 0 ; for ( int u = 0 ; u < V ; u ++ ) sum += adj [ u ] . size ( ) ; return sum ; } public static void main ( String [ ] args ) { int V = 4 ; @ SuppressWarnings ( " unchecked " ) Vector < Integer > adj [ ] = new Vector [ V ] ; for ( int i = 0 ; i < adj . length ; i ++ ) { adj [ i ] = new Vector < > ( ) ; } addEdge ( adj , 0 , 2 ) ; addEdge ( adj , 0 , 3 ) ; addEdge ( adj , 1 , 3 ) ; addEdge ( adj , 2 , 3 ) ; System . out . println ( " Sum ▁ of ▁ dependencies ▁ is ▁ " + findSum ( adj , V ) ) ; } }