Check if any permutation of a large number is divisible by 8 | Function to check if any permutation of a large number is divisible by 8 ; Less than three digit number can be checked directly . ; check for the reverse of a number ; Stores the Frequency of characters in the n . ; Iterates for all three digit numbers divisible by 8 ; stores the frequency of all single digit in three - digit number ; check if the original number has the digit ; when all are checked its not possible ; Utility reverse function ; Driver Code
function solve ( n , l ) { if ( l < 3 ) { if ( parseInt ( n ) % 8 === 0 ) return true ; n = reverse ( n ) ; if ( parseInt ( n ) % 8 === 0 ) return true ; return false ; } var hash = new Array ( 10 ) . fill ( 0 ) ; for ( var i = 0 ; i < l ; i ++ ) hash [ parseInt ( n [ i ] ) - 0 ] ++ ; for ( var i = 104 ; i < 1000 ; i += 8 ) { var dup = i ; var freq = new Array ( 10 ) . fill ( 0 ) ; freq [ parseInt ( dup % 10 ) ] ++ ; dup = dup / 10 ; freq [ parseInt ( dup % 10 ) ] ++ ; dup = dup / 10 ; freq [ parseInt ( dup % 10 ) ] ++ ; dup = i ; if ( freq [ parseInt ( dup % 10 ) ] > hash [ parseInt ( dup % 10 ) ] ) continue ; dup = dup / 10 ; if ( freq [ parseInt ( dup % 10 ) ] > hash [ parseInt ( dup % 10 ) ] ) continue ; dup = dup / 10 ; if ( freq [ parseInt ( dup % 10 ) ] > hash [ parseInt ( dup % 10 ) ] ) continue ; return true ; } return false ; } function reverse ( input ) { var a = input . split ( " " ) ; var l , r = 0 ; r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { var temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return a . join ( " " ) ; } var number = " " ; var l = number . length ; if ( solve ( number , l ) ) document . write ( " " ) ; else document . write ( " " ) ;