Sum of GCD of all numbers upto N with N itself | Java program to find the Sum of GCD of all integers up to N with N itself ; Function to Find Sum of GCD of each numbers ; Consider all prime factors of no . and subtract their multiples from result ; Check if p is a prime factor ; If yes , then update no and result ; If no has a prime factor greater than Math . sqrt ( n ) then at - most one such prime factor exists ; Return the result ; Finding GCD of pairs ; Calculate the divisors ; Return count of numbers from 1 to N with GCD d with N ; Check if d1 and d2 are equal then skip this ; Driver code
class GFG { static int getCount ( int d , int n ) { int no = n / d ; int result = no ; for ( int p = 2 ; p * p <= no ; ++ p ) { if ( no % p == 0 ) { while ( no % p == 0 ) no /= p ; result -= result / p ; } } if ( no > 1 ) result -= result / no ; return result ; } static int sumOfGCDofPairs ( int n ) { int res = 0 ; for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { int d1 = i ; int d2 = n / i ; res += d1 * getCount ( d1 , n ) ; if ( d1 != d2 ) res += d2 * getCount ( d2 , n ) ; } } return res ; } public static void main ( String [ ] args ) { int n = 12 ; System . out . print ( sumOfGCDofPairs ( n ) ) ; } }