Wasteful Numbers | Javascript implementation for the above approach ; Array to store all prime less than and equal to MAX . ; Function for Sieve of Sundaram ; Boolean Array ; Mark all numbers which do not generate prime number by 2 * i + 1 ; Since 2 is a prime number ; Print remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Function that returns true if n is a Wasteful number ; Count digits in original number ; Count all digits in prime factors of N pDigit is going to hold this value . ; Count powers of p in n ; If primes [ i ] is a prime factor , ; Count the power of prime factors ; Add its digits to pDigit ; Add digits of power of prime factors to pDigit . ; If n != 1 then one prime factor still to be summed up ; If digits in prime factors is more than digits in original number then return true . Else return false . ; Function to print Wasteful Number before N ; Iterate till N and check if i is wastefull or not ; Precompute prime numbers upto 10 ^ 6 ; Function Call
let MAX = 10000 ; let primes = [ ] ; function sieveSundaram ( ) { let marked = Array . from ( { length : MAX / 2 + 1 } , ( _ , i ) => 0 ) ; for ( let i = 1 ; i <= Math . floor ( ( Math . sqrt ( MAX ) - 1 ) / 2 ) ; i ++ ) { for ( let j = ( i * ( i + 1 ) ) << 1 ; j <= Math . floor ( 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 isWasteful ( n ) { if ( n == 1 ) return false ; let original_no = n ; let sumDigits = 0 ; while ( original_no > 0 ) { sumDigits ++ ; original_no = Math . floor ( original_no / 10 ) ; } let pDigit = 0 , count_exp = 0 , p = 0 ; for ( let i = 0 ; primes [ i ] <= Math . floor ( n / 2 ) ; i ++ ) { while ( n % primes [ i ] == 0 ) { p = primes [ i ] ; n = Math . floor ( n / p ) ; count_exp ++ ; } while ( p > 0 ) { pDigit ++ ; p = Math . floor ( p / 10 ) ; } while ( count_exp > 1 ) { pDigit ++ ; count_exp = Math . floor ( count_exp / 10 ) ; } } if ( n != 1 ) { while ( n > 0 ) { pDigit ++ ; n = Math . floor ( n / 10 ) ; } } return ( pDigit > sumDigits ) ; } function Solve ( N ) { for ( let i = 1 ; i < N ; i ++ ) { if ( isWasteful ( i ) ) { document . write ( i + " " ) ; } } } sieveSundaram ( ) ; let N = 10 ; Solve ( N ) ;