Sum of all proper divisors of natural numbers in an array | JavaScript 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
let MAX = 100001 ; class pair { constructor ( f , s ) { this . F = f ; this . S = s ; } } let factors = new Array ( MAX ) ; function sieveOfEratothenese ( ) { let isPrime = new Array ( MAX ) ; for ( let i = 0 ; i < MAX ; i ++ ) { isPrime [ i ] = true ; } isPrime [ 0 ] = isPrime [ 1 ] = false ; for ( let i = 2 ; i < MAX ; i ++ ) { if ( isPrime [ i ] ) { for ( let j = i ; j < MAX ; j += i ) { let k , l ; isPrime [ j ] = false ; for ( k = j , l = 0 ; k % i == 0 ; l ++ , k = Math . floor ( k / i ) ) ; factors [ j ] . push ( new pair ( i , l ) ) ; } } } } function sumOfProperDivisors ( num ) { let mul = 1 ; for ( let i = 0 ; i < factors [ num ] . length ; i ++ ) mul *= Math . floor ( ( Math . pow ( factors [ num ] [ i ] . F , factors [ num ] [ i ] . S + 1 ) - 1 ) / ( factors [ num ] [ i ] . F - 1 ) ) ; return mul - num ; } for ( let i = 0 ; i < MAX ; i ++ ) factors [ i ] = [ ] ; sieveOfEratothenese ( ) ; let arr = [ 8 , 13 , 24 , 36 , 59 , 75 , 91 ] ; for ( let i = 0 ; i < arr . length ; i ++ ) document . write ( sumOfProperDivisors ( arr [ i ] ) + " " ) ; document . write ( " " ) ;