text: Nearest prime less than given number n | Function to return nearest prime number ; All prime numbers are odd except two ; It will only be executed when n is 3 ; Driver Code
code: function prime ( n ) { if ( n & 1 ) n -= 2 ; else n -- ; let i , j ; for ( i = n ; i >= 2 ; i -= 2 ) { if ( i % 2 == 0 ) continue ; for ( j = 3 ; j <= Math . sqrt ( i ) ; j += 2 ) { if ( i % j == 0 ) break ; } if ( j > Math . sqrt ( i ) ) return i ; } return 2 ; } let n = 17 ; document . write ( prime ( n ) ) ;