Divisors of n | Java program to count number of divisors of n ^ 2 which are not divisible by divisor of n ; Function to count divisors of n ^ 2 having no factors of ' n ' ; Increment count of i - th prime divisor ; Find next prime divisor ; Increment count if divisor still remains ; Initialize variable for counting the factors of n ^ 2 and n as ans1 and ans2 respectively ; Range based for - loop ; Use formula as discussed in above ; return the difference of answers ; Driver code
import java . util . * ; class GFG { static int factors ( int n ) { HashMap < Integer , Integer > prime = new HashMap < Integer , Integer > ( ) ; for ( int i = 2 ; i <= Math . sqrt ( n ) ; ++ i ) { while ( n % i == 0 ) { if ( prime . containsKey ( i ) ) { prime . put ( i , prime . get ( i ) + 1 ) ; } else { prime . put ( i , 1 ) ; } n = n / i ; } } if ( n > 2 ) { if ( prime . containsKey ( n ) ) { prime . put ( n , prime . get ( n ) + 1 ) ; } else { prime . put ( n , 1 ) ; } } int ans1 = 1 , ans2 = 1 ; for ( Map . Entry < Integer , Integer > it : prime . entrySet ( ) ) { ans1 *= 2 * it . getValue ( ) + 1 ; ans2 *= it . getValue ( ) + 1 ; } return ans1 - ans2 ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( factors ( n ) ) ; n = 8 ; System . out . println ( factors ( n ) ) ; } }