Find the count of Smith Brothers Pairs in a given Array | JavaScript program for the above approach ; array to store all prime less than and equal to MAX ; utility function for sieve of sundaram ; Main logic of Sundaram . ; Since 2 is a prime number ; only primes are selected ; Function to check whether a number is a smith number . ; Find sum the digits of prime factors of n ; add its digits of prime factors to pDigitSum . ; one prime factor is still to be summed up ; Now sum the digits of the original number ; return the answer ; Function to check if X and Y are a Smith Brother Pair ; Function to find pairs from array ; Iterate through all pairs ; Increment count if there is a smith brother pair ; Preprocessing ; Input ; Function call
let MAX = 10000 ; let primes = new Array ( ) ; function sieveSundaram ( ) { let marked = Array . from ( { length : MAX / 2 + 100 } , ( _ , i ) => 0 ) ; for ( let i = 1 ; i <= ( Math . floor ( Math . sqrt ( MAX ) - 1 ) ) / 2 ; i ++ ) for ( let j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) marked [ j ] = true ; primes . push ( 2 ) ; for ( let i = 1 ; i <= Math . floor ( MAX / 2 ) ; i ++ ) if ( marked [ i ] == false ) primes . push ( 2 * i + 1 ) ; } function isSmith ( n ) { let original_no = n ; let pDigitSum = 0 ; for ( let i = 0 ; primes [ i ] <= Math . floor ( n / 2 ) ; i ++ ) { while ( n % primes [ i ] == 0 ) { let p = primes [ i ] ; n = Math . floor ( n / p ) ; while ( p > 0 ) { pDigitSum += ( p % 10 ) ; p = Math . floor ( p / 10 ) ; } } } if ( n != 1 && n != original_no ) { while ( n > 0 ) { pDigitSum = pDigitSum + n % 10 ; n = Math . floor ( n / 10 ) ; } } let sumDigits = 0 ; while ( original_no > 0 ) { sumDigits = sumDigits + original_no % 10 ; original_no = Math . floor ( original_no / 10 ) ; } return ( pDigitSum == sumDigits ) ; } function isSmithBrotherPair ( X , Y ) { return isSmith ( X ) && isSmith ( Y ) && Math . abs ( X - Y ) == 1 ; } function countSmithBrotherPairs ( A , N ) { let count = 0 ; for ( let i = 0 ; i < N ; i ++ ) for ( let j = i + 1 ; j < N ; j ++ ) { if ( isSmithBrotherPair ( A [ i ] , A [ j ] ) ) count ++ ; } return count ; } sieveSundaram ( ) ; let A = [ 728 , 729 , 28 , 2964 , 2965 ] ; let N = A . length ; document . write ( countSmithBrotherPairs ( A , N ) ) ;