Stella Octangula Number | Returns value of n * ( 2 * n * n - 1 ) ; Finds if a value of f ( n ) is equal to x where n is in interval [ low . . high ] ; Returns true if x is Stella Octangula Number . Else returns false . ; Find ' high ' for binary search by repeated doubling ; If condition is satisfied for a power of 2. ; Call binary search ; Driver code
function f ( n ) { return n * ( 2 * n * n - 1 ) ; } function binarySearch ( low , high , x ) { while ( low <= high ) { let mid = ( low + high ) / 2 ; if ( f ( mid ) < x ) low = mid + 1 ; else if ( f ( mid ) > x ) high = mid - 1 ; else return true ; } return false ; } function isStellaOctangula ( x ) { if ( x == 0 ) return true ; let i = 1 ; while ( f ( i ) < x ) i = i * 2 ; if ( f ( i ) == x ) return true ; return binarySearch ( i / 2 , i , x ) ; } let n = 51 ; if ( isStellaOctangula ( n ) ) document . write ( " " ) ; else document . write ( " " ) ;