Divisors 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
function factors ( n ) { let prime = new Map ( ) ; for ( let i = 2 ; i <= Math . sqrt ( n ) ; ++ i ) { while ( n % i == 0 ) { if ( prime . has ( i ) ) { prime . set ( i , prime . get ( i ) + 1 ) ; } else { prime . set ( i , 1 ) ; } n = Math . floor ( n / i ) ; } } if ( n > 2 ) { if ( prime . has ( n ) ) { prime . set ( n , prime . get ( n ) + 1 ) ; } else { prime . set ( n , 1 ) ; } } let ans1 = 1 , ans2 = 1 ; for ( let [ key , value ] of prime . entries ( ) ) { ans1 *= 2 * value + 1 ; ans2 *= value + 1 ; } return ans1 - ans2 ; } let n = 5 ; document . write ( factors ( n ) + " " ) ; n = 8 ; document . write ( factors ( n ) + " " ) ;