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
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 ) ) ; } }